0% found this document useful (0 votes)
28 views

Module 2 Complete

The document provides a syllabus for Module 2 which includes topics like decision making using if, else if and switch statements, looping using while, do-while and for loops, arrays including single, multi-dimensional and nested arrays. It also discusses strings and string manipulation functions. Code examples are given to demonstrate if, if-else, if-else-if ladder, switch statements and use of break statement inside loops.

Uploaded by

LEESHMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Module 2 Complete

The document provides a syllabus for Module 2 which includes topics like decision making using if, else if and switch statements, looping using while, do-while and for loops, arrays including single, multi-dimensional and nested arrays. It also discusses strings and string manipulation functions. Code examples are given to demonstrate if, if-else, if-else-if ladder, switch statements and use of break statement inside loops.

Uploaded by

LEESHMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

MODULE 2

MODULE 2

1
MODULE 2 SYLLABUS

• Decision making - if statement, if else statement, nesting of if else and else if ladder, switch
statement, break statement, continue statement, goto statement, return statement.

• looping - while, do-while, and for loops, nesting of loops, skipping & breaking loops.

• Arrays - single dimension arrays - accessing array elements - initializing an array, two
dimensional & multi-dimensional arrays memory representation

• strings - processing of strings - string manipulation functions.

2
MODULE 2

Decision making

3
C if else statement
MODULE 2

• The if-else statement in C is used to perform the operations based on some


specific condition. The operations specified in if block are executed if and
only if the given condition is true.

• There are the following variants of if statement in C language.

1. if statement

2. if-else statement

3. if else-if ladder
4

4. Nested if
If Statement
MODULE 2

The if statement is used to check some given condition and perform some operations depending
upon the correctness of that condition. It is mostly used in the scenario where we need to perform
the different operations for the different conditions. The syntax of the if statement is given below.

if(expression){
//code to be executed
}

5
#include<stdio.h>
MODULE 2

int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
}

6
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter three numbers?");
MODULE 2

scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
{
printf("%d is largest",a);
}
if(b>a && b > c)
{
printf("%d is largest",b);
}
if(c>a && c>b)
{
printf("%d is largest",c);
}
if(a == b && a == c)
{
printf("All are equal");
7 }
}
If-else Statement
MODULE 2

• The if-else statement is used to perform two operations for a single condition.
• The if-else statement is an extension to the if statement using which, we can perform two
different operations, i.e., one is for the correctness of that condition, and the other is for the
incorrectness of the condition.
• Here, we must notice that if and else block cannot be executed simiulteneously. Using if-
else statement is always preferable since it always invokes an otherwise case with every if
condition.

8
if(expression){
MODULE 2

//code to be executed if condition is true


}else{
//code to be executed if condition is false
}

9
#include<stdio.h>
int main(){
int number=0;
MODULE 2

printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}
10
#include <stdio.h>
int main()
{
MODULE 2

int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
11
}
If else-if ladder Statement
MODULE 2

• The if-else-if ladder statement is an extension to the if-else statement.


• It is used in the scenario where there are multiple cases to be performed for different
conditions.
• In if-else-if ladder statement, if a condition is true then the statements defined in the if
block will be executed, otherwise if some other condition is true then the statements
defined in the else-if block will be executed, at the last if none of the condition is true
then the statements defined in the else block will be executed.
• There are multiple else-if blocks possible. It is similar to the switch case statement
where the default is executed instead of else block if none of the cases is matched.
12
if(condition1){
//code to be executed if condition1 is true
MODULE 2

}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

13
#include <stdio.h> else if (marks > 30 && marks <= 40)
int main() {
{ printf("You scored grade C ...");
MODULE 2

int marks; }
printf("Enter your marks?"); else
scanf("%d",&marks); {
if(marks > 85 && marks <= 100) printf("Sorry you are fail ...");
{ }
printf("Congrats ! you scored grade A ..."); }
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}

14
C Switch Statement
• The switch statement in C is an alternate to if-else-if ladder statement which
MODULE 2

allows us to execute multiple operations for the different possibles values of a


single variable called switch variable.
• Here, We can define various statements in the multiple cases for the different
values of a single variable.

15
switch(expression){
case value1:
MODULE 2

//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
16
Rules for switch statement in C language
MODULE 2

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in
the case, all the cases will be executed present after the matched case. It is known as fall through the
state of C switch statement.
17
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
MODULE 2

scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
18 }
C Switch statement is fall-through
MODULE 2

