C Programming Unit3 Notes
C Programming Unit3 Notes
Control structures define the flow of execution in a program. In C, control structures are
broadly divided into Branching Statements and Looping Statements.
Branching Statements
Branching statements allow the program to make decisions based on certain conditions.
They are categorized as Conditional Statements and Unconditional Statements.
1. Conditional Statements
Conditional statements execute a block of code depending on whether a condition is true
or false.
(i) if Statement
The if statement executes a block of code only if the condition is true.
Syntax:
if (condition) {
// Code to execute if the condition is true
}
Example 1:
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
Example 2:
#include <stdio.h>
int main() {
int age = 18;
if (age >= 18) {
printf("Eligible to vote.\n");
}
return 0;
}
(ii) if-else Statement
Executes one block of code if the condition is true and another block if the
condition is false.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example 1:
#include <stdio.h>
int main() {
int num = -5;
if (num >= 0) {
printf("The number is non-negative.\n");
} else {
printf("The number is negative.\n");
}
return 0;
}
Example 2:
#include <stdio.h>
int main() {
int marks = 40;
if (marks >= 50) {
printf("You passed.\n");
} else {
printf("You failed.\n");
}
return 0;
}
(iii) Nested if Statement
An if statement inside another if or else block.
Syntax:
if (condition1) {
if (condition2) {
// Code to execute if both conditions are true
}
}
Example 1:
#include <stdio.h>
int main() {
int num = 15;
if (num > 0) {
if (num % 2 == 0) {
printf("The number is positive and even.\n");
} else {
printf("The number is positive and odd.\n");
}
}
return 0;
}
Example 2:
#include <stdio.h>
int main() {
int a = 10, b = 20;
if (a > 0) {
if (b > 0) {
printf("Both numbers are positive.\n");
}
}
return 0;
}
(iv) else-if Ladder
Checks multiple conditions sequentially.
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if no conditions are true
}
Example 1:
#include <stdio.h>
int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Example 2:
#include <stdio.h>
int main() {
int age = 25;
if (age < 13) {
printf("Child.\n");
} else if (age < 20) {
printf("Teenager.\n");
} else {
printf("Adult.\n");
}
return 0;
}
(v) switch Statement
Tests a variable against multiple values.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
Example 1:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
Example 2:
#include <stdio.h>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good.\n");
break;
case 'C':
printf("Fair.\n");
break;
default:
printf("Invalid grade.\n");
}
return 0;
}
2. Unconditional Statements
Unconditional statements alter the normal flow of control in the program.
(i) goto Statement
Transfers control to a labeled statement.
Syntax:
goto label;
...
label:
Example 1:
#include <stdio.h>
int main() {
int num = 1;
if (num == 1) {
goto label;
}
printf("This won't print.\n");
label:
printf("Jumped to label.\n");
return 0;
}
(ii) break Statement
Exits a loop or switch case.
Syntax:
break;
Example 1:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
printf("%d\n", i);
}
return 0;
}
(iii) continue Statement
Skips the current iteration of a loop.
Syntax:
continue;
Example 1:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("%d\n", i);
}
return 0;
}
Looping Statements
Looping statements execute a block of code repeatedly based on a condition. They are
classified into entry-controlled and exit-controlled loops.
1. for Loop
Definition
The for loop is an entry-controlled loop used when the number of iterations is known
beforehand.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example 1: Print numbers from 1 to 5
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Example 2: Calculate the sum of first 10 natural numbers
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
printf("Sum: %d\n", sum);
return 0;
}
2. Nested for Loop
Definition
A loop inside another loop where the inner loop executes completely for every iteration
of the outer loop.
Syntax
for (initialization1; condition1; increment/decrement1) {
for (initialization2; condition2; increment/decrement2) {
// Code to execute
}
}
Example 1: Multiplication table
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%d\t", i * j);
}
printf("\n");
}
return 0;
}
Example 2: Print a star pattern
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
3. while Loop
Definition
The while loop is an entry-controlled loop that executes as long as the condition is true.
Syntax
while (condition) {
// Code to execute
}
Example 1: Print numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Example 2: Calculate the factorial of a number
#include <stdio.h>
int main() {
int num = 5, fact = 1;
while (num > 0) {
fact *= num;
num--;
}
printf("Factorial: %d\n", fact);
return 0;
}
4. do-while Loop
Definition
The do-while loop is an exit-controlled loop that executes the block of code at least once.
Syntax
do {
// Code to execute
} while (condition);
Example 1: Print numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Example 2: Prompt user until a positive number is entered
#include <stdio.h>
int main() {
int num;
do {
printf("Enter a positive number: ");
scanf("%d", &num);
} while (num <= 0);
printf("You entered: %d\n", num);
return 0;
}
Arrays in C
Definition of an Array
Characteristics of Arrays
• Homogeneous Elements: All elements of an array must be of the same data type,
such as int, float, char, or double.
• Consecutive Memory Allocation: Elements are stored in contiguous memory
locations.
• Single Identifier: An array is referenced by a single name (or identifier).
• Indexed Access: Array elements are accessed using indices (or subscripts), starting
from index 0.
data_type array_name[size];
Example:
1. int list[10];
This declares an array list of size 10 to store int values.
2. char name[20];
This declares an array name of size 20 to store char values.
3. float p[5];
This declares an array p of size 5 to store float values.
Array Indexing
data_type array_name[size];
Where:
int numbers[5];
char letters[10];
float prices[20];
Initialization at Declaration
If fewer values are provided, the remaining elements are automatically set to 0.
Accessing Elements
• The first element of an array has an index of 0, the second element has an index of
1, and so on.
• Example: For an array arr[5] = {1, 2, 3, 4, 5}, the following accesses the first
element: arr[0].
#include <stdio.h>
void main() {
int i, n, num[20];
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
printf("Array elements are:\n");
for(i = 0; i < n; i++) {
printf("%d\n", num[i]);
}
}
#include <stdio.h>
void main() {
int i, n, a[20], b[20], sum[20];
printf("Enter the size of the arrays: ");
scanf("%d", &n);
printf("Enter the elements of the first array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the elements of the second array:\n");
for(i = 0; i < n; i++) {
scanf("%d", &b[i]);
}
printf("Sum of the two arrays is:\n");
for(i = 0; i < n; i++) {
sum[i] = a[i] + b[i];
printf("sum[%d] = %d\n", i, sum[i]);
}
}
Two-Dimensional Arrays in C
A 2D array is an array in which each element is itself an array. It can be used to represent
data in rows and columns, such as a matrix, table, or grid.
data_type array_name[row_size][column_size];
Example:
int matrix[3][4];
This declares a 2D array matrix with 3 rows and 4 columns. The total number of elements
in this array is 3 * 4 = 12.
To access elements in a 2D array, you need to specify both the row and column index:
• matrix[0][0]: Accesses the element in the first row and first column.
• matrix[1][2]: Accesses the element in the second row and third column.
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
• matrix[0][0] gives 1.
• matrix[1][2] gives 7.
• matrix[2][3] gives 12.
Initialization at Declaration
You can initialize a 2D array at the time of declaration by providing values for each row
and column.
Example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
This initializes a 3x3 matrix, where the first row is {1, 2, 3}, the second row is {4, 5, 6}, and
the third row is {7, 8, 9}.
If fewer values are provided, the remaining elements are automatically set to 0.
Example:
int matrix[3][3] = {
{1, 2},
{3, 4}
};
This initializes a 3x3 matrix:
{1, 2, 0}
{3, 4, 0}
{0, 0, 0}
Matrix Addition
This program allows the user to enter values for two matrices, then adds the
corresponding elements of both matrices and displays the result.
#include <stdio.h>
void main() {
int i, j, row, col;
// Taking input for the number of rows and columns
printf("Enter number of rows: ");
scanf("%d", &row);
printf("Enter number of columns: ");
scanf("%d", &col);
int matrix1[row][col], matrix2[row][col], sum[row][col];
// Input values for the first matrix
printf("Enter elements of the first matrix:\n");
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
printf("Element at [%d][%d]: ", i+1, j+1);
scanf("%d", &matrix1[i][j]);
}
}
// Input values for the second matrix
printf("Enter elements of the second matrix:\n");
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
printf("Element at [%d][%d]: ", i+1, j+1);
scanf("%d", &matrix2[i][j]);
}
}
// Adding corresponding elements of matrix1 and matrix2
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Displaying the result of addition
printf("\nSum of the matrices:\n");
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
}
Example Output:
Enter number of rows: 2
Enter number of columns: 2
Enter elements of the first matrix:
Element at [1][1]: 1
Element at [1][2]: 2
Element at [2][1]: 3
Element at [2][2]: 4
Enter elements of the second matrix:
Element at [1][1]: 5
Element at [1][2]: 6
Element at [2][1]: 7
Element at [2][2]: 8
Matrix Subtraction
This program allows the user to enter values for two matrices, then subtracts the
corresponding elements of both matrices and displays the result.
#include <stdio.h>
void main() {
Declaring a String
char str[50]; // Declares a string with a capacity of 50 characters
Initializing a String
char str[] = "Hello"; // The size of the array is automatically set based on the string's
length.
char str[50];
printf("Enter a string: ");
scanf("%s", str); // Input string without spaces
char str[50];
strcpy(str, "Hello, World!"); // Copies the string into str
C provides several built-in functions in the string.h library for handling strings. Let's
explore some commonly used ones:
strlen Function
The strlen function is used to calculate the length of a string (excluding the null character
\0).
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length of the string: %lu\n", strlen(str));
return 0;
}
Output:
The strcmp function compares two strings lexicographically (i.e., in dictionary order).
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "hello";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("First string is less than second string.\n");
} else {
printf("First string is greater than second string.\n");
}
return 0;
}
Output:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[50];
strcpy(str2, str1); // Copies str1 to str2
printf("Copied string: %s\n", str2);
return 0;
}
Output:
The strcat function appends one string to the end of another string.
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
strcat(str1, str2); // Appends str2 to str1
printf("Concatenated string: %s\n", str1);
return 0;
}
Output:
In addition to string handling functions, C also provides several functions in the ctype.h
library for character manipulation.
toascii Function
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
printf("ASCII value of '%c' is %d\n", ch, toascii(ch));
return 0;
}
Output:
The toupper function converts a lowercase letter to uppercase, and the tolower function
converts an uppercase letter to lowercase.
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'a';
printf("Uppercase of '%c' is '%c'\n", ch, toupper(ch));
ch = 'Z';
printf("Lowercase of '%c' is '%c'\n", ch, tolower(ch));
return 0;
}
Output:
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
if (isalpha(ch)) {
printf("'%c' is an alphabet letter.\n", ch);
} else {
printf("'%c' is not an alphabet letter.\n", ch);
}
return 0;
}
Output:
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = '5';
if (isdigit(ch)) {
printf("'%c' is a digit.\n", ch);
} else {
printf("'%c' is not a digit.\n", ch);
}
return 0;
}
Output:
'5' is a digit.
isalnum Function
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'a';
if (isalnum(ch)) {
printf("'%c' is an alphanumeric character.\n", ch);
} else {
printf("'%c' is not an alphanumeric character.\n", ch);
}
return 0;
}
Output
The isspace function checks if a character is a whitespace character (such as a space, tab,
or newline).
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = ' ';
if (isspace(ch)) {
printf("'%c' is a whitespace character.\n", ch);
} else {
printf("'%c' is not a whitespace character.\n", ch);
}
return 0;
}
Output: