0% found this document useful (0 votes)
39 views24 pages

Unit Ii

Uploaded by

subham285sahoo
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)
39 views24 pages

Unit Ii

Uploaded by

subham285sahoo
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/ 24

UNIT II

Introduction to C Programming: Control Flow, Conditional Branching Statements: if, if-else, if-
else—if, switch. Basic Loop Structures: while, do-while loops, for loop, nested loops, The Break
and Continue Statements, goto statement.
Arrays: Introduction, Operations on Arrays, Arrays as Function Arguments, Two Dimensional
Arrays, Multidimensional Arrays.
Strings: String Fundamentals, String Processing with and without Library Functions, Pointers and
Strings.

Introduction:
Control flow refers to the order in which individual instructions, statements, or function calls are
executed in a program. It determines how the execution progresses from one point in the program
to another, based on conditions, loops, or function calls.
Types of Control Statements in C
The primary types of control statements in C are:
1.Decision-making control statements

 Simple if statement
 If-else statements
 Nested if-else statements
 else-if ladder
 Switch

2. Loop control statements in C

 While Loop
 Do-while Loop
 For Loop

3. Jump statements in C

 break.
 Continue.
 Goto
Conditional statements: The conditional statements are

a. Simple if statement:
If the Boolean condition evaluates to true, then the block of code inside the 'if' statement will
be executed. If the Boolean expression evaluates to false, then the first set of code after the
end of the 'if' statement (after the closing curly brace) will be executed.
Syn: if(condition)
{
Statements;
}
Ex:
int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
b. If..else statement:
In C if else control statement, group of statements are executed when condition is true. If
condition is false, then else part statements are executed.
Syn: if (condition)
{
Statement1;
Statement2;
}
else
{
Statement3;
Statement4;
}

Ex: #include <stdio.h>


int main()
{ int m=40,n=20;
if (m == n)
printf("m and n are equal");
else
printf("m and n are not equal");
}
c. Nested if-else:
 In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true.
 If condition 2 also gets failure, then else part is executed.
Syn: if (condition1)
{
Statement1;
}
elseif (condition2)
{
Statement2;
}
else
Statement 3;
Example program
#include <stdio.h>
int main() {
int m=40,n=20;
if (m>n)
printf("m is greater than n");
else if(m<n)
printf("m is less than n");
else
printf("m is equal to n");
}
If else Ladder Statement in C Programming
The if else ladder statement in C programming language is used to test set of conditions in
sequence. If any of the conditional expression evaluates to true, then it will execute the
corresponding code block and exits whole if-else ladder.
An if condition is tested only when all previous if conditions in if-else ladder is false.
Syntax:
if(condition1)
{
statement1; }
elseif (condition2)
{
statement2; }
else if (condition3)
{
statement3;
}
else
{
statement4;
}
 First of all condition1 is tested and if it is true then statement1 will be executed and control
comes out of whole if else ladder.
 If condition1 is false then only condition2 is tested. Control will keep on flowing downward, If
none of the conditional expression is true.
 The last else is the default block of code which will gets executed if none of the conditional
expression is true.
C Program to print grade of a student using If Else Ladder Statement
#include<stdio.h>
#include<conio.h>
void main()
{
int marks;
printf("Enter your marks between 0-100\n");
scanf("%d", &marks);
if(marks >= 90)
printf("YOUR GRADE : A\n");
else if (marks >= 70 && marks < 90)
printf("YOUR GRADE : B\n");
else if (marks >= 50 && marks < 70)
printf("YOUR GRADE : C\n");
else
printf("YOUR GRADE : Failed\n");
getch();
}

Switch Statement:
the switch statement will allow multi-way branching. Depending on the expression, the
control is transferred to that particular case label and executed the statements under it. If none of
the cases are matched with the switch expression, then the default statement is executed.
The syntax of the switch statement is as given below:
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;

case value_n: statement_n;


break;
default: default_statement;
}
Key Points:
1. Expression: This is the value you want to compare. It is usually an integer or a character in
many languages .
2. Cases: Each case represents a possible value for the expression. When a case matches the
value of the expression, the code associated with that case is executed. Every case must
have case label followed by colon.
3. Break: The break statement is used to exit the switch statement once a matching case has
been found and executed. If you omit break, the execution will "fall through" to the next
case, which might not be what you want.
4. Default: The default block is optional and is executed if none of the case values match the
expression.
Output:

Q: Explain about C – Looping control statements?


A loop statement allows us to execute a statement or group of statements multiple
timesuntil the given condition is true. Control comes out of the loop statements once condition
becomes false.
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They are,
1. for
2. while
3. do-while
1. For loop:
 A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to be executed a specific number of times.
 for loop is useful when you know how many times a task is to be repeated.
Syntax: for(initialization; Boolean_expression; update)
{
// Statements
}
 The initialization step is executed first, and only once.
This step allows you to declare and initialize any loop
control variables.
 Next, the Boolean expression is evaluated. If it is true,
the body of the loop is executed. If it is false, the body of
the loop will not be executed and control jumps to the next statement after the for loop.
 After the body of the for loop gets executed, the control jumps back up to the
update(inc/dec) statement. This statement allows you to update any loop control variables.
 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats. After the Boolean expression is false, the for loop terminates.
#include <stdio.h>
int main() {
int i;
for(i=0;i<10;i++)
printf("%d ",i);
}
Nested loop: Nested loops are loops placed inside other loops. In a nested loop, the inner loop is
executed entirely for each iteration of the outer loop. This is often used for processing multi-
dimensional data structures like 2D arrays or matrices.
Example of Nested Loops
for (int i = 1; i <= 3; i++)
{ // Outer loop
for (int j = 1; j <= 2; j++)
{ // Inner loop
printf("i = %d, j = %d\n", i, j);
}
}
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

Explanation:
 The outer loop runs 3 times (i = 1, i = 2, i = 3).
 For each iteration of the outer loop, the inner loop runs completely, i.e., 2 times (j = 1, j =
2).
 This results in the inner loop being executed a total of 3 * 2 = 6 times.
2. While loop:
The while statement continually executes a block of statements while a particular
condition is true. It is called as entry level loop control structure.
Syntax: while (condition)
{
statement(s);
Increment/decrement;
}
The while statement evaluates condition, which must return a boolean value. If the
condition evaluates to true, the while statement executes the statement(s) in the while block.
The while statement continues testing the condition and executing its block until the condition
evaluates to false.
Ex:
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
2. Do while loop:
 In do..while loop control statement, while loop is executed irrespective of the condition for
first time. Then 2nd time onwards, loop is executed until condition becomes false.
 It called as exit level loop control structure.
Syn: do {
statements;
}
while (condition);
Ex: #include <stdio.h>
int main() {
int i=1;
do {
printf("Value of i is %d\n",i);
i++;
}while(i<=4 &&i>=2);
}
Difference between while & do while loops in C:
S.no while do while
1 Loop is executed only Loop is executed for first time irrespective of the condition.
when condition is true. After executing while loop for first time, then condition is
checked.
2 Entry level loop control Exit level loop control structure.
structure

3. Jumping statements/unconditional statements: C supports the following jumping statements


1. break
2. continue
3. goto
Break statement in C:
The break statement in C programming has the following two usages −
 When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
 It can be used to terminate a case in the switch statement (covered in the next chapter).
Syntax: break;
Example program for break statement in C:
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
}
Continue statement in C:
Continue statement is used to continue the next iteration. So, the remaining statements
are skipped within the loop for that particular iteration.
Syntax: continue;

Example program for continue statement in C:


#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nSkipping %d from display ",i); continue;}
printf(“%d”,i); }
}

goto statement in C:
 goto statements is used to transfer the normal flow of a program to the specified label in
the program.
 Below is the syntax for goto statement in C.
go to label;
…….
…….
LABEL:
statements;
Example program for goto statement in C:
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nWe are using goto statement when i = 5");
goto GMRIT;
}
printf("%d ",i);
}
GMTIT :printf("\nNow, we are stdying in gmrit \n");
}
Explain Array in C Language:
An array in C is a fixed-size collection of similar data items stored in contiguous memory locations.
It can be used to store the collection of primitive data types such as int, char, float, etc., and also
derived and user-defined data types such as pointers, structures, etc.
Def: An array may be defined as finite ordered set of homogenous elements.i.e limited number
of elements of same data type
Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare an array
by specifying its name, the type of its elements, and the size of its dimensions. When we declare
an array in C, the compiler allocates the memory block of the specified size to the array name.

Syntax of Array Declaration


data_type array_name [size];
Examples: int marks[10],;
char name[50];
Array Declaration: The C arrays are static in nature, i.e., they are allocated memory at the compile
time in order to declare the array use the following syntax
Example of Array Declaration
#include <stdio.h>
int main()
{ // declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}
C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the
array is declared or allocated memory, the elements of the array contain some garbage value. So,
we need to initialize the array to some meaningful value. There are multiple ways in which we can
initialize an array in C.
1. Array Initialization with Declaration
In this method, we initialize the array along with its declaration. We use an initializer list
to initialize multiple elements of the array. An initializer list is the list of values enclosed within
braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};

2. Array Initialization with Declaration without Size


If we initialize an array using an initializer list, we can skip declaring the size of the
array as the compiler can automatically deduce the size of the array in these cases. The size of the
array in these cases is equal to the number of elements present in the initializer list as the
compiler can automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the compiler.
3. Array Initialization after Declaration (Using Loops)
We initialize the array after the declaration by assigning the initial value to each
element individually. We can use for loop, while loop, or do-while loop to assign the value to each
element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example of Array Initialization in C
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{ // array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}
Access Array Elements: We can access any element of an array in C using the array subscript
operator [ ] and the index value i of the element.

array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at
index 0 and the last element is at N – 1 where N is the number of elements in the array.
Operations on arrays:Operations on arrays involve various tasks that manipulate or utilize the
elements within the array. Arrays are widely used for storing data, and operations on them are
fundamental in programming. Below are common operations that can be performed on arrays:
1. Traversal
Traversing means visiting each element of the array. This is often done using loops to access and
possibly modify the elements.
int arr[] = {10, 20, 30, 40};
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
10 20 30 40
2. Insertion
Inserting an element into an array can involve shifting elements if the array has fixed size. For
dynamic arrays, elements can be added easily.
for (int i = n; i > pos; i--) {
arr[i] = arr[i-1]; } // Shift elements to the right
arr[pos] = x; // Insert new element
n++; // Increment the size
3. Deletion
Deleting an element from an array involves shifting elements to fill the gap left by the deleted
element.
for (int i = pos; i < n-1; i++) {
arr[i] = arr[i+1]; // Shift elements to the left
}
n--; // Decrease the size
4. Searching
Searching involves finding the index of an element in the array. There are different searching
techniques like linear search and binary search.
 Linear search: Check each element one by one.
 Binary search: Used on sorted arrays, divides the array into halves to search.
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
found = i; break; } }
5. Sorting
Sorting arranges the elements of the array in a specific order (ascending or descending). Common
algorithms include Bubble Sort, Selection Sort, Merge Sort, and Quick Sort.
Example
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
} } }
6. Merging
Merging combines two or more sorted arrays into a single sorted array.
7. Reversing
Reversing an array means swapping elements from the beginning and end of the array.
8.Update Array Element
We can update the value of an element at the given index i in a similar way to accessing an
element by using the array subscript operator [ ] and assignment operator =.
array_name[i] = new_value;
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They are as follows:
One Dimensional Arrays (1D Array)
The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.
Syntax of 1D Array in C
array_name [size];
Example : int arr[5];
// C Program to illustrate the use of 1D array
#include <stdio.h>
int main() {
// Declare and initialize an array
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements in the array
// Print each element of the array
printf("Array elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
return 0;
}
Output
Array elements are:
10 20 30 40 50
Array of Characters (Strings)
In C, we store the words, i.e., a sequence of characters in the form of an array of characters
terminated by a NULL character. These are called strings in C language.
// C Program to illustrate strings
#include <stdio.h>
int main() {
char arr[6] = { 'M', 'A', 'D', 'H', 'A', ’v’ ,’I’, '\0' }; // creating array of
character
int i = 0;
while (arr[i]) {
printf("%c", arr[i++]);
} return 0; }
Output
MADHAVI
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the
popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more
dimensions than 3d arrays but they are avoided as they get very complex and occupy a large
amount of space.
A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be
visualized in the form of rows and columns organized in a two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
Here, size1: Size of the first dimension. size2: Size of the second dimension.
Example of 2D Array in C: int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
#include <stdio.h>
int main() {
// Define a 2D array with 3 rows and 3 columns
int arr[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]); // Print the element at position (i, j)
}
printf("\n"); // Move to the next line after printing one row
}
return 0;
}
B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A 3D
array has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked on top
of each other to create the third dimension.
Syntax of 3D Array in C
array_name [size1] [size2] [size3];
C Program to find the largest number in an array using loop
#include <stdio.h>
int main()
{
int size, i, largest;

printf("\n Enter the size of the array: ");


scanf("%d", &size);
int array[size]; //Declaring array
//Input array elements
printf("\n Enter %d elements of the array: \n", size);

for (i = 0; i < size; i++)


{ scanf(" %d", &array[i]);
}
//Declaring Largest element as the first element
largest = array[0];
for (i = 1; i < size; i++)
{
if (largest < array[i])
largest = array[i];
}
printf("\n largest element present in the given array is : %d", largest);
return 0;
}

This c program for addition of two matrices.