In C language, the switch statement is fall through; it means if you don't use a break
statement in the switch case, all the cases after the matching case will be executed.

19
C break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
MODULE 2

break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:
1. With switch case
2. With loop
Syntax:
//loop or switch case
break;

20
21
MODULE 2
#include<stdio.h>
#include<stdlib.h>
void main ()
MODULE 2

{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);

22
}
#include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
MODULE 2

for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
printf("%d &d\n",i,j);
if(i==2 && j==2){
break;//will break loop of j only
}
}//end of for loop
return 0;
}
23
break statement with while loop
#include<stdio.h>
void main ()
MODULE 2

{
int i = 0;
while(1)
{
printf("%d ",i);
i++;
if(i == 10)
break;
}
24 printf("came out of while loop");
}
C continue statement
MODULE 2

The continue statement in C language is used to bring the program control to the beginning of the loop. The
continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly
used for a condition so that we can skip some code for a particular condition.

Syntax:
//loop statements
continue;
//some lines of the code which is to be skipped

25
#include<stdio.h>
MODULE 2

void main ()
{
int i = 0;
while(i!=10)
{
printf("%d", i);
continue;
i++;
}
}
26
#include<stdio.h>
int main(){
MODULE 2

int i=1;//initializing a local variable


//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}

27
C goto statement
• The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the
MODULE 2

program control to a predefined label.


• The goto statment can be used to repeat some part of the code for a particular condition.
• It can also be used to break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less readable and complecated.
Syntax:

label:
//some part of the code;
goto label;

28
#include <stdio.h>
int main()
MODULE 2

{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
29
}
Enter the number whose table you want to print?10
MODULE 2

10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

30
C Loops
• The looping can be defined as repeating the same process multiple times until a specific condition satisfies.
MODULE 2

• There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all
the aspects of C loops.

Why use loops in C language?


• The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the
program so that instead of writing the same code again and again, we can repeat the same code for a finite
number of times.

31
Advantage of loops in C
1) It provides code reusability.
MODULE 2

2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for

32
do-while loop in C
MODULE 2

• The do-while loop continues until a given condition satisfies. It is also called post
tested loop.
• It is used when it is necessary to execute the loop at least once (mostly menu driven
programs).

do{
//code to be executed
}while(condition);

33
#include<stdio.h>
#include<stdlib.h>
void main ()
{
MODULE 2

char c;
int choice,dummy; printf("please enter valid choice");
do{ }
printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n"); printf("do you want to enter more?");
scanf("%d",&choice); scanf("%d",&dummy);
switch(choice) scanf("%c",&c);
{ }while(c=='y');
case 1 : }
printf("Hello");
break;
case 2:
printf("Javatpoint");
break;
case 3:
exit(0);
34 break;
default:
while loop in C
• The while loop in c is to be used in the scenario where we don't know the number of iterations in
MODULE 2

advance.
• The block of statements is executed in the while loop until the condition specified in the while loop is
satisfied.
• It is also called a pre-tested loop.

while(condition){
//code to be executed
}

35
C Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the set
MODULE 2

of programming statements enclosed by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection of functions creates a program. The
function is also known as procedureor subroutinein other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
• By using functions, we can avoid rewriting same logic/code again and again in a program.
• We can call C functions any number of times in a program and from any place in a program.
• We can track a large C program easily when it is divided into multiple functions.
• Reusability is the main achievement of C functions.
• However, Function calling is always a overhead in a C program.

36
Function Aspects
MODULE 2

There are three aspects of a C function.


• Function declaration A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.
• Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions as it
is declared in the function declaration.
• Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice that
only one value can be returned from the function.
37
SN C function aspects Syntax
MODULE 2

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function body;}

return_type function_name(data_type parameter...){


//code to be executed

38
}
Types of Functions
There are two types of functions in C programming:
1.Library Functions: are the functions which are declared in the C header files such as scanf(),
MODULE 2

printf(), gets(), puts(), ceil(), floor() etc.


2.User-defined functions: are the functions which are created by the C programmer, so that he/she
can use it many times. It reduces the complexity of a big program and optimizes the code

39
for loop in C
• The for loop is used in the case where we need to execute some part of the code until the given condition
MODULE 2

is satisfied.
• The for loop is also called as a per-tested loop.
• It is better to use for loop if the number of iteration is known in advance.

for(initialization;condition;incr/decr){
//code to be executed
}

