0% found this document useful (0 votes)
4 views

24 B.SC(CS) C LAN UNIT 1,2

The document provides an introduction to computers and programming, detailing the key components of a computer, including hardware and software, as well as the programming process. It explains the types of programming languages, the functions of computers, and the distinctions between system and application software. Additionally, it covers the roles of compilers and interpreters in code translation, and discusses machine language and its characteristics.

Uploaded by

kandamadhuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

24 B.SC(CS) C LAN UNIT 1,2

The document provides an introduction to computers and programming, detailing the key components of a computer, including hardware and software, as well as the programming process. It explains the types of programming languages, the functions of computers, and the distinctions between system and application software. Additionally, it covers the roles of compilers and interpreters in code translation, and discusses machine language and its characteristics.

Uploaded by

kandamadhuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

UNIT-1

CHAPTER 1

Introductions to Computers and Programming


Computers are electronic devices that can accept data as input, process it according to a set of
instructions, and produce output. They have become an integral part of our daily lives, from the
smartphones we carry to the complex systems that run our businesses and governments.

Programming is the process of creating a set of instructions that a computer can follow to perform
a specific task. These instructions are written in a language that the computer can understand,
known as a programming language.
Key Components of a Computer

1. Hardware: The physical components of a computer, such as the CPU, RAM, storage
devices, and input/output devices.

2. Software: The programs and applications that run on a computer, including the operating
system, software applications, and programming languages.
Types of Programming Languages

Programming languages can be broadly classified into two categories:

1. Low-level languages: These languages are closer to the machine level and require a deep
understanding of computer architecture. Examples include assembly language.

2. High-level languages: These languages are more human-readable and easier to learn. They
are often used for general-purpose programming. Examples include Python, Java, C++,
and JavaScript.
The Programming Process

1. Problem Definition: Clearly define the problem to be solved.

2. Algorithm Design: Develop a step-by-step procedure to solve the problem.

3. Coding: Write the code in a chosen programming language.

4. Testing: Test the code to ensure it works as expected and identify and fix any errors.

5. Debugging: The process of finding and fixing errors in the code.

6. Maintenance: Update and maintain the code over time to address new requirements or fix
bugs.

Basic Block Diagram of a Computer


A computer system can be represented by a simplified block diagram, illustrating the main
components and their interactions. Here's a basic representation:
Various components of computer
Key Components and Their Functions:

1. Input Units:
• Function: These devices allow users to enter data and instructions into the
computer.

Examples:

• Keyboard: For typing text and entering commands.

• Mouse: For navigating the user interface and selecting objects.

• Scanner: For digitizing images and documents.

• Microphone: For capturing audio input.

• Webcam: For capturing videos and images.

• Touchscreen: For direct interaction with the computer's display...

2. Central Processing Unit (CPU):


• Function: The "brain" of the computer, responsible for executing instructions
and performing calculations.
• Components:
▪ Control Unit (CU): Directs the operation of the processor, fetching
instructions, decoding them, and sending signals to other components.
▪ Arithmetic Logic Unit (ALU): Performs arithmetic (addition, subtraction,
multiplication, division) and logical (AND, OR, NOT) operations.

• Registers: Temporary storage locations within the CPU for holding data and
instructions during processing.
3. Memory:
• Function: Stores data and instructions temporarily or permanently.
Types:

• RAM (Random Access Memory): Volatile memory used for temporary storage of
data and programs currently in use.

• ROM (Read Only Memory): Non-volatile memory containing essential system


programs that cannot be modified by the user.

4. Output Units:
• Function: Display the results of the computer's processing.

• Examples: Monitor, printer, speakers.

5. Storage Devices:
• Function: Store data and programs permanently.
• Examples: Hard disk drives (HDDs), solid-state drives (SSDs), optical drives (CD/DVD),
USB drives.

Functions of various computers


Computers, in their essence, perform four fundamental functions:

1. Input: This is the process of receiving data from the outside world. It involves devices like
keyboards, mice, scanners, microphones, and cameras, which translate information into a
format the computer can understand.

2. Processing: This is where the computer takes the input data and manipulates it according
to a set of instructions (a program). The Central Processing Unit (CPU) is the brain of the
computer, responsible for executing these instructions and performing calculations.

3. Output: This is the presentation of the processed data in a human-readable or machine-


readable format. Output devices include monitors, printers, speakers, and network
interfaces.
4. Storage: This involves saving data for future use. Storage devices can be primary (like
RAM, for temporary storage during operation) or secondary (like hard drives, SSDs, or
external drives, for long-term storage).

These four functions work together in a continuous cycle, allowing computers to perform a vast
array of tasks, from simple calculations to complex simulations and artificial intelligence.
The following diagram shows an example of these functions.

Concepts of Hardware and Software


Hardware and software are the two fundamental components of any computer system. They work
together to enable the computer to perform tasks and interact with users

Computer Hardware
Hardware refers to the physical components of a computer. Computer Hardware is any part of the
computer that we can touch these parts. These are the primary electronic devices used to build up
the computer. Examples of hardware in a computer are the Processor, Memory Devices, Monitor,
Printer, Keyboard, Mouse, and Central Processing Unit.

Different Types of Computer Hardware

• Input Devices: Input Devices are those devices through which a user enters data and
information into the computer or simply, User interacts with the Computer. Examples of
Input Devices are Keyboard, Mouse, Scanner, etc.

• Output Devices: Output Devices are devices that are used to show the result of the task
performed by the user. Examples of Output Devices are Monitors, Printers, Speakers, etc.
• Storage Devices: Storage Devices are devices that are used for storing data and they are
also known as Secondary Storage Data. Examples of Storage Devices are CDs, DVDs,
Hard Disks, etc.

• Internal Component: Internal Components consist of important hardware devices present


in the System. Examples of Internal Components are the CPU, Motherboard, etc.

Computer Software
Software is a collection of instructions, procedures, and documentation that performs different
tasks on a computer system. We can say also Computer Software is a programming code executed
on a computer processor. The code can be machine-level code or code written for an operating
system.

Examples of software are MS- Word, Excel, PowerPoint, Google Chrome, Photoshop, MySQL,
etc.
Different Types of Computer Software

• System Software: System Software is a component of Computer Software that directly


operates with Computer Hardware which has the work to control the Computer’s Internal
Functioning and also takes responsibility for controlling Hardware Devices such as
Printers, Storage Devices, etc. Types of System Software include Operating Systems,
Language processors, and Device Drivers.

• Application Software: Application Software is the software that works the basic
operations of the computer. It performs a specific task for users. Application Software
includes Word Processors, Spreadsheets, etc. Types of Application software include
General Purpose Software, Customized Software, etc.

Types of software

Software
In a computer system, the software is basically a set of instructions or commands that tell a
computer what to do. In other words, the software is a computer program that provides a set of
instructions to execute a user’s commands and tell the computer what to do. For example
like MS-Word, MS-Excel, PowerPoint, etc.

Types of Software
It is a collection of data that is given to the computer to complete a particular task. The chart
below describes the types of software:
Above is the diagram of types of software. Now we will briefly describe each type and its subtypes:

1. System Software
• Operating System

• Language Processor

• Device Driver

2. Application Software
• General Purpose Software

• Customize Software

• Utility Software

System Software
System software is software that directly operates the computer hardware and provides the basic
functionality to the users as well as to the other software to operate smoothly. Or in other words,
system software basically controls a computer’s internal functioning and also controls hardware
devices such as monitors, printers, and storage devices, etc. It is like an interface between hardware
and user applications, it helps them to communicate with each other because hardware understands
machine language(i.e. 1 or 0) whereas user applications are work in human-readable languages
like English, Hindi, German, etc. so system software converts the human-readable language into
machine language and vice versa.
Types of System Software
It has two subtypes which are:
1. Operating System: It is the main program of a computer system. When the computer
system ON it is the first software that loads into the computer’s memory. Basically, it
manages all the resources such as computer memory, CPU, printer, hard disk, etc., and
provides an interface to the user, which helps the user to interact with the computer system.
It also provides various services to other computer software. Examples of operating
systems are Linux, Apple macOS, Microsoft Windows, etc.

2. Language Processor: As we know that system software converts the human-readable


language into a machine language and vice versa. So, the conversion is done by the
language processor. It converts programs written in high-level programming
languages like Java, C, C++, Python, etc(known as source code), into sets of instructions
that are easily readable by machines(known as object code or machine code).

3. Device Driver: A device driver is a program or software that controls a device and helps
that device to perform its functions. Every device like a printer, mouse, modem, etc. needs
a driver to connect with the computer system eternally. So, when you connect a new device
with your computer system, first you need to install the driver of that device so that your
operating system knows how to control or manage that device.

Application Software
Software that performs special functions or provides functions that are much more than the basic
operation of the computer is known as application software. Or in other words, application
software is designed to perform a specific task for end-users. It is a product or a program that is
designed only to fulfill end-users’ requirements. It includes word processors, spreadsheets,
database management, inventory, payroll programs, etc.

Types of Application Software


There are different types of application software and those are:

1. General Purpose Software: This type of application software is used for a variety of tasks and
it is not limited to performing a specific task only. For example, MS-Word, MS-Excel,
PowerPoint, etc.

2. Customized Software: This type of application software is used or designed to perform specific
tasks or functions or designed for specific organizations. For example, railway reservation
system, airline reservation system, invoice management system, etc.

3. Utility Software: This type of application software is used to support the computer
infrastructure. It is designed to analyze, configure, optimize and maintains the system, and take
care of its requirements as well. For example, antivirus, disk fragmenter, memory tester, disk
repair, disk cleaners, registry cleaners, disk space analyzer, etc.
Compiler and Interpreter
Compilers and Interpreters: The Translators of Code

In the world of programming, computers can't directly understand the code we write. They need it
to be translated into machine code, a low-level language of 0s and 1s. This is where compilers and
interpreters come into play.

Compiler

Definition: A compiler is like a translator that translates the entire source code (the code
written by the programmer) into machine code in one go, before the program is executed.

Process:

1. Source Code: The programmer writes the code in a high-level language (like C,
C++, Java).

2. Compilation: The compiler analyzes the entire source code, checks for errors, and
translates it into machine code (also known as object code or executable file).

3. Execution: The computer then executes the generated machine code.

Compiler process

Advantages:

• Faster Execution: Compiled programs generally execute much faster than interpreted
ones because the translation process is completed beforehand.

• Better Performance: Compilers can perform optimizations on the code during the
compilation process, resulting in more efficient machine code.

• Platform Independence (to some extent): Compiled code can sometimes be made to run
on different platforms with minimal modifications.

