C PROG. M1 FULL NOTES
C PROG. M1 FULL NOTES
Module 1 : C Fundamentals
A Brief History of C
C programming has a rich history that traces its roots back to earlier programming languages:
Programming is essential to interact with and harness the power of computers. However,
computers operate in binary code (1s and 0s), which is impossible for humans to write or
debug efficiently. Programming languages, such as C, Python, or Java, allow us to write
instructions in a way that is easier for humans to understand.
A compiler is a special program that acts as a translator between humans and machines. It
converts high-level programming code (written in human-readable languages like C) into
machine code (binary) that a computer can execute. Here's why compilers are indispensable:
1. Translating Code
Compilers take your source code and translate it into a machine-readable format. For
example:
• High-level code: printf("Hello, World!");
• Compiled machine code: 01101000 01100101 ... (binary instructions).
C Fundamentals
THE C CHARACTER SET
C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special
characters as building blocks to form basic program elements (e.g., constants, variables, operators,
expressions, etc.).
C uses certain combinations of these characters, such as \b, \n and \t,to represent special conditions
such as backspace, newline and horizontal tab, respectively. These character combinations are
known as escape sequences.
Constants (Literals) in C
In C programming, constants are fixed values that do not change during the execution of a
program. Constants make your code more readable and easier to maintain, as they represent
meaningful, unchanging data.
Types of Constants in C
1. Integer Constants
o These are whole numbers without any fractional part.
o Examples:
10
-45
0
2. Floating-point Constants
o These represent real numbers with fractional parts.
o Examples:
3.14
-0.001
2.5E3 (scientific notation for 2.5 × 10^3).
3. Character Constants
o A single character enclosed in single quotes (' ').
o Examples:
'A'
'9'
'#'
o Can represent printable characters, escape sequences (like \n, \t), or even
ASCII values.
4. String Constants
o A sequence of characters enclosed in double quotes (" ").
o Examples:
"Hello, World!"
"12345"
Rules for String Constants:
Identifiers
Identifiers are names given to various elements of a program, such as variables, functions,
and arrays. They help in uniquely identifying these elements in the code.
x // Single letter
Y12 // Letters followed by digits
sum_1 // Letters, digits, and underscore
temperature // Readable name
names // Simple word
area // Descriptive
Identifier Reason
8sum Starts with a digit.
x' Contains an illegal character (').
order-no Contains a hyphen (-).
error flag Contains a blank space.
Best Practices for Identifiers:
Keywords
Keywords are reserved words in C with standard, predefined meanings. These cannot be used
as identifiers.
IDE Used
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Steps:
3. Hello, World!
Variables in C
In programming, data is stored in memory. Memory consists of numerous slots, each with a
unique address used to identify that location.
A variable can be thought of as a box that can hold data. The type of data stored in a variable
can be an integer, floating-point number, character, or even multiple characters (strings).
Using a Variable in C
Before using a variable, you must declare it to specify the data type and allocate memory.
Example:
Explanation:
2. Updating a Variable
int x = 10;
x = 15; // Updates the value of x to 15
Let’s write a program to calculate the sum of two numbers stored in variables.
Code:
#include <stdio.h>
int main() {
int number_1 = 10; // Declare and initialize the first variable
int number_2 = 20; // Declare and initialize the second
variable
int sum = number_1 + number_2; // Add the two numbers and store the
result in sum
Sum = 30
Explanation of Code
1. #include <stdio.h>: Includes the standard input/output library to use functions like
printf.
2. int number_1 = 10;: Declares and initializes the first integer variable.
3. int number_2 = 20;: Declares and initializes the second integer variable.
4. int sum = number_1 + number_2;: Adds number_1 and number_2 and stores the
result in the sum variable.
5. printf("Res = %d\n", sum);: Displays the value of sum using %d.
What is %d in printf?
int x = 25;
printf("The value of x is: %d\n", x);
Output:
Summary
Data types in the C programming language are used to define the type of value a variable can
store. They also determine the memory size allocated to the variable and how the stored value
is interpreted.
1. int (Integer)
2. char (Character)
3. float
Used to store decimal numbers with single precision, providing about 7 decimal digits of
precision.
Memory size: 4 bytes (32 bits).
Format specifier: %f
Example:
float pi = 3.1415926;
4. double
Used to store decimal numbers with double precision, , offering about 15-16 decimal
digits of precision and is generally used when higher accuracy is required.
Memory size: 8 bytes (64 bits).
Format specifier: %lf
Example:
In C, data type modifiers are the keywords used to modify the original sign or length/range of
values of normal data types.
Size Qualifier:
Sign Qualifier:
1. short int:
o Requires less memory than int , Requires : 2 bytes
o Range : -32,768 to 32,767
o Example:
3. unsigned int:
o Does not reserve a bit for the sign, doubling the positive range.
o unsigned integers are used to store values that are non-negative, meaning they
are either zero or positive.
o Range : 0 to 4,294,967,295
o Example:
Meaning: It is an unsigned integer type that occupies less memory than a standard
int (2 bytes).
Range: It can store only positive values, ranging from 0 to 65535.
Meaning: It is a signed integer type that typically occupies 4 bytes (32 bits), but its
size can vary depending on the platform (on some systems, it may be 8 bytes or 64
bits).
Range: It can store both negative and positive values, typically ranging from
-2,147,483,648 to 2,147,483,647
Meaning: It is an unsigned integer type that typically occupies 8 bytes (64 bits).
Range: It can store only positive values, typically ranging from
0 to 18,446,744,073,709,551,615
IV. Derived Data Types
Enumeration types (enum) are used to define a set of named integral constants.
Example:
Additional Notes
5. Example Program
#include <stdio.h>
int main() {
int a = 10;
float b = 3.14;
char c = 'A';
unsigned int d = 100;
return 0;
}
What do you mean by formatted Input? Explain in detail the prototype of scanf() function in c
including its argument list and return type. (KTU July 2021 – 2019 Scheme) – 7 Marks
Formatted Input in C
Formatted input refers to reading data from the user (or an input source) in a specific
structure or format defined by the programmer. The C function scanf provides this
functionality by allowing the programmer to specify a format string that dictates how the
input should be taken and stored in variables.
Prototype of scanf()
Breakdown of Components
int x;
scanf("%d ", &x);
How scanf Works
1. Reads Input:
o Scans the input buffer and parses it according to the format string.
o Example: For %d, scanf skips whitespaces and reads the next integer.
2. Matches Format Specifiers:
o Interprets and converts the input based on the specifier.
o Example: %f reads a floating-point number, converts it to float, and assigns it
to the variable.
3. Assigns Values:
o Stores the converted values at the addresses provided.
Examples
1. Basic Example
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num); // Reads an integer
printf("You entered: %d\n", num);
return 0;
}
2. Multiple Inputs
#include <stdio.h>
int main()
{
int a, b;
float c;
printf("Enter two integers and a float: ");
scanf("%d %d %f", &a, &b, &c);
printf("You entered: %d, %d, %.2f\n", a, b, c);
return 0;
}
Formatted and Unformatted Input/Output Functions in C
Explain formatted and unformatted I/O functions of C language with syntax and example. (June
2022 – 2019 Scheme) – 7 marks
Formatted I/O functions allow inputs and outputs of various data types, including int, float, char,
etc., using format specifiers. These functions format the input and output according to specific
needs.
1. printf()
o Syntax:
2. scanf()
o Syntax:
o Example:
Unformatted I/O functions work only with character data and strings. They are not using any format
specifiers.
These functions lack formatting capabilities and directly deal with raw character data.
Functions in Unformatted I/O
1. getch()
The getch() function reads a single character input from the user without displaying it
on the console (echo-less input).
It does not require the user to press "Enter" after typing the character; the function
immediately returns the character as soon as a key is pressed. This function is declared in
conio.h
Syntax: char ch = getch();
Example:
#include <conio.h>
#include <stdio.h>
int main()
{
printf("Press any key: ");
char ch = getch();
printf("\nYou pressed: %c", ch);
return 0;
}
2. getche()
3. getchar()
Example:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
return 0;
}
Output:
Enter a character: Z
You entered: Z
4. putchar()
o Syntax: putchar(variable_name);
5. gets()
o Syntax: gets(char_array);
o Example:
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
gets(name);
printf("Hello, %s!", name);
return 0;
}
Output:
Hello, Alice!
6. puts()
o Displays a string.
o Syntax: puts(identifier_name);
3. Formatted I/O vs. Unformatted I/O
Data Types Supported All data types Only character and strings
OPERATORS IN C
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.
1. Arithmetic Operators
a=7,b=3
a%b=7%3=1
Example program :
#include <stdio.h>
int main() {
int a = 10, b = 5;
int c;
c = -a;
// Unary operators
printf("Value of c: %d\n",c);
return 0;
Used to compare two values. The result is either true (1) or false (0).
Example:
#include <stdio.h>
int main()
{
int a = 30, b = 4;
printf("%d",a>b);
return 0;
}
3. Logical operators:
Logical operators in C are used to perform logical operations, often involving conditional
expressions. They return a value of either true (1) or false (0) depending on the condition.
The logical operators && and || are used when we want to test more than one condition and
make decisions.
#include <stdio.h>
int main()
{
int a = 30, b = 4;
printf("%d",(a>b && a>10 && b<5 && a==30));
return 0;
}
The logical NOT (!) operator inverts the logical value of an operand:
#include <stdio.h>
int main()
{
int a = 30, b = 0;
printf("%d",!(a>b));
return 0;
}
4. Assignment Operators
Compound operators are shorthand operators in C that perform an operation and assignment
in a single step. For example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
a += b; // Equivalent to a = a + b
printf("After a += b, a = %d\n", a);
a -= b; // Equivalent to a = a - b
printf("After a -= b, a = %d\n", a);
a *= b; // Equivalent to a = a * b
printf("After a *= b, a = %d\n", a);
a /= b; // Equivalent to a = a / b
printf("After a /= b, a = %d\n", a);
a %= b; // Equivalent to a = a % b
printf("After a %%= b, a = %d\n", a);
return 0;
}
C provides two very useful operators that are not commonly found in many other languages:
Definition
Statement Meaning
++a Pre-increment
a++ Post-increment
--a Pre-decrement
a-- Post-decrement
Behavior
1. Standalone Usage:
Both ++a and a++ (or --a and a--) behave the same when used as standalone
statements.
Example:
int a = 5;
++a; // Increments a to 6
a++; // Increments a to 7
Example Table:
Examples
#include<stdio.h>
int main() {
int a = 5, b;
b = ++a; // Pre-increment: a becomes 6, then b = 6
printf("a = %d, b = %d\n", a, b);
b = a--; // Post-decrement: b = 6, then a becomes 5
printf("a = %d, b = %d\n", a, b);
return 0;
}
6. Conditional operators.
Conditional operators in C are often referred to as ternary operator because they take three
operands. The syntax and use of the conditional operator (?:) provide a short way to perform
simple conditional checks and assignments.
Syntax:
condition ? expression1 : expression2;
How It Works:
#include <stdio.h>
int main()
{
int a = 10, b = 20;
int max;
// Using the conditional operator to find the maximum
max = (a > b) ? a : b;
printf("The maximum is: %d\n", max);
return 0;
}
7. Bitwise operators
Bitwise operators are used to perform operations on the binary representations of integers.
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and
the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and
the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
8. Special Operators
sizeof Operator
sizeof(type or variable);
Cast Operator
Syntax:
(type) expression;
Example:
float a = 5.5;
What is type casting? Name the inbuilt functions available in C language. What is the difference
between type casting and type conversion? (UQ – July 2021)
#include <stdio.h>
int main() {
int a = 5;
float b = 2.5;
float result = a + b; // 'a' is implicitly converted to float
printf("Result: %.2f\n", result); // Output: 7.50
return 0;
}
Definition: Explicit conversion, also called type casting, is done manually by the
programmer to convert one data type to another using the cast operator (type).
Key Points:
o Performed manually by the programmer.
o Requires the cast operator (type).
Example:
#include <stdio.h>
int main() {
float a = 5.7;
int b = (int)a; // Explicitly cast 'a' to int
printf("After casting: %d\n", b); // Output: 5
return 0;
}
Inbuilt Functions Available in C for Type Conversion
C provides a few standard library functions to help with explicit type conversions. Here are
some of the common ones:
atof(): used to convert the data type string into the data type float.
atoi():used to convert the data type string into the data type int.
atbol():used to convert the data type string into the data type long.
itoba():used to convert the data type int into the data type string.
ltoa():used to convert the data type long into the data type string.
OPERATORS IN C
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.
1. Arithmetic Operators
a=7,b=3
a%b=7%3=1
Example program :
#include <stdio.h>
int main() {
int a = 10, b = 5;
int c;
c = -a;
// Unary operators
printf("Value of c: %d\n",c);
return 0;
Used to compare two values. The result is either true (1) or false (0).
Example:
#include <stdio.h>
int main()
{
int a = 30, b = 4;
printf("%d",a>b);
return 0;
}
3. Logical operators:
Logical operators in C are used to perform logical operations, often involving conditional
expressions. They return a value of either true (1) or false (0) depending on the condition.
The logical operators && and || are used when we want to test more than one condition and
make decisions.
#include <stdio.h>
int main()
{
int a = 30, b = 4;
printf("%d",(a>b && a>10 && b<5 && a==30));
return 0;
}
The logical NOT (!) operator inverts the logical value of an operand:
#include <stdio.h>
int main()
{
int a = 30, b = 0;
printf("%d",!(a>b));
return 0;
}
4. Assignment Operators
Compound operators are shorthand operators in C that perform an operation and assignment
in a single step. For example:
#include <stdio.h>
int main() {
int a = 10, b = 5;
a += b; // Equivalent to a = a + b
printf("After a += b, a = %d\n", a);
a -= b; // Equivalent to a = a - b
printf("After a -= b, a = %d\n", a);
a *= b; // Equivalent to a = a * b
printf("After a *= b, a = %d\n", a);
a /= b; // Equivalent to a = a / b
printf("After a /= b, a = %d\n", a);
a %= b; // Equivalent to a = a % b
printf("After a %%= b, a = %d\n", a);
return 0;
}
C provides two very useful operators that are not commonly found in many other languages:
Definition
Statement Meaning
++a Pre-increment
a++ Post-increment
--a Pre-decrement
a-- Post-decrement
Behavior
1. Standalone Usage:
Both ++a and a++ (or --a and a--) behave the same when used as standalone
statements.
Example:
int a = 5;
++a; // Increments a to 6
a++; // Increments a to 7
Example Table:
Examples
#include<stdio.h>
int main() {
int a = 5, b;
b = ++a; // Pre-increment: a becomes 6, then b = 6
printf("a = %d, b = %d\n", a, b);
b = a--; // Post-decrement: b = 6, then a becomes 5
printf("a = %d, b = %d\n", a, b);
return 0;
}
6. Conditional operators.
Conditional operators in C are often referred to as ternary operator because they take three
operands. The syntax and use of the conditional operator (?:) provide a short way to perform
simple conditional checks and assignments.
Syntax:
condition ? expression1 : expression2;
How It Works:
#include <stdio.h>
int main()
{
int a = 10, b = 20;
int max;
// Using the conditional operator to find the maximum
max = (a > b) ? a : b;
printf("The maximum is: %d\n", max);
return 0;
}
7. Bitwise operators
Bitwise operators are used to perform operations on the binary representations of integers.
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and
the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and
the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
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.
Example:
#include <stdio.h>
int main() {
return 0;
}
Output
Output = 8
Bitwise OR Operator: |
Example
#include <stdio.h>
int main() {
return 0;
}
Output
Output = 29
Bitwise XOR (exclusive OR) Operator: ^
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.
int main() {
return 0;
}
Run Code
Output
Output = 21
Bitwise Complement Operator: ~
int main() {
return 0;
}
Output
Output = -36
Output = 11
8. Special Operators
The comma operator, is represented by the comma sign (,) placed between the
expressions we want to evaluate. A simple sample syntax is shown below:
This syntax uses the comma operator in C to combine multiple expressions within a
single statement.
Each expression is evaluated sequentially from left to right, and the result of the entire
sequence is the value of the rightmost expression (expr3 in this case).
Example Code:
#include<stdio.h>
int main(){
int y;
int a = (y=3,y+1);
printf("%d", a);
return 0;
}
sizeof Operator
sizeof(type or variable);
Cast Operator
Syntax:
(type) expression;
Example:
float a = 5.5;
Sl
.
TYPE CASTING TYPE CONVERSION
N
O
In type casting, a data type is converted into In type conversion, a data type is
1. another data type by a programmer using a converted into another data type by
casting operator. the compiler.
Type casting can be applied to both compatible Type conversion can only be applied to
2.
and incompatible data types. compatible data types.
Write a C program that calculates and prints the result of the following expression:
result = 5 * (6 + 2) / 4 - 3. Explain how parentheses affect the precedence of operators in
this expression.(Model Question – 2024 Scheme)
1. Operator Precedence in C
Operator precedence determines which operation is performed first when there are multiple
operators in an expression. Operators with higher precedence are evaluated before those
with lower precedence.
int x = 15 + 20 * 3;
// '*' has higher precedence than '+', so evaluated as: 15 + (20 * 3) = 75
2. Operator Associativity
Types of Associativity
1. Left-to-Right Associativity: Operators at the same level are evaluated from left to right.
2. Right-to-Left Associativity: Operators at the same level are evaluated from right to left.
int result = 10 - 4 - 2;
// Evaluated as: (10 - 4) - 2 = 4
int a = 10;
int b = 20;
int c = 30;
a = b = c; // Right-to-left: a = (b = c) → b gets 30, then a gets 30
int main() {
int a = 5, b = 10, c = 2, result;
// Evaluate
int a = 5, b = 10, c = 2, result;
result = 14 && 1 || a == c
result = 1 || a == c
Equality Operator (a == c)
a == c → 5 == 2 → 0 (false)
result = 1 || 0
5. Summary
Write a C program that calculates and prints the result of the following expression:
result = 5 * (6 + 2) / 4 - 3. Explain how parentheses affect the precedence of operators in
this expression.(Model Question – 2024 Scheme)
#include <stdio.h>
int main() {
int result;
return 0;
}
Parentheses can override precedence to ensure correct evaluation order.
Step-by-Step Calculation:
✅ Final Output:
Result: 7
Control Statements in C
Introduction
Control statements in C determine the flow of execution in a program. These statements
allow programmers to make decisions, loop through code, and jump to different parts of a
program based on conditions.
1.1 if Statement
The if statement executes a block of code only if the given condition is true.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.\n");
}
return 0;
}
1.2 if-else Statement
The if-else statement provides an alternative block of code if the condition is false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else
{
printf("Number is negative.");
}
return 0;
}
1.3 if-else-if Ladder
Syntax:
if (condition1)
{
// Code for condition1
}
else if (condition2)
{
// Code for condition2
}
else
{
// Default block
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else if(num<0)
{
printf("Number is negative.");
}
else
{
printf("Number is Zero.");
}
return 0;
}
1.4 Nested if Statement
Example:
#include <stdio.h>
int main()
{
int temperature = 35;
else
{
printf("It's a hot day.\n");
}
}
else
{
printf("The weather is pleasant.\n");
}
return 0;
}
Write a c program to read a character from the user and check whether it is a vowel or consonant.
(June 2022 – 2019 Scheme)
#include <stdio.h>
int main()
{
char ch;
return 0;
The switch statement is used when there are multiple choices, and execution depends on the
value of a variable.
Syntax:
switch(expression)
{
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Default case (optional)
}
Example:
#include <stdio.h>
int main()
{
char signal;
printf("Enter a character : ");
scanf("%c",&signal);
switch(signal) {
case 'R':
printf("Stop\n");
break;
case 'Y':
printf("Get Ready\n");
break;
case 'G':
printf("Go\n");
break;
default:
printf("Invalid Signal\n");
}
return 0;
}
Write a c program to implement basic arithmetic operations of a calculator using switch
constructs. (May 2024 – 2019 scheme)
#include <stdio.h>
int main() {
double num1, num2, result;
char op;
switch(op) {
case '+':
result = num1 + num2;
printf("Result: %.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0)
printf("Result: %.2lf / %.2lf = %.2lf\n", num1, num2, num1
/ num2);
else
printf("Error! Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
Write a menu driven program to find the area of square,triangle,circle and rectangle according to
the choice given. (June 2023 – 2019 Scheme)
#include <stdio.h>
#include <math.h>
int main() {
int choice;
double area, side, base, height, radius, length, width;
case 2: // Triangle
printf("Enter the base and height of the triangle: ");
scanf("%lf %lf", &base, &height);
area = 0.5 * base * height;
printf("Area of Triangle: %.2lf\n", area);
break;
case 3: // Circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = M_PI* radius * radius; // Using M_PI from math.h
printf("Area of Circle: %.2lf\n", area);
break;
case 4: // Rectangle
printf("Enter the length and width of the rectangle: ");
scanf("%lf %lf", &length, &width);
area = length * width;
printf("Area of Rectangle: %.2lf\n", area);
break;
default:
printf("Invalid choice! Please enter a number between 1 and
4.\n");
}
return 0;}
Control Statements in C
Introduction
Control statements in C determine the flow of execution in a program. These statements
allow programmers to make decisions, loop through code, and jump to different parts of a
program based on conditions.
1.1 if Statement
The if statement executes a block of code only if the given condition is true.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.\n");
}
return 0;
}
1.2 if-else Statement
The if-else statement provides an alternative block of code if the condition is false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else
{
printf("Number is negative.");
}
return 0;
}
1.3 if-else-if Ladder
Syntax:
if (condition1)
{
// Code for condition1
}
else if (condition2)
{
// Code for condition2
}
else
{
// Default block
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else if(num<0)
{
printf("Number is negative.");
}
else
{
printf("Number is Zero.");
}
return 0;
}
1.4 Nested if Statement
Example:
#include <stdio.h>
int main()
{
int temperature = 35;
else
{
printf("It's a hot day.\n");
}
}
else
{
printf("The weather is pleasant.\n");
}
return 0;
}
Write a c program to read a character from the user and check whether it is a vowel or consonant.
(June 2022 – 2019 Scheme)
#include <stdio.h>
int main()
{
char ch;
return 0;
The switch statement is used when there are multiple choices, and execution depends on the
value of a variable.
Syntax:
switch(expression)
{
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Default case (optional)
}
Example:
#include <stdio.h>
int main()
{
char signal;
printf("Enter a character : ");
scanf("%c",&signal);
switch(signal) {
case 'R':
printf("Stop\n");
break;
case 'Y':
printf("Get Ready\n");
break;
case 'G':
printf("Go\n");
break;
default:
printf("Invalid Signal\n");
}
return 0;
}
Write a c program to implement basic arithmetic operations of a calculator using switch
constructs. (May 2024 – 2019 scheme)
#include <stdio.h>
int main() {
double num1, num2, result;
char op;
switch(op) {
case '+':
result = num1 + num2;
printf("Result: %.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0)
printf("Result: %.2lf / %.2lf = %.2lf\n", num1, num2, num1
/ num2);
else
printf("Error! Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
Write a menu driven program to find the area of square,triangle,circle and rectangle according to
the choice given. (June 2023 – 2019 Scheme)
#include <stdio.h>
#include <math.h>
int main() {
int choice;
double area, side, base, height, radius, length, width;
case 2: // Triangle
printf("Enter the base and height of the triangle: ");
scanf("%lf %lf", &base, &height);
area = 0.5 * base * height;
printf("Area of Triangle: %.2lf\n", area);
break;
case 3: // Circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = M_PI* radius * radius; // Using M_PI from math.h
printf("Area of Circle: %.2lf\n", area);
break;
case 4: // Rectangle
printf("Enter the length and width of the rectangle: ");
scanf("%lf %lf", &length, &width);
area = length * width;
printf("Area of Rectangle: %.2lf\n", area);
break;
default:
printf("Invalid choice! Please enter a number between 1 and
4.\n");
}
return 0;}
Used when the number of iterations is unknown but the loop must continue while a condition
is true.
Syntax:
while(condition)
{
// Code to execute
}
Example: 1
#include <stdio.h>
int main()
{
int i = 0;
while(i < 10)
{
printf("TechTalkz\n");
i++;
}
return 0;
}
Example: 2
#include <stdio.h>
int main()
{
int i = 5;
while(i >= 1)
{
printf("%d\n", i);
i--;
}
return 0;
}
Syntax:
do
{
// Code to execute
} while(condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do
{
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
}
2.1 for Loop
Syntax:
Example:
#include <stdio.h>
int main()
{
for(int i = 1; i <= 5; i++)
{
printf("%d ", i);
}
return 0;
}
int main()
{
int n;
printf("Enter n = ");
scanf("%d",&n);
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
printf("Sum = %d", sum);
return 0;
}
3. Jump Statements (Control Transfer)
Jump statements alter the normal flow of execution.
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if(i == 3)
{
break;
}
printf("%d ", i);
}
return 0;
}
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++)
{
if(i == 3)
{
continue;
}
printf("%d ", i);
}
return 0;
}
3.3 goto Statement
Example:
#include <stdio.h>
int main ()
{
int n = 0;
if (n == 0
{
goto end;
}
printf("The number is: %d\n", n);
end:printf ("End of program");
return 0;
}
Q. Write a c Program to find the sum of first and last digit of a
number.
#include<stdio.h>
int main()
int num,first,last,sum;
scanf("%d",&num);
last = num%10;
first = num;
while(first >=10)
first = first/10
sum = first+last;
printf("Sum = %d",sum);
return 0;
#include<stdio.h>
int main()
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
scanf("%d",&key);
for(i=0;i<n;i++)
if(arr[i]==key)
found = 1;
break;
if(!found)
arr[n] = key;
n++;
for(i=0;i<n;i++)
printf("%d ",arr[i]);
}
return 0;