40
Return Value
MODULE 2

A C function may or may not return a value from the function. If you don't have to return
any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:

void hello(){
printf("hello c");
}

41
Different aspects of function calling
MODULE 2

A function may or may not accept any argument. It may or may not
return any value. Based on these facts, There are four different aspects of
function calls.
• function without arguments and without return value
• function without arguments and with return value
• function with arguments and without return value
• function with arguments and with return value

42
#include<stdio.h>
void printName();
MODULE 2

void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Javatpoint");
}

43
#include<stdio.h>
void sum();
void main()
MODULE 2

{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);

44
printf("The sum is %d",a+b);
}
#include<stdio.h>
int sum();
void main()
MODULE 2

{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
45
return a+b;
}
#include<stdio.h>
int sum();
void main()
MODULE 2

{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
46
}
#include<stdio.h>
void sum(int, int);
void main()
MODULE 2

{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
47
printf("\nThe sum is %d",a+b);
}
#include<stdio.h>
int sum(int, int);
void main()
MODULE 2

{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
48
}
#include<stdio.h>
int even_odd(int);
void main()
{ int even_odd(int n)
{
MODULE 2

int n,flag=0;
printf("\nGoing to check whether a number is even or odd"); if(n%2 == 0)
printf("\nEnter the number: "); {
scanf("%d",&n); return 1;
flag = even_odd(n); }
if(flag == 0) else
{ {
printf("\nThe number is odd"); return 0;
} }
else }
{
printf("\nThe number is even");
}
}

49
C Library Functions
MODULE 2

• Library functions are the inbuilt function in C that are grouped and placed at a common place called the library.
Such functions are used to perform some specific operations.
• For example, printf is a library function used to print on the console.
• The library functions are created by the designers of compilers.
• All C standard library functions are defined inside the different header files saved with the extension .h. We
need to include these header files in our program to make use of the library functions defined in such header
files
• . For example, To use the library functions such as printf/scanf we need to include stdio.h in our program which
is a header file that contains all the library functions regarding standard input/output.

50
SN Header file Description
1 stdio.h This is a standard input/output header file. It contains all the library functions
regarding standard input/output.
2 conio.h This is a console input/output header file.
MODULE 2

3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(), calloc(),
exit(), etc.
5 math.h This header file contains all the math operations related functions like sqrt(),
pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
51 13 assert.h This file contains diagnostics functions.
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
MODULE 2

int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}

long int multiplyNumbers(int n) {


if (n>=1)
return n*multiplyNumbers(n-1);
else
52
return 1;
}
C Recursion
MODULE 2

• Recursion is the technique of making a function call itself.


• This technique provides a way to break complicated problems down into
simple problems which are easier to solve.

53
Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);
MODULE 2

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
54 else
return n;
}
55
MODULE 2
Fibonacci series is a sequence of Integers that starts with 0 followed by 1, in this sequence the
first two terms i.e. 0 and 1 are fixed, and we get the successive terms by summing up their
previous last two terms. i.e, the series follows a pattern that each number is equal to the sum of
MODULE 2

its preceding two numbers


Mathematically it can be written as :F(n )=F(n−1)+F(n−2)
where F is the Fibonacci function having base values F0)=0 and F(1)=1

Sample Series:
0
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ... 1
0+1=1
1+1=2
2+1=3
3+2=5
5+3=8
56
...
#include <stdio.h> int main()
int fibonacci(int num) {
{ int num;
MODULE 2

if (num == 0) printf("Enter the number of elements


{ to be in the series : ");
return 0; scanf("%d", &num);
} int i;
else if (num == 1) for (i = 0; i < num; i++)
{ {
return 1; printf("%d, ", fibonacci(i));
} }
else return 0;
{ }
return fibonacci(num - 1) +
fibonacci(num - 2);
}
}
57
58
MODULE 2
A Quick Explanation:
MODULE 2

• fib(5) is breaking down into fib(4) and fib(3)


• left fib(4) is breaking into fib(3) and fib(2) and right fib(3) is breaking into fib(2) and fib(1)
• This process keeps going till we reach the base condition of fib(1) i.e., value 1 or fib(0) i.e.,
value 0 in both the directions and thereafter finally each call returns to its parent who has
called them by getting added and finally we get the value of fib(5)

59
Advantages and Disadvantages of Recursion
MODULE 2

• Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is
usually much slower.
• That being said, recursion is an important concept. It is frequently used in data structure and
algorithms. For example, it is common to use recursion in problems such as tree traversal.

60
C Array

MODULE 2
• An array is defined as the collection of similar type of data items stored at contiguous
memory locations.
• Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc.
• It also has the capability to store the collection of derived data types, such as
pointers, structure, etc.
• The array is the simplest data structure where each data element can be randomly
61
accessed by using its index number.
• By using the array, we can access the elements easily.
62
MODULE 2
63
MODULE 2
Properties of Array
MODULE 2

• Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
• Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the address
of each element of the array with the given base address and the size of the data
element.
64
Declaration of C Array
We can declare an array in the c language in the following way.
MODULE 2

data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.
65
Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can initialize each
MODULE 2

element of the array by using the index.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

66
C Array: Declaration with Initialization
MODULE 2

We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as the
following code.

int marks[]={20,30,40,50,60};

67
#include<stdio.h>
MODULE 2

int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}

