C Programming
C Programming
TO
PROGRAMMING
UNIT-I
LECTURE NOTES
DEFINITION OF COMPUTER
Computer is fast electronic machine which can perform arithmetic and logic operations.
(OR)
Computer is a fast electronic calculating machine that accepts digitized input information,
processes it according to a list of internally stored instructions, and produces the resulting
output information.
BLOCK DIAGRAM OF COMPUTER
Founder of computer is Charles Babbage.
The block diagram of computer is
On the basis of its internal structure, a computer can be divided into three main parts.
1. Input unit.
2. CPU
3. Output unit.
1. INPUT UNIT: -
Input unit is the device used to enter data and instructions into the computer. The
data read from the input device is stored in the computer’s memory.
Ex: key board, mouse, joy stick, track ball, light pen…..etc.
2. CPU: -
CPU is the main part of the computer.
In other words, it is brain of the computer.
This is also called as processor.
This unit takes the input data from input devices and processes it according
to the set of instructions called as “program”. The output for the processed
data is directed to the output devices.
It controls the operations.
MEMORY UNIT: -
Memory unit is also one of the most important parts of the computer.
Memory is the storage area in a computer where data, instructions, and
information are kept.
It is essential because the CPU can only process data that is stored in memory.
This unit stores the data, calculations and results into it and in case of need it sends
the data in the form of output.
Memory is made up of semiconductor cells, each cell is capable of storing one bit
of information either 0 or 1.
The capacity of memory is measured in terms of Bytes, Kbytes or megabytes.
SECONDARY MEMORY: -
It is used to hold the output data or program for future use.
These memory devices are for long term storage.
These are larger in capacity than main memory but these are very slower than
main memory.
The data from this memory is first transferred to the main memory.
Examples are Magnetic Tapes, Magnetic Disks, CD ROM, and Floppy disk.
3. OUTPUT UNIT: -
The function of output unit is reverse in nature than that of input unit.
Output unit takes out the data from the computer.
The information generated from the processor is displayed on the output device.
Some output devices are monitors, Printers, Floppy disk etc.
1. PROGRAM:-
A sequence of instructions that can be executed by the computer to solve the given
problem is known as program.
2. SOFTWARE:-
A set of programs to operate and controls the operation of a computer.
3. HARDWARE:-
All the physical components or units of the computer system connected to the
computer circuit are known as hardware.
Machine Language
First generation programming language.
Consists only of binary code (0s and 1s).
Example: 10110000 01100001
Features:
o Directly understood by the computer.
o Very fast execution.
o Difficult for humans to learn, read, or debug.
o Hardware dependent (different for each CPU).
Assembly Language
Second generation programming language.
Uses mnemonics (symbols/short codes) instead of binary.
The general form of Assembly Language code is
Source and destination are two operands and result is stored in destination operand.
Add R1, R2 ; Add the contents of R1 and R2 and result stored in R1 ( R1-R1+R2)
Features:
o Easier to write than machine language.
o Still hardware dependent.
o Needs an assembler to convert to machine code.
o Used for system programming and embedded systems.
High Level Language
Third generation programming language.
Uses English-like instructions.
Examples: C, C++, Java, Python.
Features:
o Easy to learn, write, and understand.
o Portable (can run on different machines).
o Requires a compiler or interpreter to translate into machine code.
o Supports structured programming, loops, functions, etc.
#include <stdio.h>
void main()
{
int a=10,b=20,c;
c=a+b;
printf("addition value is %d", c);
}
Middle-Level Language
It has features of both low-level languages (machine/assembly) and high-level languages.
It allows programmers to write system-level programs (like operating systems, device drivers)
and application programs (like calculators, games, business software).
Low-Level Features:
o Can directly access memory using pointers.
o Can perform bitwise operations and interact with hardware.
High-Level Features:
o Uses English-like syntax (if, while, printf).
o Programs are portable across different computers.
Translators Comparison
Feature Compiler Interpreter Assembler
High-level
Input Language High-level (C, Java) Assembly language
(Python, JS)
Error Handling Shows all errors after compilation Stops at first error Shows assembly errors
When we want to develop a program using any programming language, we follow a sequence
of steps. These steps are called phases in program development. Generally, the program
development life cycle contains 6 phases, they are as follows….
Problem Definition
Problem Analysis
Algorithm Development
Coding & Documentation
Testing & Debugging
Maintenance
1. PROBLEM DEFINITION
In this phase, we define the problem statement and we decide the boundaries of the problem.
In this phase we need to understand the problem statement, what is our requirement,
what should be the output of the problem solution. These are defined in this first phase of
the program development life cycle.
2. PROBLEM ANALYSIS
In phase 2, we determine the requirements like variables, functions, etc. to solve the
problem. That means we gather the required resources to solve the problem defined in the
problem definition phase.
3. ALGORITHM DEVELOPMENT
During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. That means we write the solution in step by step
statements. A step- by – step procedure to solve the given problem is known as Algorithm.
An algorithm is defined as finite set of steps which accomplish the particular task.
Characteristics of an algorithm are:
1. Finiteness: The algorithm must always terminate after a finite number of steps.
2. Definiteness: Each and every instruction should be precise and unambiguous i.e. each and
every instruction should be clear and should have only one meaning.
3. Effectiveness: Each instruction should be performed in finite amount of time.
4. Input and Output: An algorithm must take zero or more inputs, and produce one or more
outputs.
FLOW CHART: -
The flow charts use some symbols to represent specific actions and arrows to indicate the flow
of control.
These symbols have been standardized by the American National Standard Institute
(ANSI).
Here are the five most common shapes used in a flowchart.
Connectors: - A small, labeled circle used to connect different parts of a flowchart.
Coding is a process of converting the algorithmic solution or flow chart into a computer
program.
In this process each and every step of an algorithm will be converted into computer
programming language.
Before selecting a programming language, we must follow the following three considerations.
a. Nature of the problem.
b. Programming language available on the computer system.
c. Limitations of the computer.
During this phase, we test the program whether it is solving the problem for various
input data values or not.
6. MAINTENANCE
Start from the main problem and break it into smaller sub-problems (modules).
Keep dividing until each module is simple enough to implement.
Process
Bottom-Up Approach
Meaning
Start solving from smallest sub-problems (modules) and then combine them to make
the complete system.
Build complex programs by combining small, tested components.
Process
Time Complexity
Time complexity measures how much time an algorithm takes to run as a function of
the input size (usually denoted as n).
It tells us how fast or slow the algorithm is.
Key Points:
Space Complexity
Definition:
Key Points:
Iterative version:
int fact = 1;
for(i = 1; i <= n; i++)
fact *= i;
Comparison Table
Assembly language was used, but it was too complex and machine-dependent.
Higher-level languages like ALGOL (1960) and BCPL (1966) were developed to
make programming easier.
1970 – B Language
1972 – Birth of C
Major breakthrough!
UNIX operating system (originally in Assembly) was rewritten in C.
This proved C’s power, portability, and efficiency.
1978 – K&R C
Later Versions
C99 (1999): Added new features like inline functions, long long int, variable length
arrays.
C11 (2011): Added multi-threading support and improved standard libraries.
C18 (2018): Minor bug fixes and updates.
The latest official C standard is ISO/IEC 9899:2024, commonly referred to as C23. It was published in
October 2024 and supersedes the previous standard C17/C18.
Applications of C Language
1. Operating Systems
o Most of the UNIX operating system is written in C.
o Other OS like Windows, Linux kernel, and Android parts also use C.
2. Embedded Systems
o Widely used in microcontrollers, automotive systems, medical devices, and
consumer electronics.
o Example: Programming firmware for washing machines, TVs, cars, etc.
3. Compilers and Interpreters
o Many language compilers (C++, Java, Python interpreters) are implemented in
C.
4. Databases
o Popular databases like MySQL, Oracle, PostgreSQL use C for speed and
efficiency.
5. System Programming
o Device drivers, networking software, file systems, and system utilities are
often written in C.
6. Game Development
o Used for game engines and graphics rendering because of high performance.
o Example: Many early PC/console games were written in C.
7. Graphics and GUI Applications
o C is used in libraries for graphics, simulations, and GUI frameworks.
o Example: OpenGL, DirectX-based tools.
8. IoT (Internet of Things)
o Lightweight and efficient, making it suitable for IoT devices and sensors.
9. Scientific Computing and Simulations
o Used in numerical methods, simulations, and performance-critical research
applications.
10. Portable Applications
o C programs can run on different platforms with minimal modification, making
them highly portable.
STRUCTURE OF C PROGRAM
A C program has a well-defined structure. Every program is made up of the following sections:
1. Documentation section: The documentation section consists of a set of comment lines giving
the name of the program, the author and other details, and statements mentioned in this section are
not executed by the compiler.
2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the #define
directive.
4. Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that is
outside of all the functions
5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the executable
part.
2. Executable part: There is at least one statement in the executable part. These two parts
must appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main function is
the logical end of the program. All statements in the declaration and executable part end
with a semicolon.
User-defined functions are generally placed immediately after the main () function, although they
may appear in any order.
void main()
{
// Variable declaration
int radius;
float area;
// Input
printf("Enter radius: ");
scanf("%d", &radius);
// Processing
area = PI * radius * radius;
// Output purpose
printf("Area = %f", area);
}
Output:
Enter radius: 5.5
Area = 78.539749
BASIC INPUT AND OUTPUT FUNCTIONS
C programming has several in-built library functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas
the printf() function sends formatted output to the standard output (screen).
printf( ) in C
printf() is a standard library function in C (defined in <stdio.h>).
It is used to print/output text, variables, and results on the screen.
It helps in displaying messages to the user and the results of computations.
Syntax:
print("format string”);
format_specifiers → tells the type of data to be read (%d, %f, %c, %s, etc.).
& (address operator) → gives the memory location of variables so that the entered
value can be stored there.
Integer %d 10
Float %f 12.34
Character %c A
String %s Hello
Example:
#include <stdio.h>
void main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b); // input operation
printf("Sum = %d", a + b);
}
Sum = 40
Introduction to Compilation and Execution,
Generally, the programs created using programming languages like C, C++, Java, etc., are
written using a high-level language like English. But, the computer cannot understand the
high-level language.
It can understand only low-level language. So, the program written in the high-level
language needs to be converted into the low-level language to make it understandable for
the computer. This conversion is performed using either Interpreter or Compiler.
A compiler is a program that converts high-level language instructions into low-level
language instructions.
To create and execute C programs in the Windows Operating System, we need to install
Turbo C software. We use the following steps to create and execute C programs in
Windows OS…
1. Source Code
The program you write in a high-level language (like C, C++, Java, Python).
Example in C:
printf("Hello, World!");
2. Compilation
The compiler translates the entire source code into machine code (binary).
Machine code is what the computer understands directly (0s and 1s).
If there are errors, the compiler shows them (like syntax errors, missing semicolon).
After successful compilation, a machine code file (called object code / executable file)
is created.
👉 Example:
3. Linking
Sometimes your program uses libraries (like printf from stdio.h).
The linker combines your code with these library functions to make the final executable
file.
4. Execution
When you run the program, the executable is loaded into memory.
The CPU executes the machine code step by step.
Output is shown on the screen.
The C Character Set includes all the valid characters that can be used to write C programs.
These characters are used to form keywords, identifiers, constants, operators, and symbols.
Source Characters
These are characters that are used to create source text file. Source characters include
Alphabets A to Z, a to z
Digits 0,1,2,3,4,5,6,7,8,9
Special Characters , . ; : ? ‘ “ ! | / \ ~ _ $ % # & ^ * + - <> ( ) { } [ ] and blank
Execution Characters
Escape sequences
Escape
Sequence Name Meaning
Moves the cursor to the previous position of the
\b Backspace current line
\r Carriage return Moves the cursor to beginning of the current line.
Keywords
These are also called as reserved words.
All Keywords have fixed meanings and these meanings cannot be changed.
There are 32 keywords in C programming.
Keywords serve as basic building blocks for a program statement.
All keywords must be written in lowercase only.
The keywords cannot be used as Identifiers
Identifiers
An identifier is the name given to variables, functions, arrays, or any user-defined item
in a C program.
Identifiers must be unique. They are created to give a unique name to an entity to identify it
during the execution of the program
Examples: int marks; float average; void display();
Here, marks, average, and display are identifiers.
Rules for naming identifiers
Identifiers can contain letters (A–Z, a–z), digits (0–9), and underscores (_)
The first letter of an identifier should be either a letter or an underscore.
No special symbols (like @, $, #, !) are allowed
No spaces in identifiers.
C is case-sensitive → Total and total are different
Keywords (reserved words) cannot be used as identifiers
Length should be reasonable. ( Max -31 characters)
Valid Identifiers-- a, A1, _sum, total_marks, average, MaxValue
Invalid Identifiers 1sum, total marks, float, @value, marks#
Constants
Constant can be defined as a value that can be stored in memory and cannot be
changed during execution of the program.
Constants are used to define fixed values like pi.
C has four basic types of constants. They are:
Integer Constant
An integer constant must have at least one digit and should not have a decimal point. It can be
either positive or negative.
Examples for integer constants
1 9 234 999
It may be specified in Decimal, Octal and Hexa decimal notation.
1. There should be at least one digit, and could be either positive or negative value. A
decimal point is must.
2. There should be no commas or blanks.
Examples for fractional form
12.33 -19.56 +123.89 -0.7
When expressed in exponential form, a floating point constant will have 2 parts.
One is before e and after it. The part which appears before e is known as mantissa and the
one which follows is known as exponent. When expressed in this format, note the following
points.
1. mantissa and exponential should be separated by letter E.
2. mantissa can have a positive and negative sign.
3. default is positive.
Character Constant
String Constant
A String constant is sequence of characters enclosed in double quotes.
Example
“hello” “Programming”
Variables in C
A variable is a named memory location that stores a value which can change during program
execution. It acts like a container that holds data.
Each variable in C has a specific type, which determines the size of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
datatype variable_name;
int a;
The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part).
In C language, Type Modifiers (or Type Specifiers) are keywords that change the size, range, or
behavior of a basic data type. They don’t create new types, but modify existing primitive types like
int, char, float, etc.
Data Usage
Size Range Format
Type
(Bytes) (Typical 32-bit) Specifier
Data Usage
Size Range Format
Type
(Bytes) (Typical 32-bit) Specifier
(e.g., 3.140000e+00)
Double precision
floating-point type.
More accurate than ~ 1.7 × 10⁻³⁰⁸
float.
double
15 decimal digits
8 to %lf or %le
precision 1.7 × 10³⁰⁸
Format
Data Type Memory Size Range
Specifier
Uses of void
A function that does not return any value is declared with void.
Syntax:
void function_name()
{
// code
}
Introduction to bool
bool is used to store Boolean values — true or false.
Unlike integers, it is specifically meant for logical operations.
In C, bool is not a built-in keyword in older C standards; it was introduced in C99 via the
header <stdbool.h>.
Syntax
#include <stdbool.h>
true → 1
false → 0
Properties of bool
void main()
{
// Integer data types
int a = -100;
short int b = -20000;
long int c = 1234567890;
signed int d = -500;
unsigned int e = 40000;
// Display values
printf("----- Integer Data Types -----\n");
printf("int: %d \n", a);
printf("short int: %d \n", b);
printf("long int: %ld \n", c);
printf("signed int: %d \n", d);
printf("unsigned int: %u \n", e);
printf("flag1= %d \n",flag1);
printf("flag2= %d \n",flag2);
}
Output:
----- Integer Data Types -----
int: -100
short int: -20000
long int: 1234567890
signed int: -500
unsigned int: 40000
flag1= 1
flag2= 0
C - OPERATORS
An operator is a symbol which operates on a value or a variable. For example: + is an operator to
perform addition between two operands.
C programming has wide range of operators to perform various operations. For better
understanding of operators, these operators can be classified as:
Operators in C programming
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Unary Operators
Special Operators
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and
multiplication on numerical values (constants and variables).
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction and multiplication respectively as you
might have expected.
It is because both variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after decimal point and shows answer 2 instead of 2.25.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is = .
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is true,
it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
#include <stdio.h>
void main()
Output
a = 10, b = 20
a == b : 0 // false
a != b : 1 // true
a > b : 0 // false
a < b : 1 // true
a >= b : 0 // false
a <= b : 1 // true
Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether expression
results true or false. Logical operators are commonly used in decision making in C programming.
#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;
}
Output
Bitwise Operators
Bitwise operators are used in C programming to perform bit-level operations. They
perform binary operations on operands.
Bitwise AND
The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either
bit of an operand is 0, the result of corresponding bit is evaluated to 0.
In C Programming, the bitwise AND operator is denoted by &.
I/P AND O/P
0 0 0
Let us suppose the bitwise AND operation of two integers 12 and 25.
0 1 0
1 0 0
12 = 00001100 (In Binary)
25 = 00011001 (In Binary) 1 1 1
I/P OR O/P
12 = 00001100 (In Binary)
25 = 00011001 (In Binary) 0 0 0
0 1 1
Bitwise OR Operation of 12 and 25
00001100 1 0 1
| 00011001
________ 1 1 1
00011101 = 29 (In decimal)
Shift Operators
Left shift operator shifts all bits towards left by certain number of specified bits.
It is denoted by << .
The bit positions that have been vacated by the left shift operator are filled with 0.
.
Expression Binary Decimal
a=5 00000101 5
a << 1 00001010 10
a << 2 00010100 20
a << 3 00101000 40
Right shift operator shifts all bits towards right by certain number of specified bits.
It is denoted by >>.
The bit positions that have been vacated by the right shift operator are filled with 0.
Each shift divides the number by 2 (integer division).
a = 20 00010100 20
a >> 1 00001010 10
a >> 2 00000101 5
a >> 3 00000010 2
Complement operator
Bitwise complement operator is a unary operator (works on only one operand).
It changes 1 to 0 and 0 to 1. It is denoted by ~.
Consider a= 5 ;
a= 5 0 1 0 1
Complement 1 0 1 0
Add 1:
0 1 0 1
+ carry 1
1
0 1 1 0
0110 = 6
void main()
{
int a, b, result;
Output:
Unary Operators
Unary operators operate on only one variable (or operand).
They’re mostly used to increment, decrement, negate, or get properties of a value.
Operator Meaning Example Explanation
+ Unary plus +a Indicates the number is positive
- Unary minus -a Changes the sign of the number
++ Increment ++a or a++ Increases the value by 1
-- Decrement --a or a-- Decreases the value by 1
! Logical NOT !a True → False, False → True
~ Bitwise NOT ~a Flips all bits (1 → 0, 0 → 1)
sizeof Size of a data type or variable sizeof(a) Returns number of bytes used
When Increment/Decrement
Type Syntax Example
Happens
Pre-Increment ++a Value is increased first, then used If a=5, then b = ++a → a=6,
b=6
Post-Increment a++ Value is used first, then increased If a=5, then b = a++ → b=5,
a=6
Pre-Decrement --a Value is decreased first, then used If a=5, then b = --a → a=4,
b=4
Post- a-- Value is used first, then decreased If a=5, then b = a-- → b=5,
Decrement a=4
#include <stdio.h>
void main()
{
int a = 5, b;
b = ++a; // Pre-increment
printf("After ++a: a = %d, b = %d \n", a, b);
b = a++; // Post-increment
printf("After a++: a = %d, b = %d \n", a, b);
b = --a; // Pre-decrement
printf("After --a: a = %d, b = %d \n", a, b);
b = a--; // Post-decrement
printf("After a--: a = %d, b = %d \n", a, b);
Output:
Initial value of a = 5
After ++a: a = 6, b = 6
After a++: a = 7, b = 6
After --a: a = 6, b = 6
After a--: a = 5, b = 6
Special Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator
The sizeof is an unary operator which returns the size of data (constant, variables, array,
structure etc).
It is a compile time operator. Syntax: sizeof (data-type or variable)
#include <stdio.h>
void main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %d bytes\n", sizeof(e));
Output
max = (a > b) ? a : b;
Output:
#include <stdio.h>
int main() {
int a, b, c, largest;
return 0;
}
Output:
#include <stdio.h>
void main()
{
int a = 10;
Output:
Value of a = 10
Address of a = 0x7ffeeab3b68c
#include <stdio.h>
void main()
{
int a = 10;
int *p; // pointer variable declaration
Value of a = 10
Address of a = 0x7ffeec3b68c
Pointer p holds = 0x7ffeec3b68c
Value at address stored in p = 10
Operator Precedence and Associativity
Precedence decides which operator is evaluated first in an expression when there are
multiple operators.
int a = 5 + 3 * 2;
Here:
Associativity:
➡️ Associativity decides which direction (left or right) the expression is evaluated when
operators of same precedence appear together.
int a = 10 / 2 * 5;
Type Conversion
Type Conversion means changing one data type into another while performing operations or
assignments.
There are two main types of type conversion in C:
#include <stdio.h>
void main( )
{
int a = 5;
float b = 2.5;
float result = a + b; // a (int) → float automatically
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float ->
double -> long double
(data_type) expression;
where, data_type is any valid c data type, and expression may be constant, variable or expression.
For example,
void main()
{
double x = 1.2;
Output: sum = 2
Example 2:
#include <stdio.h>
void main()
{
int a = 7;
int b = 2;
float c;
Output:
Without casting: 3.00
With casting: 3.50
Control Statements in C
Control statements in C are the statements that control the flow of execution of a
program — i.e., they decide which part of the code should be executed and when.
They allow the program to make decisions, repeat actions, and jump from one part of
the program to another.
Iteration/ Looping(Repetitive) statements are as follows: There are three types of loops
in C
programming:
1. while loop
2. do..while loop
3. for loop
Specifying Test Condition for Selection and Iteration
• A test condition used for selection and iteration is expressed as a test
expression.
• If an expression evaluates to true, it is given the value of 1.
• If a test expression evaluates to false, it is given the value of 0.
•
Relational and Logical operators are available to specify the test condition
used in the control statements of C.
•
Relational operators are used to specify individual test expression.
•
Logical operators are used to connect more than one test expression.
1
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
The simple if
This is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used
in conjunction with an expression. It takes the following form:
Syntax: Flowchart
if(test expression )
{
statement-block;
}
statement - x;
• .If the test expression is true then the statement-block will be executed;
otherwise the statement block will be skipped and the execution will jump
to the statement-x.
• Remember, when the condition is true both the statement-block and the
statement-x are executed in sequence.
Ex 1: Write a program to check whether the given number is +ve or –ve using
simple if statement.
#include<stdio.h>
void main()
{
int num;
printf("Enter a number:");
scanf("%d”, &num);
if(num>0)
Output:
Enter a number: 9
9 is a positive number.
2
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Syntax Flowchart
if (test-expression)
{
statement block - 1;
}
else
{
statement block - 2;
}
statement-x;
Ex 2: Write a program to check whether the given number is even or odd using
if..else statement.
#include<stdio.h>
void main()
{
int num;
printf("Enter a number:");
scanf("%d",&num);
if(num%2==0)
{
printf("%d is even number\n",num);
}
else
{
printf("%d is odd number\n",num);
}
Output:
Enter a number: 8
8 is even number.
3
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Ex 3: Write a program to check whether the given year is leap or not using
if..else statement.
#include<stdio.h>
int main()
{
int year;
printf("Enter any year:");
scanf("%d",&year);
if(year%4==0)
printf("%d is leap year\n", year);
else
printf("%d is non leap year\n", year);
return 0;
}
Output:
Enter any year: 1996
1996 is leap year.
Syntax: Flowchart:
if (test expression 1)
{
if (test expression 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
4
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
else
printf("%d is the big\n",c);
}
else
{
if(b>c)
printf("%d is the big\n",b);
else
printf("%d is the big\n",c);
}
}
Output:
Enter a, b, c values: 9 5 17
17 is the big
In simple terms —
5
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
• All the conditions are evaluated one by one starting from top to bottom, if
any one of the condition evaluating to true then statement group
associated with it are executed and skip other conditions.
• If none of expression is evaluated to true, then the statement or group of
statement associated with the final else is executed.
Flowchart
6
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
void main()
{
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
7
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Ex: Write a C program to calculate the electricity bill based on the number of
units consumed according to the following conditions:
Program:
#include <stdio.h>
void main()
{
int units;
float amount;
else
{
amount = (100 * 2.0) + (100 * 3.0) + ((units - 200) * 5.0);
}
Output:
Enter total units consumed: 250
Total Electricity Bill = ₹1050.00
8
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Ex: Write a C program to find the roots of a quadratic equation of the form
ax² + bx + c = 0
#include <stdio.h>
#include <math.h> // for sqrt() function
void main()
{
float a, b, c, discriminant, root1, root2, realPart, imagPart;
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
// Real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct.\n");
printf("Root1 = %.2f and Root2 = %.2f", root1, root2);
}
else if (discriminant == 0)
{
// Real and equal roots
root1 = -b / (2 * a);
printf("Roots are real and equal.\n");
printf("Root1 = Root2 = %.2f", root1);
}
9
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
else
{
// Complex roots
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and imaginary.\n");
printf("Root1 = %.2f + %.2fi and Root2 = %.2f - %.2fi",
realPart, imagPart, realPart, imagPart);
}
Outputs:
10
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
case constant2:
// statements
break;
...
default:
// statements
}
.Flow Chart:
11
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
int main()
{
int choice;
float a, b, result;
printf("1.Add\n2.Subtract\n3.Multiply\n4.Divide\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
result = a + b;
printf("Sum = %.2f", result);
break;
case 2:
result = a - b;
printf("Difference = %.2f", result);
break;
case 3:
result = a * b;
printf("Product = %.2f", result);
break;
case 4:
if(b != 0)
printf("Division = %.2f", a / b);
else
printf("Division by zero not allowed");
break;
default:
printf("Invalid choice");
}
}
12
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Output:
// case 1 addition
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 1
Enter two numbers: 5 7
Sum = 12.00
// case 2 subtraction
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 2
Enter two numbers: 10 4
Difference = 6.00
13
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Looping Structures
The programmer sometimes interested to repeat a set statements a number of
times. This is known as looping in a computer program.
A loop is a group of instructions that computer executes repeatedly
while some loop continuation conditions remains true.
Every loop — whether it’s a for, while, or do-while — needs three basic parts
to work correctly.
14
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
syntax:
while (test expression)
{
body of the loop;
}
statement-x;
Flowchart
Output: 1 2 3 4 5 6 7 8 9 10
15
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
void main()
{
int i = 1, sum = 0;
while (i <= 5)
{
sum = sum + i;
i++;
}
Output: Sum = 15
16
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Syntax Flowchart
do
{
body of the loop;
}
while (expression);
statement -x;
Output: 1 2 3 4 5
17
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Syntax:
for(initialization; test expression; increment /decrement/ update)
{
body of the loop;
}
Flowchart
18
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Note: In for loop everything is optional but mandatory to place two semicolons
(; ;)
#include <stdio.h>
void main()
{
for (int i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
}
Output:
1
2
3
4
5
#include <stdio.h>
void main()
{
int i, sum = 0;
19
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Nested loops
A nested loop means one loop inside another loop.
The inner loop runs completely for every single iteration of the outer loop.
#include <stdio.h>
int main()
{
int i, j;
return 0;
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
20
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include<stdio.h>
main()
{
int i,j,n;
printf("Enter number of rows:" );
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");
}
}
Output:
Enter number of rows: 5
*
* *
* * *
* * * *
* * * * *
break;
21
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
void main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
break; // loop stops when i = 5
printf("%d ", i);
}
}
Output
1 2
The continue statement skips the remaining code inside the current loop and
jumps to the next iteration of that loop.
continue;
22
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
void main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
continue; // loop stops when i = 5
printf("%d ", i);
}
Output
1 2 3 4 6 7 8 9 10
Used to terminate the loop or Used to skip the remaining statements of the
Purpose
switch completely. current iteration.
Control Transfers control outside the Transfers control to the beginning of the next
Transfer loop/switch. iteration of the loop.
Effect on The loop stops running The loop continues running, but skips the
Loop immediately. current iteration.
for, while, do-while, and for, while, and do-while loops only (not in
Usage In
switch statements. switch).
Common Use To exit when a condition is met. To ignore or skip a particular case/iteration.
Example
If i==5, loop prints up to 4 only. If i==5, loop skips 5 but prints the rest.
Output
23
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
void main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num < 0)
goto negative;
printf("You entered a positive number.\n");
negative:
printf("You entered a negative number.\n");
return 0;
}
Output
Enter a number: -3
You entered a negative number.
24
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Exercise Programs
Ex : Write a C program to check whether the given number is prime or not.
Concept
A prime number is a number that is greater than 1 and divisible only by 1
and itself.
👉 Example: 2, 3, 5, 7, 11, 13, …
void main()
{
int num, i, count = 0;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1)
{
printf("Not a prime number.\n");
if (count == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
}
Output
Enter a number: 13
13 is Prime.
Enter a number: 22
22 is not a prime number.
25
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include <stdio.h>
int main()
{
int num, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
while(num > 0)
{
digit = num % 10; // Get the last digit
sum = sum + digit; // Add it to sum
num = num / 10; // Remove the last digit
}
printf("Sum of digits = %d\n", sum);
return 0;
}
26
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
#include<stdio.h>
void main( )
{
int n,rem,sum=0,temp;
printf("Enter a number:");
scanf("%d",&n);
temp=n;
while(n != 0)
{
rem = n%10;
sum = sum+(rem*rem*rem);
n = n/10;
}
if(sum == temp)
printf("%d is Armstrong\n", temp);
else
printf("%d is not an Armstrong\n", temp);
}
Output
Enter a number: 153
153 is Armstrong
27
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Ex: Write a C program to print reverse of given number using while loop.
#include <stdio.h>
int main()
{
int num, reverse = 0, digit;
Output
Enter a number: 5214
Reversed number = 4125
---------------------------
#include <stdio.h>
int main()
{
int num, reverse = 0, digit,temp;
printf("Enter a number: ");
scanf("%d", &num);
temp=num;
while(num > 0)
{
digit = num % 10; // Get the last digit
reverse = reverse * 10 + digit; // Add digit to reverse
num = num / 10; // Remove last digit
}
28
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
if (temp==reverse)
{
printf("%d is palindrome number",temp);
}
else
{
printf("%d is not palindrome number",temp);
}
return 0;
}
Output:
Enter a number: 258
258 is not palindrome number
#include <stdio.h>
#include<stdio.h>
int main( )
{
int n,i;
long int fact=1;
printf("Enter a number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
fact = fact*i;
}
printf("Factorial of %d is %ld\n", n, fact);
return 0;
}
Output
Enter a number: 5
Factorial of 5 is 120
Enter a number:10
Factorial of 10 is 3628800
29
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
int main()
{
int n, i, j; //i and j represents rows and columns respectively
printf("Enter number of rows:" );
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
30
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
include <stdio.h>
int main()
{
int n, i, j, num = 1;
return 0;
}
#include <stdio.h>
void main()
{
int num, i;
printf("Enter a number: ");
scanf("%d", &num);
printf("Multiplication Table of %d:\n", num);
for(i = 1; i <= 10; i++)
{
printf("%d x %d = %d\n", num, i, num * i);
}
}
31
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Enter a number: 5
Multiplication Table of 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
A Perfect Number is a number that is equal to the sum of its proper divisors (excluding
the number itself).
Examples:
• 6 → Divisors = 1, 2, 3 → 1 + 2 + 3 = 6 → ✔ Perfect
• 28 → Divisors = 1, 2, 4, 7, 14 → 1 + 2 + 4 + 7 + 14 = 28 → ✔ Perfect
• 12 → Divisors = 1, 2, 3, 4, 6 → 1 + 2 + 3 + 4 + 6 = 16 → ❌ Not Perfect
#include <stdio.h>
int main()
{
int num, i, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
for(i = 1; i <= num / 2; i++)
{ // check divisors up to num/2
if(num % i == 0) // if i divides num
sum = sum + i; // add to sum
}
if(sum == num)
printf("%d is a Perfect Number.\n", num);
else
printf("%d is not a Perfect Number.\n", num);
return 0;
}
32
Introduction to Programming UNIT-2 J.SRAVAN KUMAR@CSE AIML
Output:
Enter a number: 28
28 is a Perfect Number.
Enter a number: 25
25 is not a Perfect Number.
Pre-test loop: The condition can be tested- At the beginning is called as pre-test
or entry- controlled loop. Example: while and for loops.
Post-test loop: The condition can be tested - At the end is called as post-test or
exit- controlled loop. Example: do-while loop.
33