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

Lecture 1 Looping Statements

This document discusses nested loops in C programming. It begins by stating the course objectives of providing exposure to problem-solving through programming and raising programming skills via logic building. It then discusses nested loops, which involve having one or more loops inside another loop. Nested loops allow programmers to iterate over multiple variables and create complex patterns that would be difficult or impossible with simple loops alone. Examples are provided to illustrate how nested loops can be used.

Uploaded by

Raghav
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)
59 views

Lecture 1 Looping Statements

This document discusses nested loops in C programming. It begins by stating the course objectives of providing exposure to problem-solving through programming and raising programming skills via logic building. It then discusses nested loops, which involve having one or more loops inside another loop. Nested loops allow programmers to iterate over multiple variables and create complex patterns that would be difficult or impossible with simple loops alone. Examples are provided to illustrate how nested loops can be used.

Uploaded by

Raghav
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/ 84

1

INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-3
Bachelor of Engineering (All Non IT)
Subject Name: Introduction to Problem Solving
Course Code: 22CSH-107

Loop Control structure in C DISCOVER . LEARN . EMPOWER


2

Fundamentals of
Computer
Programming

Course Objectives
The course aims to provide exposure to problem-
solving through programming.
The course aims to raise the programming skills of
students via logic building capability.
With knowledge of C programming language, students
would be able to model real world problems.
Contents

Looping
Types For loop While loop Do while
statements

3
Looping Statements
I/O Statements
The statements that help us to execute set of
statements repeatedly are called as looping
statements. It executes a block
of statements number of times until the condition
becomes false.

It executes a block of statements number of times


until the condition becomes false.

4
Types ofI/O types statements
Looping
• Entry controlled loop or Pre-Test Loop: In the
entry controlled loop or Pre-Test loop, the
condition is checked before we start and at the
beginning of each iteration of the loop. If the
condition is true, we execute body of loop; if the
control expression is false, we terminate the
loop.
• Examples: while statement and for statement

• Exit controlled loop or Post-Test Loop: In the exit


controlled loop or Post-Test loop, the condition is
checked after or at the end of each iteration of
the loop. If the condition is true, we repeat body
of loop; if the condition is false, we terminate the
loop.
5
• Examples: do…while statement
Loops Definition & Syntax
Statements Definition & Syntax
It is a most basic loop in C programming. It has one control condition, and executes
as long the condition is true. The condition of the loop is tested before the body of
the loop is executed.
Syntax:
while while (condition)
{
statement(s);
Incrementation;
}
C for loops is very similar to a while loops in that it continues to process a block of
code until a statement becomes false, and everything is defined in a single line.
The for loop is also entry
-controlled loop.
Syntax:
for for ( init; condition; increment )
{
statement(s);
}

C do while loops are very similar to the while loops, but it always executes the code
block at least once and furthermore as long as the condition remains true.
Syntax:
do
Do while {
statement(s);

}while( condition ); 6
7

While loop
Working:
step1: The loop variable is
initialized with some value and
then it has been tested for the
condition.
step2: If the condition returns true
then the statements inside the
body of while loop are executed
else control comes out of the loop.
step3: The value of loop variable
is incremented/decremented then
it has been tested again for the
loop condition.
8

Example 1
Example 1 Program to print first 10
natural numbers.
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
x++;
}
}
9

Example 2

Infinite loop
10

Do-while loop
Working:
1. First we initialize our variables,
next it will enter into the Do While
loop.
2. It will execute the group of
statements inside the loop.
3. Next we have to use Increment
and Decrement Operator inside the
loop to increment or decrements
the value.
4. Now it will check for the
condition. If the condition is True,
then the statements inside the do
while loop will be executed again. It
will continue the process as long
as the condition is True.
11

Example
Program to print fibonacci series
#include<stdio.h>
void main()
{
int n,f,f1=-1,f2=1;
printf(" Enter The Number Of Terms:");
scanf("%d",&n);
printf(" The Fibonacci Series is:");
do
{
f=f1+f2;
f1=f2;
f2=f;
printf(" \n %d",f);
n--;
}while(n>=0);
}
12

For loop Flowchart of continue statement

Working:
Step 1: First initialization happens
and the counter variable gets
initialized.
Step 2: In the second step the
condition is checked, where the
counter variable is tested for the
given condition, if the condition
returns true then the C statements
inside the body of for loop gets
executed, if the condition returns
false then the for loop gets
terminated and the control comes
out of the loop.
Step 3: After successful execution of
statements inside the body of loop,
the counter variable is incremented
or decremented, depending on the
operation (++ or –)
13

Example
Program to print factorial of a number
#include<stdio.h>
#include<conio.h>
void main()
{
int fact, i, n;
fact = 1;
printf("Enter the number\t");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
fact = fact*i;
}
printf("Factorial of %d is %d", n , fact);
getch();
}
14

Summary
It continues to process a block of code until a statement
for becomes false, and everything is defined in a single line.

It has one control condition, and executes as long the condition is true.
while

It always executes the code block at least once and furthermore as


Do while long as the condition remains true.
15
FAQ
1. What is the difference between while loop and do-while loop?
16

FAQ
• Q2 Write a program to print table of a number enter by user.
• #include <stdio.h>
• void main()
• {
• int j,n;
• printf("Input the number (Table to be calculated) : ");
• scanf("%d",&n);
• printf("\n");
• for(j=1;j<=10;j++)
• {
• printf("%d X %d = %d \n",n,j,n*j);
• }
• }
17

Assessment Questions
1. Program to check Armstrong number.
2. Write a c program to check a number is prime number or not.
3. Write programs for the following :
a) program to read 10 numbers from keyboard and find their sum and average.
b) to calculate the simple interest.
4. do-while loop terminates when conditional expression returns?
A One
B ZERO
C NON-ZERO
D NONE OF THE ABOVE
5. What will be the output of following program ?
#include <stdio.h>
void main()
{
int cnt=1;
do
{ printf("%d,",cnt);
cnt+=1;
}while(cnt>=10);
printf("\nAfter loop cnt=%d",cnt);
printf("\n")
18

Discussion
Forum

Program takes an integer from the user and calculates


the number of digits.
For example: If the user enters 231967, the output of
the program will be 6.
References
Book References:
http://www2.cs.uregina.ca/~hilder/cs833/Other%20Reference%20Materials/The%20C%20Progr
amming%20Language.pdf
http://www.freebookcentre.net/programming-books-download/The-Basics-of-C-
Programming.html

Vedio Lecture: https://www.studytonight.com/c/loops-in-c.php


https://www.youtube.com/watch?v=4gFfGzpDGFw
https://spocathon.page/video/lecture-20-implementation-loops-statement-contd
https://study.com/academy/lesson/nesting-loops-statements-in-c-programming.html

Websites: https://www.programiz.com/c-programming/c-for-loop
https://www.tutorialspoint.com/cprogramming/c_loops.htm
https://beginnersbook.com/2014/01/c-loops-examples/
20

THANK YOU
21

INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-3
Bachelor of Engineering (All Non IT)
Subject Name: Introduction to Problem Solving
Course Code: 22CSH-107

Nested Loops DISCOVER . LEARN . EMPOWER


22

Fundamentals of
Computer
Programming
Course Objectives
The course aims to provide exposure to problem-
solving through programming.
The course aims to raise the programming skills of
students via logic building capability.
With knowledge of C programming language, students
would be able to model real world problems.
Contents

Nested
Looping Syntax Working Examples

23
Nested Looping
I/O Statements

A loop within another loop is called nested loop. C programming


language supports nesting of one loop inside another. We can
define any number of loops inside another loop. And also have
any number of nesting level..

Put any type of loop in another type. Write for loop


inside while loop, while inside another while etc. A
programmer nest up to 3 loops. But there is no limit of nesting
in C.

24
Loops Definition & Syntax

Syntax

outer_loop
{
inner_loop
{
// Inner loop statement/s
}
// Outer loop statement/s
}

25
26

How Nested loop work:


There are two conditions that are given.
1. The inner loop condition gets executed only when the outer loop condition gives the Boolean output as
True. Else the flow control directly goes out of both the loops.
2. Now coming into the execution of the inner loop, If the loop condition gives a true result, then the block
of statements under that loop and the incremental condition gets executed.
3. And in turn, if the condition gives a Boolean condition as False, then the inner loop gives its control
back to the outer loop and again same conditions/loops gets executed/repeated.
27
Explanation:
Example1 of Nested •First, we initialize the outer loop counter variable, i.e., 'i' by
do-while loop 1.
#include <stdio.h> •As we know that the do..while loop executes once without
int main() checking the condition, so the inner loop is executed without
{ checking the condition in the outer loop.
int i=1; •After the execution of the inner loop, the control moves to
do // outer loop the update of the i++.
{ •When the loop counter value is incremented, the condition
int j=1; is checked. If the condition in the outer loop is true, then the
do // inner loop inner loop is executed.
{ This process will continue until the condition in the outer loop
printf("*"); is true
j++; Output:
}while(j<=8);
printf("\n");
i++;
}while(i<=4);
}
28

Example2 using Nested for loop


Output
29

Summary
A loop within another loop is called nested loop. C programming
language supports nesting of one loop inside another.

We can define any number of loops inside another loop. And also have
any number of nesting level.
Nested Looping
Write for loop inside while loop, while inside another while etc. A
programmer nest up to 3 loops. But there is no limit of nesting in C.

It always executes the code block at least once and


furthermore as long as the condition remains true.
30

FAQ
Q1 Print the pattern
#include<stdio.h>
int main()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=j;i++)
printf("%5d",i);
printf("\n\n");
}
for(j=4;j>=1;j--)
{
for(i=1;i<=j;i++)
printf("%5d",i);
printf("\n\n");
}
return 0;
}
31

FAQ
• Q2 Print the reverse pattern

• #include<stdio.h>
• int main()
• {
• int i,j;
• for(j=5;j>=1;j--)
• {
• for(i=j;i>=1;i--)
• printf("%5d",i);
• printf("\n\n");
• }
• return 0;
}
nt• Questions
32

Print the above two numbering patterns


References
Book References:
http://www2.cs.uregina.ca/~hilder/cs833/Other%20Reference%20Materials/The%20C
%20Programming%20Language.pdf
http://www.freebookcentre.net/programming-books-download/The-Basics-of-C-
Programming.html

Vedio Lecture: https://study.com/academy/lesson/nesting-loops-statements-in-c-


programming.html
https://www.youtube.com/watch?v=mZqo8KDR37U
https://nptel.ac.in/courses/106/104/106104128/

Websites: https://www.studytonight.com/c/programs/loop/nested-loops
https://beginnersbook.com/2014/01/c-for-loop/
https://www.tutorialspoint.com/cprogramming/c_nested_loops.htm
34

THANK YOU
35

INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-3
Bachelor of Engineering (All Non IT)
Subject Name: Introduction to Problem Solving
Course Code: 22CSH-107

Jump Statements DISCOVER . LEARN . EMPOWER


36

Fundamentals of
Computer
Programming
Course Objectives
The course aims to provide exposure to problem-
solving through programming.
The course aims to raise the programming skills of
students via logic building capability.
With knowledge of C programming language, students
would be able to model real world problems.
Contents

Jump
break continue goto return
statements

37
Jump Statements
I/O Statements
Jump statements can be used to modify the
behavior of conditional and iterative
statements

They allow you to exit a loop, start the next


iteration of a loop, or explicitly transfer
program control to a specified location in
your program.

38
Types I/O types statements
of Jump
They are of four types:-
• Break
• Continue
• goto
• Return

39
Loops Definition & Syntax
Statements Definition & Syntax
A break statement is used to terminate the execution of the rest of the
block where it is present and takes the control out of the block to the
Break next statement.
Syntax: break;

Continue statement like any other jump statements interrupts or


Continue changes the flow of control during the execution of a program.
Syntax: continue;

This jump statement is used to transfer the flow of control to labeled


statement in the program.
goto Syntax: goto <label>;
This label indicates the location in the program where the control jumps
to.
to.

This jump statement is usually used at the end of a function to end or


Return terminate it with or without a value.
Syntax: return<expression>;

40
41

Break statement • F

The break statement is used to


terminate the loop or statement in
which it present. After that, the
control will pass to the statements
that present after the break
statement, if available. If the break
statement present in the nested
loop, then it terminates only those
loops which contains break
statement.

Flowchart of break statement


42

Example
Example 1: Program to print first 15
natural numbers
#include <stdio.h>
int main()
{
int i;
for(i=1;i<=15;i++)
{
printf("%d\n",i);
if(i==10)
break;
}
return 0;
}
43

Continue statement

This statement is used to skip over


the execution part of the loop on a
certain condition. After that, it
transfers the control to the
beginning of the loop. Basically, it
skips its following statements and
continues with the next iteration of
the loop.

Flowchart of continue statement


44

In this program, we see that the printf() instruction for the


condition j=2 is skipped each time during the execution
Example because of continue. We also see that only the
Write a c program to print numbers condition j=2 gets affected by the continue. The outer loop
#include <stdio.h> runs without any disruption in its iteration.
int main()
{
int i,j;
for(i=1;i<3;i++)
{
for(j=1;j<5;j++)
{
if(j==2)
continue;
printf("%d\n",j);
}
}
return 0;
}
45

goto statement Flowchart of continue statement


This statement is used to transfer control
to the labeled statement in the program.
The label is the valid identifier and placed
just before the statement from where the
control is transferred.
Example: #include <stdio.h>
int main()
{
int i,j;
for(i=1;i<5;i++)
{
if(i==2)
goto there;
printf("%d\n",i);
}
there:
printf("Two");
return 0;
In this program, we see that when the control goes to
} the goto there; statement when i becomes equal to 2 then the
control next goes out of the loop to the label(there: ) and
prints Two.
46

Return statement
This statement terminates the execution of the method
and returns the control to the calling method. It returns
an optional value. If the type of method is void, then the
return statement can be excluded.
Example: #include <stdio.h>
char func(int ascii)
{
return ((char)ascii);
}
int main()
In this program we have two functions that have
{
a return type but only one function is returning a value
int ascii; [func()] and the other is just used to terminate the
char ch; function[main()].
printf("Enter any ascii value in decimal: \n"); The function func() is returning the character value of
scanf("%d",&ascii); the given number(here 110). We also see that return
ch=func(ascii); type of func() is char because it is returning a character
value.
printf("The character is : %c",ch);
return 0; The return in main() function returns zero because it is
necessary to have a return value here because main has
}
been given the return type int.
47

Summary
It terminate the loop or statement in which it
break
present.

It is used to skip over the execution part of the loop on a


continue
certain condition.
It transfer control to the labeled statement in the program.
Goto

return It terminates the execution of the method and returns the


control to the calling method.
48
FAQ
Q1 Write a program in C to display the sum of the numbers enter by a user and stop taking input when user enter zero.
#include<stdio.h>
void main()
{
int num, sum=0, i,n;
printf("Enter Number of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i)
{
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0)
{
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n");
}
sum=sum+num;
}
printf("Total is %d",sum);
getch();}
49

FAQ
• Q2 Write a program to check if a number is even or not and print using the goto statement.
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d",&num);
if (num % 2==0)
goto even;
else
goto odd;
even:
printf("even Number");
Odd:
printf("odd Number");
return 0;
}
50

Assessment Questions
1. #include<stdio.h> 2. #include<stdio.h>
int main() int main()
{
int x;
{
int x=1;
for(x=1;x<=10;x++)
for(;;)
{
{
if(x%2==1)
if(x>5)
continue;
break;
printf("\t%d",x);
printf("\t%d",x++);
}
}
return 0;
return 0;
}
}
3. The break statement is used in? 4. #include <stdio.h>"
a) for loop int main()
b)switch statement {
c) while loop int i;
d)None of the above goto LOOP;
for (i = 0 ; i < 10 ; i++)
{
printf("GeeksQuizn");
LOOP:
break;
}
return 0;
References
Book References:
https://www.pdfdrive.com/learn-to-program-with-c-learn-to-program-using-the-popular-c-
programming-language-
e166650744.htmlhttp://www2.cs.uregina.ca/~hilder/cs833/Other%20Reference%20Materials/Th
e%20C%20Programming%20Language.pdf
http://www.freebookcentre.net/programming-books-download/The-Basics-of-C-
Programming.html

Vedio Lecture: http://www.digimat.in/nptel/courses/video/106104128/L17.html


https://spoken-tutorial.org/watch/C+and+Cpp/Loops/English/
https://www.youtube.com/watch?v=67TlTBT68LE
https://www.youtube.com/watch?v=Bv1LcqhqnZs

Websites: https://www.cs.auckland.ac.nz/references/unix/digital/AQTLTBTE/DOCU_075.HTM
https://www.programiz.com/c-programming/c-goto-statement
https://www.geeksforgeeks.org/c-sharp-jump-statements-break-continue-goto-return-and-throw/
52

THANK YOU
INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-3
Bachelor of Engineering (All Non IT)
Subject Name: Introduction to Problem Solving
Course Code: 22CSH-107

Array & Strings DISCOVER . LEARN . EMPOWER


53
OBJECTIVES
The course aims to provide exposure to problem solving with

OBJECTIVES
programming

The course aims to raise the programming skills of students via logic
building capability

With the knowledge of C language students would be able to model


real world problems

54
Array
Types of Array
Content Declaration of one Dimensional
Array
Initialization of one
Dimensional Array
Examples
References
55
In C programming, one of the frequently arising problem is to
handle similar types of data.
For example: If the user want to store marks of 100 students.
This can be done by creating 100 variable individually but, this
process is rather tedious and impracticable. These type of
problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous value(same
type).

Array All the data items of an array are stored in consecutive memory
locations in RAM.
The elements of an array are of same data type and each item can
be accessed using the same name.

56
Array is of three types:

Types
of
Array

57
Declaration of one-dimensional array: We know
that all the variables are declared before they are used
in the program. Similarly, an array must be declared
before it is used.
During declaration, the size of the array has to be
specified. The size used during declaration of the
array informs the compiler to allocate and reserve the
Declaration of 1-D specified memory locations.

Array data_type array_name[array_size];


For example:

int age[5];
Here, the name of array is age. The size of array is
5,i.e., there are 5 items(elements) of array age. All
element in an array are of the same type (int, in this
case).

58
Each element of array can be accessed and used by user
according to the need of program.

For example:
int age[5];

Array Elements
Note that, the first element is numbered 0 and so on.

Here, the size of array age is 5 times the size of int because there ar
5 elements.

Suppose, the starting address of age[0] is 2120d and the size of int
bytes.
Then, the next address (address of a[1]) will be 2124d, address
of a[2] will be
2128d and so on.
59
Initialization of one-dimensional array:
Arrays can be initialized at declaration time in this source
code as:

int age[5]={2,4,34,3,4};

Initialization It is not necessary to define the size of arrays during


initialization.
1-D Array int age[]={2,4,34,3,4};

In this case, the compiler determines the size of array by


calculating the number of elements of an array

60
1. Program to take 5 values from the user and store them in an array.
#include<stdio.h>
int main()
{

Examples of 1- int values[5];

D Array
printf("Enter 5 integers: ");
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
for(int i = 0; i < 5; ++i)
{
printf("%d\n", values[i]);
Here, we have used a for loop to take 5
} inputs from the user and store them in an
return 0; array. Then, using another for loop, these
elements are displayed on the screen
} 61
2. Program to find the average of n numbers using
arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
Examples of printf("Enter number of elements: ");
scanf("%d", &n); for(i=0; i<n; ++i)
1-D Array {
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
Here, we have computed the
average of n numbers entered by
return 0; the user.
} 62
1.
Array is defined as an
ordered set of similar
data items

SUMMARY 2. 3.
During declaration of an Arrays can be initialized
array the size of the array at declaration time in this
has to be specified. source code
PROGRAMS

1. Write a C Program to Addition of All Elements of the Array


2. Write a C Program to insert an element in an array.
3. Write a C Find Smallest Element in Array .
4. Write a C program to reversing an element in an array.
FREQUENTLY 5. C program to find the sum and calculate percentage of marks of
n students using arrays
ASKED
QUESTIONS

64
1.What is the right way to initialize an array?
A.int num[6] = { 2, 4, 12, 5, 45, 5 };
B.int n{} = { 2, 4, 12, 5, 45, 5 };
C.int n{6} = { 2, 4, 12 };

UTILISE YOUR D.int n(6) = { 2, 4, 12, 5, 45, 5 };

KNOWLEDGE
TO ANSWER 2. An array element is always stored in …………………..memory
location?
Let us see how much you A. Sequential
have learned from the
lecture and how effectively B. Random
you can apply your
knowledge…!! C. Sequential and Random
D. None of the above

65
3. Let x be an array. Which of the following operation are illegal?
I ++X
II X+1
III X++
IV X*2

UTILISE YOUR A.I and II

KNOWLEDGE B.I, II and III

TO ANSWER C.II and III


D.I, III and IV
Let us see how much you
have learned from the E.III and IV
lecture and how effectively 4 Size of an array need not be specified, when
you can apply your
knowledge…!! A. Initialization is a part of definition
B. It is a declaratrion
C. It is a formal parameter
D. All of these 66
DISCUSSION
FORUM

Q1 C Program to Delete duplicate elements from an


array

67
Book References:
[1] Kanetkar, Y. (2010). Let us C. 15th ed.
[2] Thareja Reema (2014) Programming in C. 2nd ed.
[3] Zed A. Shaw, Learn C the Hard Way’
[4] https://en.wikibooks.org/wiki/C_Programming

REFERENCES
Vedio Lecture: https://nptel.ac.in/courses/106/106/106106127/
BOOKS https://nptel.ac.in/courses/106/105/106105171/

WEBSITES https://study.com/academy/lesson/declaring-one-dimensional-
arrays-definition-example.html
COURSES https://www.youtube.com/watch?v=XZGZm-0wUC0

Websites:
https://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
https://beginnersbook.com/2014/01/c-arrays-example/
https://www.codesdope.com/c-array/

68
THANK YOU

Still have a doubt ?

Mail your queries at :


[email protected]

69
INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-3
Bachelor of Engineering (All Non IT)
Subject Name: Introduction to Problem Solving
Course Code: 22CSH-107

Array & Strings DISCOVER . LEARN . EMPOWER


OBJECTIVES
The course aims to provide exposure to problem solving with

OBJECTIVES
programming

The course aims to raise the programming skills of students via logic
building capability

With the knowledge of C language students would be able to model


real world problems

71
Two Dimensional Array
Initialization of Two
Content Dimensional Array
Memory Representation of 2D
Array
Examples
References
A two-dimensional array is an array where its elements are
selected (identified) using two indices. In 2-D array, to declare
and access elements of a 2-D array we use 2 subscripts instead
of 1.
Syntax: data_type array_name[ROW][COL];
The total number of elements in a 2-D array is ROW*COL.
Example: int a[m][n];
In rectangular 2-dimensional arrays, m number of rows and n
number of columns in the array has the same number of array
2-Dimensional elements.
Array

A conceptual representation of 2D array


Initialization of two-dimensional array: Initialization
of 2-D array is similar to a 1-D array.
Example:

Initialization
2-D Array
After this initialization, each element is as follows:
temp[0][0] : 1
temp[0][1] : 2
temp[0][2] : 3
temp[1][0] : 11
temp[1][1] : 22
temp[1][2] : 33
The compiler will allocate the memory for two dimensional
array row-wise meaning the first element of the second row will
be placed after the last element of the first row.

Memory
Representation
2-D Array
And if we assume that the first element of the array is at address
1000 and the size of type int is 2 bytes then the elements of the array
will get the following allocated memory locations.

Memory
Representatio
n 2-D Array
1. Program to store the elements
from the user and store them in an
2D array. for(i=0; i<2; i++)
#include<stdio.h> {
int main() for(j=0;j<3;j++)
{
{
Examples of 2- int disp[2][3], i, j;
printf("%d ",
disp[i][j]);
D Array for(i=0; i<2; i++) if(j==2){
printf("\n");
{
}
for(j=0;j<3;j++) }
{ }
printf("Enter value for disp[%d][%d]:", i, j); return 0;
}
scanf("%d", &disp[i][j]);
}
}
printf("Two Dimensional array
elements:\n");
2.. Program to sum of even and
odd of 2D array.
even=even+arr[i][j];
#include<stdio.h> }
int main() else
{
{ odd=odd+arr[i][j];
}
int i=0,j=0;
Examples of int
}
}
printf("Sum of even =%d \n",even);
arr[3][4]={{1,2,3,4},{2,3,4,5},{3,4,5,
2-D Array 6}}; printf("Sum of odd =%d",odd);
return 0; }
int even=0;int odd=0;
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
if(arr[i][j]%2==0)
{
1.
In 2-D array, to declare
and access elements of a
2-D array we use 2
subscripts instead of 1.

SUMMARY 2. 3.
In rectangular 2-
The compiler will allocate the
dimensional arrays, m
memory for two dimensional
number of rows and n
array row-wise meaning the
number of columns in
first element of the second
the array has
row will be placed after the
the same number of array
last element of the first row.
elements.
PROGRAMS

1. Write a C Program to addition of two matrices.


2. Write a program in C to calculate determinant of a 3 x 3
matrix.
3. Write a program in C to accept two matrices and check
FREQUENTLY whether they are equal.

ASKED 4.
5.
Write a C program to transpose of two matrices.
Program to multiply two matrices.
QUESTIONS
1.Which of the following is true about arrays in C.
(A) For every type T, there can be an array of T.
(B) For every type T except void and function type, there can be an array of T.
(C) When an array is passed to a function, C compiler creates a copy of array.
(D) 2D arrays are stored in column major form
2. What will be the output of the following C code?
#include <stdio.h>
void f(int a[][3])
{

UTILISE YOUR a[0][1] = 3;

KNOWLEDGE int i = 0, j = 0;
for (i = 0; i < 2; i++)
TO ANSWER for (j = 0; j < 3; j++)
printf("%d", a[i][j]);
Let us see how much you
}
have learned from the
lecture and how effectively void main()

you can apply your {


knowledge…!! int a[2][3] = {0};
f(a);
}
a) 0 3 0 0 0 0
b) Junk 3 junk junk junk junk
c) Compile time error
d) All junk values
3. What will be the output of the following C code?
#include <stdio.h>
void main()
{
int a[2][3] = {1, 2, 3, 4, 5};
UTILISE YOUR int i = 0, j = 0;
KNOWLEDGE for (i = 0; i < 2; i++)
TO ANSWER for (j = 0; j < 3; j++)
Let us see how much you printf("%d", a[i][j]);
have learned from the
lecture and how effectively }
you can apply your
knowledge…!!
a) 1 2 3 4 5 0
b) 1 2 3 4 5 junk
c) 1 2 3 4 5 5
d) Run time error
Book References:
[1] Thareja Reema (2014) Programming in C. 2nd ed.
[2] Zed A. Shaw, Learn C the Hard Way’
[3] https://en.wikibooks.org/wiki/C_Programming

REFERENCES Vedio Lecture: https://nptel.ac.in/courses/106/105/106105171/


https://nptel.ac.in/courses/106/106/106106127/
BOOKS
https://spoken-
tutorial.org/watch/C+and+Cpp/Working+With+2D+Arrays/English/
WEBSITES
COURSES Websites: https://beginnersbook.com/2014/01/2d-arrays-in-
c-example/
https://processing.org/tutorials/2darray/
https://www.programiz.com/c-programming/c-multi-dimensional-
arrays
THANK YOU

You might also like