Disadvantages:
• Slower Development Cycle: The entire program needs to be recompiled after every code
change, which can be time-consuming.
• Difficult Debugging: Identifying and fixing errors can be more challenging as the
compiler might report errors after the entire program has been translated.

• Platform Dependence: While some level of portability is possible, compiled code is often
tied to a specific processor architecture.

Interpreter
Definition: An interpreter, on the other hand, translates and executes the code line by line.
It doesn't create a separate machine code file.

Process:

1. Source Code: The programmer writes the code in a high-level language (like
Python, JavaScript, Ruby).

2. Interpretation: The interpreter reads the code line by line, translates it into
machine code, and executes it immediately.

3. Execution: If there's an error in a line, the interpreter stops and reports the error.

Interpreter process

Examples

• Compiler-based languages: C, C++, C#, Java (bytecode is compiled)

• Interpreter-based languages: Python, JavaScript, Ruby, PHP


Advantages:

• Faster Development: Changes to the code can be tested immediately without the need for
a lengthy compilation process.

• Easier Debugging: Errors are identified and reported line by line, making it easier to
pinpoint the source of the problem.
• Platform Independence: Interpreted code is generally more portable across different
operating systems.
Disadvantages:
• Slower Execution: Interpreted programs typically run slower than compiled ones due to
the overhead of translation during execution.

• Less Efficient: Interpreters generally cannot optimize code to the same extent as
compilers, leading to less efficient execution.

• Requires Interpreter: The interpreter program must be present on the machine to run the
interpreted code.

Concepts of Machine Level


What is Machine Language

Machine language is a low-level programming language that consists of binary bits i.e. only 0 and
1. The data present in binary form is the reason for its fast execution. In Machine language,
instructions are directly executed by the CPU. Machine language is also known as object code or
machine code. Machine language is binary language.

Machine language

How Machine Code is Created

• Assembly Language: A slightly higher-level language called assembly language uses


mnemonics (short codes) to represent machine code instructions.

• Assemblers: Special programs called assemblers translate assembly language code into
machine code.

Needs of Machine Language

As a human, we write code in high level language. The programming language which we use to
write codes such as C, C++ and java are high level languages. High level language is not
understood by computer directly so it is converted into low level machine language to understand
the meaning of code and perform execution. Computers compile the code written by us and
translate into machine code and then execute it. Computers are only able to understand machine
language.

Features of Machine Language


• Machine language is a low level language.
• Machine language consist of only 0 and 1 bits.
• Machine languages are platform dependent.

• It is nearly impossible to learn machine language for humans because it requires a lot of
memorization.

• Machine language is used to create and construct drivers as well.

Machine Language Instruction Components

Machine language consists of two instruction components :

1. Operand(s)

The operand(s) represents the data that the operation must be performed on. This data can
take various forms, depending on the processor's architecture. This can be a register
containing a value, a memory address pointing to a location in memory where the data is
stored, or a constant value embedded within the instruction itself.

2. Opcode

The opcode (Operation code) represents the operation that the processor must perform.
This indicates that the instruction is an arithmetic operation such as addition, subtraction,
multiplication, or division.

Advantages of Machine Language

• Machine languages are faster in execution because they are in binary form.

• Machine language does not need to be translated , because it is already present in simple
binary form.

• The CPU directly executes the machine language.

• The evolution of the computer system and operating system over the time period is due to
machine language.
• Machine languages are used in developing a high-grade computer system.

Disadvantages of Machine Language

• Machine language are complex to understand and memorize.

• Writing codes in machine language is time-consuming.


• It is very difficult to resolve bugs and errors present in the codes and programs.

• Codes written in machine languages are more prone to error.

• Machine languages are not easy to modify.


• Machine language are platform Independent.
Assembly language and High-level programming
Programming languages can be broadly classified into two categories: Assembly Language and
High-Level Languages.

Assembly Language:
Assembly language is a low-level programming language that provides a way for humans to
communicate directly with computer hardware. It's a step above machine code, which is the raw
binary instructions that the computer's processor understands.

• Low-level language: It's closer to machine code, the raw instructions understood by the
computer's processor.

• Uses mnemonics: Instead of binary code, it uses short abbreviations (mnemonics) to


represent machine instructions.

• Processor-specific: Assembly language instructions are specific to a particular type of


processor (e.g., x86, ARM).

• Direct hardware control: Provides fine-grained control over hardware resources like
memory and registers.
Examples: x86 assembly, ARM assembly

Advantages

• Execution of code is efficient

• Low-level operations can be performed

• High control over Hardware

Disadvantages

• More Complex
• More time consuming
• Lack of Portability
High-Level Language:

It is a machine-independent language. It enables a user to write a program in a language that


resembles English words and familiar mathematical symbols, COBOL was the first high-level
language. Examples of high-level language are python, c#, etc.

• Human-readable: Uses English-like syntax and constructs, making them easier to write
and understand.
• Platform-independent (mostly): Programs written in high-level languages can often be
compiled to run on different types of computers.
• Abstraction: Hides low-level details of the hardware, allowing programmers to focus on
the problem at hand.

• Examples: C, C++, Java, Python, JavaScript, etc.


Advantages

• Increase Readability

• Portability

• Faster Development

Disadvantages

• Slower Execution

• Memory Usage
• Less Control Over Hardware

