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

Module-2 PPS Notes

The document provides an overview of unconditional branching statements, looping statements, and arrays in C programming. It explains various control statements such as goto, break, continue, and return, as well as different types of loops including while, do-while, and for loops. Additionally, it covers one-dimensional and two-dimensional arrays, their declaration, initialization, and basic operations like searching and sorting.

Uploaded by

suprithnj517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module-2 PPS Notes

The document provides an overview of unconditional branching statements, looping statements, and arrays in C programming. It explains various control statements such as goto, break, continue, and return, as well as different types of loops including while, do-while, and for loops. Additionally, it covers one-dimensional and two-dimensional arrays, their declaration, initialization, and basic operations like searching and sorting.

Uploaded by

suprithnj517
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Module – 2: Looping Statements & Arrays

UNCONDITIONAL BRANCHING STATEMENTS: The unconditional branching


statements transfer the control from one statement to another statement in the program without
any conditions.

a) Goto Statement: This statement is used to transfer the control from one point to another
point anywhere in the program. The goto requires a label in order to identify the place where
the branch is to be made.
• The general forms of goto statement:

• Example:

#include<stdio.h>
void main()
{
int a=1;
SHOW:
if(a>10)
{
printf("%d",a);
a+=2;

}
goto SHOW;
}
}

b) Break Statement: The break statement is used to break any type of loop as well as
switch statement. Breaking a loop means terminating the loop.
• The general forms of break statement:
break;
• Example:
switch(opr)
{
case '+':
printf("Sum : %f",(a + b));
break;

} control is transferred to the end of block

c) Continue Statement: The continue statement is used to transfer the control to the
beginning of a statement block in a loop. In other words, a break statement breaks the entire
loop, but a continue statement breaks the current iteration. The continue statement breaks the
current execution of a loop condition and then continue the loop with next condition.
• The general forms of continue statement:
continue;

• Example:

#include<stdio.h>

int main()

int i=1;

//starting a loop from 1 to 10

for(i=1;i<=10;i++){

if(i==5)

continue;

printf("%d \n",i);

} //end of for loop

return 0; }

d) Return Statement: It is used to return the control to the calling function with/without a
value. For example, if a function is not returning any value, use the return keyword

return;
If a function is returning a value, then

return value;

• Example:

int sumDigits()

int sum = 0;

int digit;

for(digit = 0; digit <= 9; digit++)

sum = sum + digit;

return sum; //Returning value & control

LOOPING STATEMENTS: The statement which is used to repeat a set of statements


repeatedly for a given number of times or until a given condition is satisfied is called as looping
statements. The set or block of statements used for looping is called loop.

• Way of Looping:
1) Entry Controlled Loop or pretest loop or top test loop
2) Exit Controlled Loop or posttest loop

• The C Language supports the following three looping operations:

1) The while statement

2) The do while statement

3) The for statement


a) While Loop/Statement (Entry Controlled/Pretest loop): The while statement is the
pretest loop. It uses an expression to control the loop. Since it is a pretest loop, it tests the
expressions before every iterations of the loop.

The syntax and flow chart of While loop is as illustrated below:

Example: Program to find the sum of n natural numbers using while loop
#include<stdio.h>

void main()

int i,n,sum=0;

printf("Enter the value of n\n");

scanf("%d",&n);

i=0;

while(i<=n)

{
sum = sum + i;

i++;

printf("The sum of natural numbers = %d",sum);

b) Do-While Loop/Statemen(Exit Controlled Loop/Post-test): It is an exit controlled


loop. It is also known as posttest or bottom test looping statement.

The syntax and flow chart of Do-While looping statement is as illustrated below:

Example: Program to find the sum of n natural numbers using do while


#include<stdio.h>

void main()

int i,n,sum=0;
printf("Enter the value of n\n");

scanf("%d",&n);

i=0;

do

sum = sum + i;

i++;

while(i<=n);

printf("The sum of natural numbers = %d",sum);

• Differences between while & do-while looping statements

c) For Loop/Statement(Entry Controlled/Pre-test loop): The for statement is a pretest


loop that uses three expressions.

Syntax:

for (initialization ; test condition ; increment/decrement)