#include <stdio.h>
void main()
{
int r, c, a[10][10], b[10][10], sum[10][10], i, j;
printf("\nEnter elements of 1st matrix:\n");
for(i=0; i<2; ++i)
for(j=0; j<5; ++j)
{
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for(i=0; i<2; ++i)
for(j=0; j<5; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf(" %d", &b[i][j]);
}
// Adding Two matrices
for(i=0;i<2;++i)
for(j=0;j<5;++j)
{
sum[i][j]=a[i][j]+b[i][j];
}
// Displaying the result
printf("\nSum of two matrix is: \n\n");
for(i=0;i<2;++i)
for(j=0;j<5;++j)
{
printf("%d ",sum[i][j]);
}
printf(“\n"); } } }
Array as Function Parameters:
In c we can pass array as parameter to the function.
 When declaring a function that takes an array as a parameter, you can use the following
forms:
o void myFunction(int arr[]) or
o void myFunction(int *arr)
 Both forms are equivalent because an array is just a pointer to the first element.
 Example:
void myFunction(int arr[]) {
// Same as void myFunction(int *arr)
}
Explain about String’s in C?
 C Strings are nothing but array of characters ended with null character (‘\0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is enclosed
by single quotes Example for C string:
 char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘e’,’r’}; (or)
 char string[20] = “fresher”; (or)
 char string [] = “fresher”;
 Difference between above declarations are, when we declare char as “string[20]“, 20 bytes
of memory space is allocated for holding the string value.
 When we declare char as “string[]“, memory space will be allocated as per the requirement
during execution of the program.
Example program for C string:
#include <stdio.h>
int main ()
{
char string[20] = "GMRIT";
printf("The string is : %s \n", string );
return 0;
}
C String functions:
String.h header file supports all the string functionsin C language. All the string functions
are given below.
strcat():
Strcat( ) function in C language concatenates two given strings. It concatenates source
string at the end of destination string.
Syntax:strcat( str2, str1 );
str2 is concatenated at the end of str1.
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " GMRIT" ;
char target[ ]= " College" ;
printf( "\nSource string = %s", source ) ;
printf( "\nTarget string = %s", target ) ;
strcat( target, source ) ;
printf( "\nTarget string after strcat( ) = %s", target ) ;
}
strcpy():
strcpy( ) function copies contents of one string into another string.
Syntax: strcpy(str1, str2);
It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t
be copied into destination string will be truncated.
Ex: strcpy (target, source ) ;
strlen():
strlen( ) function counts the number of characters in a given string and returns the integer
value.It stops counting the character when null character is found. Because, null
character indicates the end of the string in C.
Ex: len = strlen(array) ;
strcmp():
This function in C compares two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value.
If length of string1 > string2, it returns > 0 value.
Syntax for strcmp ) function is given below.
strcmp (str1, str2 );
strcmp( ) function is case sensitiv. i.e, “A” and “a” are treated as different characters.
strcmpi():
This function in C is same as strcmp() function. But, strcmpi( ) function is not case sensitive.
i.e, “A” and “a” are treated as same characters. Where as, strcmp() function treats “A” and
“a” as different characters.
strcmpi (str1, str2 );
strlwr():
strlwr( ) function converts a given string into lowercase.
strlwr(string);
strupr():
strupr( ) function converts a given string into uppercase.
strupr(string);
strrev():
strrev( ) function reverses a given string in C language.
strrev(string);

Ex: Program for handling strings by using string handling functions in c:


#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " GMRIT” ;
char target[ ]= " College" ;
int c,l;
char s1[10],s2[10];
printf( "\nSource string = %s", source ) ;
printf( "\nTarget string = %s", target ) ;
strcat( target, source ) ;
printf( "\nTarget string after strcat( ) = %s", target ) ;
c=strcmpi (target, source);
printf( "\n the camparisions strings are %d”,c);
l= strcat( target);
printf( "\n the length of target string are %d”,l);
s1=strlow(source);
printf( "\n The lower case string is”,s);
s2=strupr(target);
printf( "\n The upper case string is”,s2);
strrev(soure);
printf( "\n The reverse Source string = %s", source ) ;
getch();}
}
String Handling With out Library functions:
In C language without using standard library functions, you'll need to manually implement
operations such as copying, comparing, or calculating the length of a string .Some of them are as
follows.
String length calculation:
Char s[]=”MADHAVI PERLA”;
It will automatically add \0 at the end of the string
Void main()
{
int length = 0,i;
Char s[]=”MADHAVI PERLA”;
while (s[i] != '\0') {
length++;
printf(“Length of the string is %d”,length);
}
String copy:
We can copy the content from string to another string
void stringCopy(char dest[], char src[])
{ int i = 0;
while (src[i] != '\0')
{
dest[i] = src[i]; i++;
}
dest[i] = '\0'; // Null-terminate the destination string
}

You might also like