Key Differences
Flowcharts and algorithms
Algorithm
The word Algorithm means “a process or set of rules to be followed in calculations or other
problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that define
step-by-step how a work is to be executed in order to get the expected results. Let’s take a look at
an example for a better understanding. As programmers, we are all aware of the Linear Search
program

Key Characteristics:
• Finiteness: An algorithm must eventually terminate after a finite number of steps.

• Definiteness: Each step in the algorithm must be precisely defined and unambiguous.
• Input: An algorithm may or may not take input.

• Output: An algorithm must produce an output.

• Effectiveness: Each step in the algorithm must be feasible and executable.

Flowcharts
A flowchart is a diagrammatic representation of an algorithm. It uses various shapes to
depict different types of operations and arrows to indicate the flow of control between
them.

Common Symbols:

• Oval: Represents the start or end of the flowchart.

• Rectangle: Represents a process or action.


• Diamond: Represents a decision point (e.g., a conditional statement).

• Parallelogram: Represents input or output.

Example: - Finding the Largest of Three Numbers

Algorithm:
1. Read three numbers: num1, num2, and num3.

2. If num1 is greater than num2:

If num1 is greater than num3:

▪ Largest = num1

Else:

▪ Largest = num3

3. Else:
If num2 is greater than num3:
▪ Largest = num2

Else:

▪ Largest = num3

4. Print the value of Largest.


Flowchart:
Introduction to C
Introduction: C is a general purpose programming language developed by Dennis Ritchie in 1972 at AT&T
(American Telephone and Telegraph) Bell Labs, New Jersey, U.S.A. It was developed from B (Bell),
BCPL (Basic Combined Programming Language), and ALGOL (Algorithmic Language). Father of BCPL is
“Ken Thompson”; Father of B language is “Martin Richards”.

Features of “C”:
1. C language was standardized in 1988 by ANSI (American National Standards
Institute).
2. C language program is nothing but a collection of functions, each function has a unique name
and Each Function contains Block of code which performs a particular Task. Hence C language
is called as Procedural Programming Language.
3. C is very small language with only 32 keywords.
4. Using C we can learn the Basics of Programming very easily. Learning C helps in learning
C++, Java.
5. Programs written in C are efficient and fast. This is due to its variety of Data types and powerful
Operators.
6. C is often termed as Middle level programming language, because it combines the power of a
High level language with the flexibility of Low level Languages.
7. C language rich in Built-in Functions (Library Functions).
8. Users can create their own functions and add them to C library to perform a varietyof tasks.
9. C is portable language and free form Language. C is case sensitive language(use lower case
letters).
10. C language is a structured Programming Language. (if block, for block, do block etc).