{
body of the loop;

The first expression contains any initialization statements, the second contains the limit-test
expression, and the third contains the updating expression.

1) The initialization set the initial value of the loop control variable.

2) The test condition test the value of the loop control variable.

3) The increment/decrement update the loop control variable.

Example: Program to print N Natural Numbers


#include<stdio.h>

void main()

int i, n;

printf(“Enter the value of N \n”);

scanf(“%d”,&n);

for ( i=1 ; i<=n ; i++)

printf(“%d\t”,i);

• Nested for-loop: Nested loops consist of an outer loop with one or more inner loops.
for (i=1;i<=100;i++)
{
for(j=1;j<=50;j++)
{

}
}
The above loop will run for 100*50 iterations.
ARRAYS: “An array is a sequential collection/group of homogeneous (same type) elements
which are referred by the same name”

The type refers to the data types like int, char, float etc. All the elements/values in the array are
of the same type (data type). We cannot store values of different data types in the same array.

It is normal in programming to work with a list of values or a group of values at once. For such
purposes, variables cannot be used. So, C language provides the construct array for holding
multiple values at once.

TYPES OF ARRAYS:
1) One-dimensional Arrays: To maintain a list of values.

2) Multidimensional Arrays: To maintain a table of values.

ONE-DIMENSIONAL ARRAYS(1-D Array): For maintaining a list of items in C, we


can declare an array with a single subscript (index). Such arrays with only a single subscript are
known as “one dimensional arrays”.

• Common uses of one dimensional arrays are:

1) To maintain a list of numbers.

2) To maintain the list of marks.

3) To maintain a list of student names etc.

a) One-dimensional Array Declaration: For using arrays in C programs, just like we are
declaring variables before using them, we should declare arrays before using them.

Syntax: for declaring a 1-D Array is shown below:


type arrayName [Size];

Example:
int a[10];
In the above example ’a’ is an integer array, which can hold 10 integer values.

b) One-dimensional Array Initialization: Initialization means assigning values. To assign


values to the elements in the array.
Generally, there are two types of initializing an array:
1) Static Initialization (at compile time).
2) Dynamic Initialization (at run time).

In static initialization, the elements of an array are assigned values when the program is
compiled.

Syntax for static Initialization:

type arrayName[size] = {value1, value2,…valueN};

Examples:

int a[10] = {1,2,3,4,5,6,7,8,9,10};


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

In dynamic initialization, the values are assigned to the elements of the array during the
execution of the program.

Example: int a[10], i;


for(i = 0; i < 10; i++)
{
scanf(“%d”,&a[i]);
}
In the above example, the user will be storing the values into the array while executing the
program. Until then, garbage values will be stored in the array. If we use braces i.e., { and }, for
initializing the array, the default values for all the elements in the array will be zero.
c) Example Program on One-dimensional Array: C Program to find Sum of n Number using
1-D Array.
#include<stdio.h>
void main()
{
int i, n, sum=0, a[100];
printf("Enter Number of array elements: n");
scanf("%d",&n);
printf("Enter the elements one by one\n");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<n; i++)
{
sum = sum + a[i];
}
printf("Sum of the Numbers = %d", sum);
}
SEARCHING: The process of finding a particular item in the large amount of data is called
“searching”. The element to be searched is called “key element”.

There are two methods of searching:

1] Linear search. 2] Binary search.

Linear search also called sequential search is a simple searching technique. In this technique we
search for a given key item in linear order i.e. one after the other from first element to last
element. If key item is present, the search is successful, otherwise unsuccessful search.

1] LINEAR SEARCH:

• Algorithm:
Linear_search (list, value)

for each item in the list


if key == value
return successful
else
return unsuccessful
end if
end for
end procedure

• C Program to perform Linear Search:


#include<stdio.h>
#include<stdlib.h>
void main()
{
int i, n, a[10], key;
printf(“enter the number of array elements\n”);
scanf(“%d”, &n);
printf(“enter array elements\n”);
for(i=0; i<n; i++)
{
scanf(“%d”, &a[i]);
}
printf(“enter the key element\n”);
scanf(“%d”, &key);
for(i=0; i<n;i++)
{
if(key==a[i])
{
printf(“successful search\n”);
exit(0);
}
}
printf(“unsuccessful search\n”);
}
2] BINARY SEARCH: This search algorithm works on the principle of divide and conquers.
For this algorithm to work properly, the data should be in the sorted.
There are 3 cases in binary search algorithm
1) Comparing the middle most item of the collection. If a match occurs, then the index of
item is returned.
2) If the middle item is greater than the item, then the item is searched in the sub-array to
the left of the middle item.
3) Otherwise, the item is searched for in the sub-array to the right of the middle item.
This process continues on the sub-array as well until the size of the sub-array reduces to zero.

• C Program to perform Binary Search:


#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[50], n, i, key, low, mid, high;
printf("enter the number of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("enter the key element to be searched\n");
scanf("%d", &key);
low=0;
high=n-1;
while(high>=low)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("successful search, element found");
exit(0);
}
else if (key>a[mid])
{
low=mid+1;
} else
{
high=mid-1;
}
printf("UNSUCCESSFULL SEARCH\n");
}
SORTING: A Sorting is used to rearrange a given array or list elements according to a
comparison operator on the elements. The comparison operator is used to decide the new order
of element in the respective list of elements.

There are two methods of sorting:

1] Bubble Sort. 2] Selection Sort.

1] BUBBLE SORT: Bubble sort is a simple sorting algorithm. This sorting algorithm is
comparison-based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order.

This algorithm is not suitable for large data sets.


Algorithm: Bubble Sort compares each pair of array element unless the whole array is
completely sorted in an ascending order.

for(i=1; i<n; i++) //for loop for number of passes


{
for(j=0;j<n-i;j++) //for loop for number of comparisons
{
if(a[j]>a[j+1]) //Comparison
{
temp=a[j]; //Swap using temp
a[j]=a[j+1];
a[j+1]=temp;
}
}}

• C Program to perform Bubble sort:


#include<stdio.h>
void main()
{
int a[50],i,j,n,temp;
printf("enter the number of terms\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nARRAY ELEMENTS AFTER SORTING\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
2] SELECTION SORT: The Selection sort algorithm is based on the idea of finding the
minimum or maximum element in an unsorted array and then putting it in its correct position in a
sorted array.

• Algorithm:

Selection_sort (int A[ ], int n)


{
int minimum; // temporary variable to store the position of minimum element

for(int i = 0; i < n-1 ; i++) // reduces the comparison size by one in each iteration.
{
minimum = i ; // assuming the first element to be the minimum.
for(int j = i+1; j < n ; j++ ) // gives the effective size of the unsorted array
{
if(A[ j ] < A[ minimum ]) { //finds the minimum element
minimum = j ;
}
}
swap ( A[ minimum ], A[ i ]) ; // putting minimum element on its proper position.
}
}

• C Program to perform Selection Sort:


#include <stdio.h>
void main()
{
int a[100], n, i, j, minimum,temp;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

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


{
scanf("%d", &a[i]);
}
for(int i = 0; i < n-1 ; i++)
{
minimum = i ;
for(int j = i+1; j < n ; j++ )
{
if(a[ j ] < a[ minimum ])
{
minimum = j;
}
}
if (a[minimum ]!= a[i])
{
temp= a[i];
a[i] = a[minimum];
a[minimum] = temp;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", a[i]);
}
}
TWO-DIMENSIONAL ARRAYS(2-D Array): A two dimensional array is used to store
a table of values which has rows and columns. An array that has two subscripts (index), for
example: a[i][j] is known as a two dimensional.

• Some of the uses/applications of the two dimensional arrays are:


1) To maintain the marks of students.
2) To maintain prices of items etc…

a) Two-dimensional Array Declaration: For using arrays in C programs, just like we are
declaring variables before using them, we should declare arrays before using them.

Syntax: for declaring a 2-D Array is shown below:


type arrayName [rows] [columns];

Example:
int x[3] [3];
In the above example ’x’ is an integer array, which can hold 9 integer values.

b) Two-dimensional Array Initialization: Initialization means assigning values. To assign


values to the elements in the array.
Generally, there are two types of initializing an array:
1) Static Initialization (at compile time).
2) Dynamic Initialization (at run time).

In static initialization, the elements of an array are assigned values when the program is
compiled.

Syntax for static Initialization:

type arrayName[row] [columns]= {value1, value2,…valueN};


arrayName[row] [coumns] = value;

Examples: a [0] [0] = 1; int a [3] [3] = {1,1,1,2,2,2,3,3,3};

The memory representation of the two dimensional array will be as shown below:

In dynamic initialization, the values are assigned to the elements of the array during the
execution of the program.

Example: int a[3] [3], i, j;

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

for(j=0;j<3;j++)

scanf(“%d”, a[i][j]);

}
c) Example Program on Two-dimensional Array: C Program to find Transpose of a matrix
#include <stdio.h>
void main()
{
int a[10][10], t[10][10], m, n, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
printf("\nEnter elements of matrix:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
t[j][i] = a[i][j];
}
}
printf("\nTranspose of Matrix:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d ",t[i][j]);
}
}

Additional Programs on Looping Statements & Arrays:


1) C Program to find GCD & LCM using Euclid’s Method.
#include<stdio.h>
void main( )
{
int a, b, m, n, r, gcd, lcm;
printf(“Enter the value of m and n: ”);
scanf(“%d %d”, &m, &n);
a=m;
b=n;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
gcd=a;
lcm=(m*n)/gcd;
printf(“GCD=%d\t LCM=%d”,gcd,lcm);
}

2) C Program to print all numbers between a given range using while loop.
#include<stdio.h>
void main( )
{
int min, max;
printf(“Enter min and max values for range: ”);
scanf(“%d %d”, &min, &max);
while(min<=max)
{
printf(“%d\t”, min);
min++;
}
}

3) C Program to find sum and average of N natural numbers using for loop.
#include<stdio.h>
void main( )
{
int n, i, sum=0;
float avg;
printf(“Enter n value: ”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
sum=sum+i;
}
average=sum/n;
printf(“Sum=%d\t Average=%f”,sum, avg);
}

4) C Program to find factorial of a number using for loop.


#include<stdio.h>
void main( )
{
int n, i, fact=0;
printf(“Enter a number: ”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
fact=fact*i;
}
printf(“Factorial=%d”, fact);
}

5) C Program to print the multiplicative table using for loop.


#include<stdio.h>
void main( )
{
int n, i, mul;
printf(“Enter a number: ”);
scanf(“%d”, &n);
for(i=1; i<=10; i++)
{
mul=n*i;
printf(“%d * %d = %d\n”,n, i, mul);
}
}
6) C Program to print pattern using nested for loop.
#include<stdio.h>
void main( )
{
int n, i, j;
printf(“Enter number of rows: ”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
{
for(j=1;j<=i;j++)
{
printf(“*”)
printf(“\n”);
}
}
7) C Program to copy the contents of an 1D-array using for loop.
#include<stdio.h>
void main( )
{
int a[10], b[10], i, n;
printf(“Enter the number of array elements: ”);
scanf(“%d”, &n);
printf(“Enter the Array elements: ”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
for(i=0;i<n;i++)
{
b[i]=a[i];
}
printf(“Array-B elements: ”);
for(i=0;i<n;i++)
{
printf(“%d\t”,b[i]);
}
}
8) C Program to print the contents of an 1D-array in reverse order.
#include<stdio.h>
void main( )
{
int a[10], i, n;
printf(“Enter the number of array elements: ”);
scanf(“%d”, &n);
printf(“Enter the Array elements: ”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“Printing Array elements in reverse order: ”);
for(i=n-1;i>=0;i--)
{
printf(“%d\t”,b[i]);
}
}
9) C Program to display the even numbers and odd numbers present in an1D-array.
#include<stdio.h>
void main( )
{
int a[10], i, n;
printf(“Enter the number of array elements: ”);
scanf(“%d”, &n);
printf(“Enter the Array elements: ”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“Even Numbers in array are: ”);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
{
printf(“%d\t”, a[i]);
}
}
printf(“Odd Numbers in array are: ”);
for(i=0;i<n;i++)
{
if(a[i]%2!=0)
{
printf(“%d\t”, a[i]);
}
}
}

You might also like