68
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
MODULE 2

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


{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
69 }
}
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
MODULE 2

#include<stdio.h>
void main () {
{ if(arr[i]>largest)
int arr[100],i,n,largest,sec_largest; {
printf("Enter the size of the array?"); sec_largest = largest;
scanf("%d",&n); largest = arr[i];
printf("Enter the elements of the array?"); }
for(i = 0; i<n; i++) else if (arr[i]>sec_largest && arr[i]!=largest)
{ {
scanf("%d",&arr[i]); sec_largest=arr[i];
} }
}
printf("largest = %d, second largest = %d",largest,sec_largest
);

}
70
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a
list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something
as follows −
MODULE 2

type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can
be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a,
which contains three rows and four columns can be shown as follows −

71 Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the
array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.
Two Dimensional Array in C
MODULE 2

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can
be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational
database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any
number of functions wherever required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.


data_type array_name[rows][columns];
Consider the following example.

72
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
MODULE 2

• In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously.
• However, this will not work with 2D arrays. We will have to define at least the second
dimension of the array.
• The two-dimensional array can be declared and defined in the following way.

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

73
#include<stdio.h>
int main(){
MODULE 2

int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
74 }
Output

arr[0][0] = 1
MODULE 2

arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
75
arr[3][2] = 6
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
MODULE 2

{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
76
}
}
Output

Enter a[0][0]: 56
MODULE 2

Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78
77
Pass arrays to a function in C
MODULE 2

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]); float calculateSum(float num[]) {
float sum = 0.0;
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18}; for (int i = 0; i < 6; ++i) {
sum += num[i];
// num array is passed to calculateSum() }
result = calculateSum(num);
printf("Result = %.2f", result); return sum;
return 0; }
}

78
Example 3: Pass two-dimensional arrays // pass multi-dimensional array to a function
MODULE 2

#include <stdio.h> displayNumbers(num);


void displayNumbers(int num[2][2]);
return 0;
int main() { }
int num[2][2];
printf("Enter 4 numbers:\n"); void displayNumbers(int num[2][2]) {
for (int i = 0; i < 2; ++i) { printf("Displaying:\n");
for (int j = 0; j < 2; ++j) { for (int i = 0; i < 2; ++i) {
scanf("%d", &num[i][j]); for (int j = 0; j < 2; ++j) {
} printf("%d\n", num[i][j]);
} }
}
}

79
C Strings

• The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
MODULE 2

• The character array or the string is used to manipulate text such as word or sentences.
• Each character in the array occupies one byte of memory, and the last character must always be 0.
• The termination character ('\0') is important in a string since it is the only way to identify where the
string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the
null in the memory.
• There are two ways to declare a string in c language.
1. By char array
2. By string literal

80
1. By char array
MODULE 2

char ch[8]={‘s', ‘t', ‘u', ‘d', ‘e', ‘n', ‘t', ‘s', '\0'};

2. string literal
char ch[]=“students";

In such case, '\0' will be appended at the end of the string by the compiler.

81
#include<stdio.h>
#include <string.h>
MODULE 2

int main(){
char ch[11]={'L', 'e', 'e', 's', 'h', 'm', 'a', '\0'};
char ch2[11]="Leeshma";

printf("Char Array Value is: %s\n", ch);


printf("String Literal Value is: %s\n", ch2);
return 0;
}

82
Access Strings
MODULE 2

Since strings are actually arrays in C, you can access a string by referring to its index
number inside square brackets [].

This example prints the first character (0) in greetings:

Example
char greetings[] = "Hello World!";
printf("%c", greetings[0]);

83
Modify Strings
MODULE 2

To change the value of a specific character in a string, refer to the index number, and
use single quotes:

Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);

// Outputs Jello World! instead of Hello World!


84
Loop Through a String
MODULE 2

You can also loop through the characters of a string, using a for loop:

Example
char carName[] = "Volvo";
int i;
for (i = 0; i < 5; ++i) {
printf("%c\n", carName[i]);
}

85
Strings - Special Characters
Escape character Result Description
MODULE 2

\' ' Single quote


\" " Double quote
\\ \ Backslash

#include <stdio.h>
int main()
{
char txt[] = "We are the so-called \"Vikings\" from the north.";
printf("%s", txt);
86 return 0;
}
#include <stdio.h>
MODULE 2

int main()
{
char txt[] = "The character \\ is called backslash.";
printf("%s", txt);
return 0;
}

87
Escape Character Result
\n New Line
\t Tab
MODULE 2

\0 Null

#include <stdio.h>
int main()
{
char txt[] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("%s", txt);
return 0;
}
88
Accepting string as the input
Till now, we have used scanf to accept the input from the user. However, it can also be used in the case of
MODULE 2

strings but with a different scenario. Consider the below code which stores the string while space is
encountered.

#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}
89
To make this code working for the space separated strings, the minor changed required in the scanf function, i.e.,
instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the compiler to store the
string s while the new line (\n) is encountered.
MODULE 2

#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%[^\n]s",s);
printf("You entered %s",s);
}

gets() which is an inbuilt function defined in a header file string.h. The gets() is capable of receiving only one
90 string at a time.
String Functions
MODULE 2

C also has many useful string functions, which can be used to perform certain operations on strings.

To use them, you must include the <string.h> header file in your program:

#include <string.h>

91
String Length
MODULE 2

• The strlen() function in C calculates the length of a given string. The strlen()
function is defined in string.h header file. It doesn’t count the null character ‘\0’.

Syntax of C strlen()
The syntax of strlen() function in C is as follows:

size_t strlen(const char* str);

92
Parameters
The strlen() function only takes a single parameter.

str: It represents the string variable whose length we have to find.


Return Value
MODULE 2

This function returns the integral length of the string passed.

#include <stdio.h>
#include <string.h>

int main() {
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
return 0;
93
}
Important Points about strlen()
MODULE 2

The following points should be kept in mind while using strlen():

• strlen() does not count the NULL character ‘\0’.


• The time complexity of strlen() is O(n), where n is the number of characters in the string.
• Its return type is size_t ( which is generally unsigned int ).

94
In the Strings chapter, we used sizeof to get the size of a string/array. Note that sizeof and
strlen behaves differently, as sizeof also includes the \0 character when counting:
MODULE 2

#include <stdio.h>
#include <string.h>
int main()
{
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("Length is: %d\n", strlen(alphabet)); //output=26
printf("Size is: %d\n", sizeof(alphabet)); //output = 27
return 0;
}
95
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:
MODULE 2

#include <stdio.h>
#include <string.h>

int main()
{
char str1[20] = "Hello ";
char str2[] = "World!";

// Concatenate str2 to str1 (the result is stored in str1)


strcat(str1, str2);
printf("%s", str1);

return 0;
96
}
Copy Strings
strcpy() is a standard library function in C++ and is used to copy one string to another. In C++ it is present
in the <string.h> and <cstring> header files.
MODULE 2

Syntax:

char* strcpy(char* dest, const char* src);

Parameters: This method accepts the following parameters:

dest: Pointer to the destination array where the content is to be copied.


src: string which will be copied.

97 Return Value: After copying the source string to the destination string, the strcpy() function returns a pointer to the
destination string.
To copy the value of one string to another, you can use the strcpy() function:
MODULE 2

#include <stdio.h>
#include <string.h>

int main()
{
char str1[20] = "Hello World!";
char str2[20];

strcpy(str2, str1); // Copy str1 to str2

printf("%s", str2);

return 0;
98
}
Compare Strings
• To compare two strings, you can use the strcmp() function.
• It returns 0 if the two strings are equal, otherwise a value that is not 0
MODULE 2

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";

printf("%d\n", strcmp(str1, str2)); // Compare str1 and str2, and print the result

// Compare str1 and str3, and print the result


printf("%d\n", strcmp(str1, str3));

return 0;
99 }
THANK YOU

You might also like