C – CHARACTER SET:
C language supports rich set of characters to define statements which are
a. Alphabets – (A to Z , a to z)
b. Numbers – (0 to 9)
c. Special Symbols – (~! @ # $ % ^ & ( ) _ -+ = | \, - * + : ; “ „ < > , . ? / …)
d. White Spaces – (space, horizontal tab, vertical tab, new line …)

Writing First „C‟ Program:
main( )
{
printf(“ Welcome to C Programming”);
}
[To write a program we need Editor Software. TurboC Editor or IDE (Integrated
Development Environment) is an Integration of several Tools]
Q) Basic Structure of C Program:
The general Structure of C language program is subdivided into different Sections.
1. Documentation Section
2. Preprocessor Directive Section
a. Link Section
b. Definition Section
3. Global Variable Declaration Section
4. main() function Section
5. Pair of Braces{ }
6. Local Variable Declaration Section
7. Executable statements
8. User Defined Functions
1. Documentation Section:
In Documentation section we give a comment. Comment statement is a non executable statement.
Comment Start by using “/*” and end with “*/” Symbols. The general Syntax is
/*Message line */.There are two types of comments. Single line comments and multi linecomments.
Examples: /* My First Program */
// My First Program
2. Preprocessor Directive Section:
These statements begin with # symbol. These statements direct the C preprocessor to include header
files and also Symbolic Constants into C program. There are two types ofPreprocessor Directives:
i. LINK SECTION: Link section is used to include the header files, which contains definition
for the standard library functions (printf,scanf,clrscr,sqrt) provided by C developers.
Example: #include<Stdio.h>
ii. DEFINITION SECTION: By using this we can define constant variables with its
values. Example: #define PI 3.14
3. Global Variable Declaration Section:
If you want to use a variable throughout the program, you need to declare variable as Global variable. If
we declare variables before main( ), then it is called Global declaration. Global variables are
automatically initialized with zero.
4. main ( ) function Section:
As the name itself indicates, it is the main function of every C program. We cannot write programs
without main() function. Execution of program starts from main ( ). It should be written in lower case
letters and should not be terminated by Semicolon. It calls other library functions.
5. Pair of Braces { }:
Every C Program uses a Pair of Curly braces. The left brace indicates beginning of main ( ), the right
brace indicates end of the main ( ).
6. Local Variable Declaration Section:
Variables which are used in main( ) program are declared by using local variable declaration
statement.These variables are available within the block only.
Ex: main( )
{
int m=45;
}
7. Executable statements:
This section has Input, Output statements, Arithmetic statements, Control Statementsand Function
calling statements.
Examples: i. printf(“Enter values for a and b:”);
ii. c=a+b;
iii. if(a>b)
8. User Defined Functions:
These are sub programs, which are called by a calling statement from main program. A
subprogram isa function; they contain a set of statements to perform a specific task. These are
written by user.
Syntax: type function name (parameters)
{
Local declaration;
Executable
statements;return
(argument);
}
Example Program: /*Simple Interest Calculation*/
#include<stdio.h>
#include<conio.h> Header File Section
main( )
{ Main Section
int p,t,r;
float si; Local Variable Declaration Section
clrscr();
Executable Part
printf(“Enter P,T,R values:”);
scanf(“%d%d%d”,&p,&t,&r);
si=(p*t*r)/100;
printf(“Simple Interest is =
%f”,si);
getch();

FILE USED IN C-PROGRAM:


Each and every file in a computer is recognized by using file extension. For example Word documents have
an extension .doc, spread sheets have an extension .xls in the same way C programs have an extension .c
Source File (code): Program Name can be any name that must contains extension C. It is also known as
source file. Example: demo. C
Compiling And Executing a C-Program:
Compiling is an operation, which translates a program written in human readable language into machine
language that can be understood by the CPU.
A compiler is itself a program that reads source files written by human and generate object file
that contains machine code. If you want to compile a c-program select compile option from compile
menu or press the key combinationctrl+F9. If any errors in your source code compiler will give you list of
errors with line number with error description.

The code available in header files is joined into your code and translated into machine code that means
objectcode contains not only your code it contains header file code also.
1. To compile the program - Alt+F9
2. To execute the program - Ctrl+F9
3. To see the output - Alt+F5
Object file (code): compiler produces an object code (.obj) if the program does not have any Errors.
Example: demo.obj
Executable file (code): After Completion of Compilation Process, executable files with .exe extension
are created. Example: demo.exe
Source Code (demo.c)
Pre-Processor Directive(H eader Files)

Expanded Source Code

Compile

Object Code (demo.obj)


Linker (Includes SystemLibraries)
Executable Code (demo.exe)

DATA TYPES in “C‟:


C language is rich in its data types. Data types are defined as the building blocks of a C program. C
languagesupports different types of data types. A data type of a variable tells us three things:
o The type of value that can be stored in a variable.
o The range of values.
o The type of operations that can be performed.
Data types are classified into Three Sections:
1. Built-in or Primary or Fundamental Data types
2. Derived Data types
3. User-defined Data types
I. Built-in Data types: The built-in data types are int, float, char, and double. These are also called as
Primary or Fundamental Data types.
Integer Data Types:
Integer data types are used to represent value without decimal point. We can represent signed values
and unsigned values. In integer category we have int, short int, long int as data types. The size and range
of integer data types described in below table.

TYPE Format Specifier SIZE RAN


GE
short int 1 byte -128 to +127
unsigned short int 1 byte 0 to 255
%d
int 2 bytes -32768 to +32767
unsigned int %u 2 bytes 0 to 65535
long int %ld 4 bytes -2,147,483,648 to +2,147,483,647
unsigned long int %lu 4 bytes 0 to 429,49,67,295

Real (float) Data Type: Floating point numbers are defined in C by the Keyword “float‟. These
data type have at least one digit with a decimal point. These are also signed or unsigned. The size and
range of float data types described in below table.
TY Format Specifier SIZE RAN
PE GE
float (6 decimal places) %f 4 bytes 3.4E-38 to 3.4E+38

double( 15 decimal %lf 8 bytes 1.7E-308 to 1.7E+308


places)
long double %lf 10 bytes 3.4E-4932 to 1.1E+4932

Character Data Type: By using character data type we can represent single character or combination
of characters called strings. Character data types are either signed or unsigned.
TYPE Format Specifier SIZE RANGE
char %c (Single) 1 byte -128 to +127
%s (String) 0 to 255
II. Derived Data type: Derived Data types are derived from the Primary data types.These are used for
representing a single value or multiple values. Arrays, Structures, Unions are some examples for
Derived types.
III. User-defined Data types: user can also declare his own types by using „typedef‟ and „enum‟ data
types.
Q) I/O Statements In „C‟:
1. In order to work with dynamic values every programming language input/output statements to read values
from standard input device and provide output to standard output device.
2. In C language there are two types of I/O statements available to work with dynamic values
a. Formatted I/O statements
b. Unformatted I/O statements
Formatted I/O Statements:
1. The functions printf() and scanf() perform formatted output and input statements.
2. They can read data and write data in various formats that you need.
3. The printf() function write data on the standard output device.
4. The scanf() function read data from the standard input device.
5. Both functions can operate on any of the built-in data types.
printf( ):
This function most commonly used function for displaying data of any type.
Syntax: printf(“formatted string” , arguments list );
Example: printf(“ %d ” , a );
Here formatted string consist of group of characters, contains symbols and formatspecifiers like %d ,
%f , %s , %c …etc.
scanf( ):This function can read all the built-in data types and automatically convertnumbers into the
proper internal format.
Syntax: scanf( “ formatted string ” , &variable_name);

&(ampersand) address operator
Example: scanf( “ %d “ , &a);
In the above statement %d represents integer value and &-ampersand represents address of memory
location of variable „a‟.
Unformatted Input and Output Statements:
getc : getc( ) is an exclusive function for reading characters.
putc :Output Writes a character into a stream
gets :Input Reads a string from keyboard. gets is an exclusive function for reading strings. Also
gets( ) function executes faster than scanf( )function. gets( ) function handles only strings
puts :output Writes string on to the screen. Puts( ) is an exclusive functionfor printing the
strings
C Tokens:
Token: Each individual unit or element in a statement is called Token. C language contains different types
of Tokens. C tokens include identifiers, keywords, variables, constants and operators.

