0% found this document useful (0 votes)
8 views27 pages

C Programming Unit3 Notes

The document provides an overview of control structures in C programming, categorizing them into branching statements (like if, if-else, switch) and looping statements (for, while, do-while). It also explains arrays, detailing their definition, characteristics, declaration, and types, including one-dimensional and two-dimensional arrays. Examples are provided for each control structure and array usage to illustrate their application in C.

Uploaded by

dbossd183
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)
8 views27 pages

C Programming Unit3 Notes

The document provides an overview of control structures in C programming, categorizing them into branching statements (like if, if-else, switch) and looping statements (for, while, do-while). It also explains arrays, detailing their definition, characteristics, declaration, and types, including one-dimensional and two-dimensional arrays. Examples are provided for each control structure and array usage to illustrate their application in C.

Uploaded by

dbossd183
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/ 27

Control Structures in C: Branching and Looping

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

An array in C is an ordered collection of elements of the same data type stored in


consecutive memory locations. Arrays are used to store multiple values in a single
variable, rather than declaring individual variables for each value.

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.

Syntax for Declaring an Array

data_type array_name[size];

• data_type: Specifies the type of data (e.g., int, float, char).


• array_name: The identifier for the array.
• size: The number of elements to be stored in the array (must be a positive integer).

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

Array elements are accessed using subscripts (indexes). For example:

• even[0]: Accesses the first element in the array.


• even[1]: Accesses the second element in the array.
• even[i]: Accesses the element at index i.
Classification of Arrays

Arrays in C can be classified into two types:

1. One-Dimensional Arrays (1D Array)


A one-dimensional array is like a list of elements. Example: int arr[5];
2. Multi-Dimensional Arrays
Multi-dimensional arrays have more than one subscript:
o Two-Dimensional Array (2D Array)
Example: int matrix[3][3]; (a 3x3 matrix)
o Three-Dimensional Array (3D Array)
Example: int arr[3][3][3];
o n-Dimensional Array
An array with n dimensions.

One-Dimensional Arrays (1D Array)

Declaration of One-Dimensional Array

The general syntax is:

data_type array_name[size];

Where:

• data_type: The type of elements (e.g., int, float, char).


• array_name: The name of the array.
• size: The number of elements the array can hold.

Example of Declaring a 1D Array:

int numbers[5];
char letters[10];
float prices[20];

Initializing a One-Dimensional Array

Initialization at Declaration

You can initialize an array at the time of declaration.

int arr[5] = {1, 2, 3, 4, 5};

If fewer values are provided, the remaining elements are automatically set to 0.

int arr[5] = {1, 2}; // arr = {1, 2, 0, 0, 0}


Example of Array Initialization:

int evenum[4] = {2, 4, 6, 8};

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].

Rules for Array Indexing

1. Array indices must be positive integers.


2. C does not perform bound checking; accessing an element outside the defined
range can cause undefined behavior.
3. Array indexing starts from 0.

Example: Accepting and Printing Integer Values in an Array

#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]);
}
}

Example: Adding Two Arrays

#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 two-dimensional array (2D array) in C is an array of arrays, essentially creating a


matrix-like structure. It can be visualized as a table with rows and columns, where each
element is identified by two indices: one for the row and one for the column.

Definition of a Two-Dimensional Array

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.

Syntax for Declaring a Two-Dimensional Array

data_type array_name[row_size][column_size];

• data_type: Specifies the type of data (e.g., int, float, char).


• array_name: The name of the 2D array.
• row_size: The number of rows in the 2D array.
• column_size: The number of columns in the 2D array.

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.

Accessing Elements in a Two-Dimensional Array

To access elements in a 2D array, you need to specify both the row and column index:

• Row index: Identifies the row of the element.


• Column index: Identifies the column of the element.
For example, for a 2D array matrix[3][4]:

• 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.

Example of Accessing Elements

Given the 2D array:

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.

Initializing a Two-Dimensional Array

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}

Example Programs with Two-Dimensional Arrays

1. Reading and Printing Elements of a 2D Array


#include <stdio.h>
void main() {
int i, j, matrix[3][3];

// Input values for the 3x3 matrix


printf("Enter elements for the 3x3 matrix:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Output the matrix


printf("Matrix elements are:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
}
}
}
2. Sum of All Elements in a 2D Array
#include <stdio.h>
void main() {
int i, j, sum = 0, matrix[3][3];

// Input values for the 3x3 matrix


printf("Enter elements for the 3x3 matrix:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Sum of all elements
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
sum += matrix[i][j];
}
}
printf("Sum of all elements in the matrix is: %d\n", sum);
}

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

Sum of the matrices:


68
10 12

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() {

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], diff[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]);
}
}
// Subtracting corresponding elements of matrix1 and matrix2
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
diff[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
// Displaying the result of subtraction
printf("\nDifference of the matrices:\n");
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
printf("%d ", diff[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]: 9
Element at [1][2]: 8
Element at [2][1]: 7
Element at [2][2]: 6
Enter elements of the second matrix:
Element at [1][1]: 1
Element at [1][2]: 2
Element at [2][1]: 3
Element at [2][2]: 4

Difference of the matrices:


86
42

String and Character Handling in C

In C, strings are essentially arrays of characters. C provides several built-in functions to


handle strings and characters efficiently. Below are the details about string and character
handling functions.

Declaring and Initializing String Variables

In C, a string is an array of characters terminated by a special character '\0' (null


character). The size of the array needs to be specified at the time of declaration.

Declaring a String
char str[50]; // Declares a string with a capacity of 50 characters
Initializing a String

There are two ways to initialize strings:

Direct Initialization (Assigning a string literal):

char str[] = "Hello"; // The size of the array is automatically set based on the string's
length.

Using scanf or gets for Input:

char str[50];
printf("Enter a string: ");
scanf("%s", str); // Input string without spaces

Using strcpy Function:

char str[50];
strcpy(str, "Hello, World!"); // Copies the string into str

String Handling Functions

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:

Length of the string: 13


strcmp Function

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:

First string is less than second string.


strcpy Function

The strcpy function copies the content of one string to another.

#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:

Copied string: Hello


strcat Function

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:

Concatenated string: Hello World!

3. Character Handling Functions

In addition to string handling functions, C also provides several functions in the ctype.h
library for character manipulation.

toascii Function

The toascii function converts a character to its ASCII value.

#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:

ASCII value of 'A' is 65


toupper and tolower Functions

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:

Uppercase of 'a' is 'A'


Lowercase of 'Z' is 'z'
isalpha Function

The isalpha function checks if a character is an alphabet letter (either uppercase or


lowercase).

#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:

'A' is an alphabet letter.


isdigit and isnumeric Functions

The isdigit function checks if a character is a digit (0-9). In C, there's no isnumeric


function, but isdigit can be used similarly for numeric checks.

#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

The isalnum function checks if a character is either an alphabet letter or a digit.

#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

'a' is an alphanumeric character.


isspace Function

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:

' ' is a whitespace character.

You might also like