Operators In C:
An operator is a special symbol which operates one or more operands. The data items that operators act
upon are called Operands. C language supports a rich set of Operators. Theyare categorized by several
types.
Arithmetic Operators:
Arithmetic operators are used for arithmetic operation like Addition, Subtraction, Multiplication,
Division, modulo division.
Operator Operator Name

+ Addition

- Subtraction

* Multiplication

/ Division

Modular Division
%
(remainder)

Note: The difference between division and modular division is division returns quotient where as
modular division returns reminder.
Relational Operators: These operators are used to tell the relation between two operands. The relational
operators are used to compare left hand side expression with the right hand side expression.
Operator Operator Name

> Is greater than

< Is Less than

>= Is Greater than or equal to

<= Is Less than or equal to

== Is Equal to

!= Is Not equal to

Logical Operators: These operators are used to check more than one condition at a time.

Operator Operator Name


&& logical AND
|| logical OR
! logical NOT
Bitwise Operators: These operators perform manipulations on values in a bit manner. Bitwise
Operators are used to perform operations on binary Digits (0‟s,1‟s).

Operato Operator Name


r
& bit wise AND
| bit wise OR
^ bitwise XOR
<< Left shift
>> Right shift
~ bitwise complement
Increment and Decrement Operators:
These Operators are also called as Unary Operators. These operators are used to incrementone value of
variable and decrement operator is used to decrease one value of a variable.
Operator Operator Name
++ Increment Operator
-- Decrement Operator
These operators are available in two forms.
a. Prefix Operator: Operator comes before the operand. Ex: ++a; --a;
b. Postfix Operator: Operator comes after the operand. Ex: a++; a--;
In prefix operation first increment/decrement will be done later assignment will be done. In postfix
operation first assignment will be done later increment/decrement will be done.
Assignment Operators:
Assignment Operator is used to assign values to the variables. Ex: c =a + b; in the above example the
addition result is assigned to variable C. Assignment Operator requires a variable on its left hand side,
contains an expression or avalue or another variable on its right hand side.
= Stores the value in right side variable to left hand side variable.
+= Add right hand side value to value in left hand side variable and stores in it.
-= Subtract right hand side value from value in left hand side variable and stores in it.
Multiply right hand side value with left hand side value and store the result in left hand
*=
side variable.

Conditional Operator:
Conditional operator is also called as Ternary Operator. It is used in decision making process. ? :

Syntax: condition ? True block statement: False block statement;


Ex: a>b ? printf(“a is big”) : printf(“b is big”);
If condition is true, true block statement will be executed otherwise false block statement will beexecuted.

Special Operators:
• Sizeof operator: sizeof( )
• Comma operator: ,
• Member Selection operator (dot operator): .
• Pointer operator: &,*
Q) Keywords:
Keywords are reserved words in C language. They have pre-defined meaning and are used for the
intended purpose. All keywords must be written in lowercase. (Or) Keywords (reserved words) are
defined by C compiler and each word has different meaning, these cannot use as names of variables,
functions or labels. Standard Keywords are

Identifiers:
In C-language names of variables, functions, labels and various other user-defined names or objects are
called identifiers.
Rules for defining identifiers:
1. The first character must be an alphabet or an underscore, sub-sequent characters must be either
letters, digits or underscore.
2. No space is allowed in between identifiers and no special characters are also allowed except
underscore.
3. Key Words are not allowed as identifiers.
4. There is no limit of length of an identifier but some compilers will recognize only 8 or 32
characters
Variables:
Variable is a name given to a memory location where a value is stored. Or A variable canbe thought
as a symbolic representation of address of the memory space where values can be stored, Accessed
and changed.
Initialization: The process of assigning initial values to the variable is known asinitialization.
Ex: int k=6;
Rules for variable names:
1. It can contain A-Z, a-z,0-9 and Underscore( _ ).
2. It can not start with a Digit.
3. It can not have any blanks with in a variable name.
4. Turbo C Compiler allows a maximum of 32 characters.
5. variable names can not be Keywords.
Constants: (Literals)
Constant refers to fixed values that the program cannot alter. Constants can be any of the basic data
types. Constants are also called “LITERALS”. Constants are classified into 2 basic types. They are
Numeric Constants, Character Constants.

CONSTANTS

Numeric Constants Character Constants

Single String
Integer Real
Character

Figure: Basic Types of Constants in C


I. Numeric Constants
Numeric constants, as the name itself indicates, are those which consist of numerals. They are further
divided into two types:
a. Integer Constants: A whole number is an integer constant. Integer constants do not have a
decimal point. These are further divided into three types depending on the number systems they belong
to. They are:
i. Decimal integer constants
ii. Octal integer constants
iii. Hexadecimal integer constants
Ex: 10,124, 4564,-20 etc (Decimal)
Ex: 0456,037, -0123(Octal)
Ex: 0x8E, 0x456, -0x123, 0x56A (Hexadecimal)
b. Floating Point Constants (real): Floating Point constants require the decimal point
followed by the numbers fractional component. The real constants also known as floating point
constants are written in two forms:
(i) Fractional form
(ii) Exponential form.
i. Fractional Form:

ii.Exponential Form: The exponential form offers a convenient way for writing very largeand small
8
real constant. For example, 56000000.00, which can be written as 0.56 x 10 is written as 0.56E8 or
0.56e8 in exponential form. A real constant expressed in exponential form has two parts: (i) Mantissa
part, (ii) Exponent part.
Ex: 7500000000 written as 7.5E9
II.Character Constants:
a. Single Character Constant: It is a single character enclosed in single quotes.
Each character has an ASCII value to identify.
Ex: „A‟, „@‟, „55‟,‟98‟ etc
C supports some special backslash character constants that are used in output functions.Ex: \n
(Next line), \t (Horizontal tab), \v (Vertical tab) etc.
b. String Constants: A String is a set of characters enclosed in double quotes.
Ex: “abc”, “c-language”, “Salary is 18000.00”,”2314” etc.

Type Conversion:
1. Type casting is a mechanism which is used to convert one data type value into anotherdata type
value.
2. If the operands are of different types, the lower type is automatically converted to thehigher type
before the operation proceeds.
Implicit Type Casting: It is performed by compiler. It means compiler automaticallyconverts
lower data type values into higher data type values.

int i=10;
float f;

f=i; implicit type casting
Explicit Type Casting: It means converting higher data type value into lower data type
value. Explicit type casting is performed by the programmer this means we need to write
additional code to convert higher data type value into lower data type value.

Variable = (data type) expression;


1.Example Program for Type Casting:

main( )
{
int
a,b;
float
c;
printf(“ Enter any two numbers: ”);
scanf(“ %d%d ”, &a, &b);
c= (float) a/b; //Type casting
printf(“ Quotient value = %f ”, c);
}
Example: 2
main( )
{
int p,t,r,i;
clrscr();
printf(“ Enter p,t,r values: ”);
scanf(“%d%d%d”,&p,&t,&r);
i=(int)(p*t*r)/100;
printf(“Simple Interest = %d”, i);
getch( );
}
UNIT-2
Q) Decision Control and Looping Statements (or)
Control Structures in C:
Normally statements in C program are executed sequentially i.e in the order in which they are
written. This is called sequential execution. We can transfer the control point to a desired Location
is possible with control structures. C allows many kinds of control statements.
I. Conditional (Decision) control structures
· if
· if –else
· nested if– else
· nested else-if
II. Loop
(iterative) control
structures · for
loop
· while loop
· do - while loop
III. Multi way conditional (case) control structures
· Switch- case
IV. Jumping
(branching) control
structures · goto
· break
· return
· continue
Decision Control Structures:
These are used to express decisions based on Conditions. Decision Control structuresare
classified into below types:
1. simple if statement
2. if-else statement
3. Nesting of if..else statement
4. else if ladder statement.
1. Simple if statement: (unidirectional)
In simple if, controller initially checks the condition, if the condition is true it executes the true block
statements otherwise it skips the true block statements and executes the statements after the true block
statements. Simple if is also known as Unidirectional Decision control structure. It is implemented
through the keyword „if‟. [When we need to perform a particular action when a condition gets satisfied,
then weuse Unidirectional Decision Control structure.]
Syntax:
if( condition)
{

Statement- Block;
}
statement-x;

Flow Chart:

Example 1: if(age>=18)
printf(“Eligible for Vote”);
Example 2: if(number>0)
printf(“Positive number”);

2. if else statement:(Bidirectional)
This statement has a simple condition with two different blocks one is true block and other is false
block. It is implemented through the keywords „if‟ and „else‟. [When we need to perform a particular
action when a condition gets satisfied and perform a different action if the condition is not satisfied,
then we use Bidirectional decision Control structure]. In this statement first the condition will be
checked. If the condition is „true‟, the statements associated with „if block‟ gets executed, otherwise
„else block‟gets executed.
Syntax:

if( condition)
{
True Block Statements
}
else
{
False Block Statements
}
Statement-x;

Flowchart:

Example: if(age>=18)
printf(“Eligible for Vote”);else
printf(“Not Eligible for Vote”);
3. Nesting of if-else:
When a series of decisions are involved, we may have to use more than one if, else statements in nested
form. These are used for Multi-way decision making.
Syntax:
if( condition1)
{
if( condition2)
{
True Block statements
}
else
{
False Block Statements
}
}
else
{
if( condition3)
{
True Block statements
}
else
{
False Block Statements
}
}
Flowchart:

Example:
4. Else if ladder (or) nested else if: Else if ladder statement is used to check more than one
condition on same value. The conditions are evaluated in order, if any condition is true, the statements
associated with it are executed, and terminates the whole chain. The final else block will be executed if no
true block find.
Syntax:
if(condition-1)
{
True Block - 1
}
else if(condition-2)
{
True Block - 2
}
else if(condition3)
{
True Block – 3
}
else if(condition4)
{
True Block - 4
}
else
{
default statement;
}
Example:
if(marks>=95)
{
printf(“A+ Grade”);
}
else if(marks>=85)
{
printf(“A Grade”);
}
else if(marks>=75)
{
printf(“B Grade”);
}
else if(marks>=60)
{
printf(“C Grade”);
}
else
printf(“D Grade”);
Loop Control Structures:
Loop control structures can also be called as iterative or repetitive control structures. Whenwe need to repeat
s set of instructions certain number of times, then we use loop control structures.
In C there are Three types of Loop Control Structures:
1. while Loop
2. do-while Loop
3. for Loop
I. WHILE LOOP:
1. while statement is also known as “Entry Control Loop”.
2. In this controller first check the condition, if the condition is true then controllermoves to
while block and executes the statements.
3. After completing execution of last statement controller again checks thecondition.
This process will be repeated until the condition is false.
4. In while loop it checks the condition first and executes the statements later.So minimum
number of execution times of statements is 0.

Syntax:
Initial value; while(condition)
{
Block of Statements
… Increment/decrement;
}
Statement-x;
Flowchart:

Example 1: i=1;
while(i<=40)
{
printf(“%d \t”, i);
i++;
}
Example 2:
i=1;
while(i<=10)
{
printf(“hello”); prints hello 10 times.
i++;
}
2. do-while Loop:
1. do-while loop is also called as “Exit Control Loop”.
2. In this first body of the loop is executed and then condition is checked.
3. If the condition is true then the body of the loop is executed.
4. When the condition becomes false then it will exit from the loop.
5. In do while it executes the statements first and checks the condition later. So

Syntax: initial value;


do
{
Statements

Increment/decrement

} while (condition);

Flowchart:

Example 1::
i=1;

do
{
printf(“%d \t”, i);
i++;
}while(i<=40);
Example 2:
i=1;
do
{
printf(“hello”); prints
hello 10 times.i++;
} while(i<=10);
3. for Loop: For is a looping control statement in which three expressions were present.
1. Initialization (In this the initial value of the loop is specified, where to start the loop)
2. Condition ( In this condition is specified, when to stop the loop)
3. Increment/Decrement ( In this modification statement, in each iteration how much
increment or decrement is specified)
The three expressions present in for loop are separated by using semicolon (;). Even in the
absence of any expression you need to place semicolon.
Syntax: for(initialization ; condition ; increment/decrement)
{
Statement 1;
Statement 2;

}
Flowchart:

Loop process in for loop:


1. In first iteration for loop executes initialization part and checks the condition.
2. If the condition is true it executes the block of statements then performs
increment/decrement.
3. After performing increment/decrement it checks the condition, if it returns trueexecutes
block of statements otherwise terminate the loop.

Example:
for(i=1;i<=20;i++)
{
printf(“%d \t”,i);
}
Differences Between while and do-While:
WHILE DO-WHILE
1. While loop is also called as Entry 1. Do-While loop is also called as Exit
Control Loop. Control Loop.
2. In While Loop control first checks the 2. In Do-while loop control first
condition then executes the while executes the while block statements
block statements. and then checks the condition.
3. No Semicolon at the end of condition. 3. There is a semicolon at the end of
condition.
4. Statements in while loop may or may 4. Statements in do while loop get
not get executed. Minimum executed at least once. Minimum
executions are zero executions are one
5. While(condition) 5. do
{ {
Block of statements; Block of statements;
Increment/decrement Increment/decrement
} } while(condition);
Nested Loops:
A loop inside another loop is called as nested loop. When a for statement is executed with in another for
statement, then it is called nested for statement. One for statement within another for statement is called as
Nested for loop.
Syntax: fo r (initialization; condition; incr ement/decrement)
Outer Loop
{

for (initialization ; condition ; increment/decrement)


{
Inner Loop
--------------
Statements;
-
}

}
When the control reaches the inner loop, only after the complete execution of the innerloop, the control
goes to the modification counter of the outer loop.
With in the inner loop, the outer loop counter variables value remains constant, where as theinner loop counter
variables value keeps changing.
Example:
void main( )
{
int i, j; for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf(“%d,%d\n”,i,j);
}
}
}
Output:
1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3
Jump Statements:
Whenever we need to transfer the control from one place to another place in a program thenwe use Jump
statements.
C supports three Jump Statements
1.break
2. continue
3. goto
break statement:
1. „break‟ is a keyword used to terminate the loop or exit from the block. When break statement is
encountered inside a loop, the control comes out of that loop and resumes at the next statement
following the loop.
2. Sometimes there may be a situation where we want immediate termination of a loop,bypassing the
test condition expression and any remaining statements in the body of the loop. Break statements can
be used with for, while, do-while and switch statement.
The general syntax for break statement is
as: break;

Example:
switch(n)
{
case 1: c=a+b;
break;
case 2: c=a*b;
break;
}
continue statement:
1. „continue‟ is a keyword used for continue the next iteration of the loop.
2. Unlike break which causes the loop to be terminated, the continue statement causes theloop to be
continued with the next iteration.
3. The continue statement tells the controller, “SKIP THE FOLLOWINGSTATEMENTS AND
CONTINUE WITH THE NEXT ITERATION”.
The general Syntax is for continue statement is:
continue;

Example:
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf(“%d \t”,i);
}
getch( );
}
OUTPUT: 1 2 3 4 6 7 8 9 10

goto statement: goto statement is one of the jumping statement. It is used to transfer the controller
from one location to another location in the program.
Syntax: goto can beused in any of the following forms.

label:

goto label;
goto label;

label:

Example: /* Even or Odd Number Using goto Statement*/


void main( )
{
int
n;
clrsc
r();
printf("Enter any Integer
number:");scanf("%d",&n);
if(n%2==0)
{
goto even;
}
else
{
goto odd;
}
even:printf("The given number is Even");
return;
odd:printf("The given number is Odd");

You might also like