Beruflich Dokumente
Kultur Dokumente
CONTROL STRUCTURES
(LOOPS)
&
ARRAYS AND STRINGS
UNIT III
Mallikharjuna Rao K
INTRODUCTION
FOR LOOP
WHILE LOOP
DO-WHILE LOOP
NESTED LOOPS
UNIT III
Mallikharjuna Rao K
INTRODUCTION
In the modern society the computer and its related products called
software's are engaging everything in the realistic-world. Examples are at
kirana store the store manager is using an application for billing, in the
same way Mobile/Telephone recharges, Ticket reservation, Banking
Transactions, Traffic Signals, Alarm signals in refrigerator.etc. And
these tasks are performed by each person for a number of times in a day.
All these are fulfilling the user needs using software applications.
What is software?
Is a set programs when executed provided desired features, functions and
performance.
A single user may perform transactions one time or multiple times in a
day, in the same way multiple users may perform different actions at
different times for multiple times. In this process many tasks are executed
in repetitive in nature. For example salary calculations for employees,
Marks calculations at universities/colleges, scanning the items at bill
counter, Withdrawing/Depositing the cash at ATMs, recharging mobiles,
X-Rays, various scanning's at diagnostic centreetc. i.e. the same task
is executing for several times in a single day.
Such type of repetitive actions can be easily done using a program that
has a loop built into the solution of the problem.
What is a loop?
A loop is a control structure that contains a block of statements which
are repeatedly executed for certain number of times.
The loop body contains the statements which are executed for several
times.
There are two types of loop structures
Pretest loop: the condition is tested before each iteration when loop
occurs
UNIT III
Mallikharjuna Rao K
Posttest loop: the condition is tested after each iteration when the loop
continues to execute the statements.
Loops
Every loop contains three components. They are
Loop variable: it is a variable used in the loop
Initialization: it is the first step in which starting and final value is
assigned to the loop variable. Each time the updated value is checked by
the loop itself.
Updation (increment/decrement): it is the numerical value added or
subtracted to the variable in each iteration of the loop
Flow Diagram of Loop Choice Process
UNIT III
Mallikharjuna Rao K
When to Use
C Structure
Counting loop
while, for
Sentinel-controlled
loop
while, for
Endfile-controlled
loop
while, for
Input validation
loop
do-while
General conditional
loop
while, for
while
do-while
for( expression1;
While(expression)
do
expression2;
expression3)
{
statement(s);
}
statement(s);
statement(s);
}
While(expression);
}
UNIT III
Mallikharjuna Rao K
for loop
The for loop statement contains three actions. They are
Initialization
Test condition
Re-evaluation parameters
These are separated by semicolon(;)
The for loop allows a user to execute a set of instructions until a certain
condition is satisfied. If the condition may be predefined or open-ended.
Syntax:
for(initialization; test-condition; re-evaluation parameter)
{
statement1;
statement2;
..
}
The initialization sets a loop to an initial value. This element is executed
only once.
The test condition is a relational expression that determines the number
of iterations desired or it determines when to exit from the loop. The for
loop continues execution until the condition is failed. If the condition is
true the loop body will execute. If the condition fails exits from the for
loop and executes the remaining statements in the program.
UNIT III
Mallikharjuna Rao K
Output
Remarks
for(;;)
Infinite loop
Infinite loop
i is neither increased
nor decreased
i value is increased
from 1 to 10
Prints values 10 to 0
i value is decreased
from 10 to 0
UNIT III
Mallikharjuna Rao K
PROGRAMMING EXAMPLES:
/* write a c program for printing first 5 numbers and their squares */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1; i<=5; i++)
{
printf("number is %d its square is %d\n",i,i*i);
}
getch();
}
Output
Number is 1 its square is 1
Number is 2 its square is 4
Number is 3 its square is 9
Number is 4 its square is 16
Number is 5 its square is 25
UNIT III
Mallikharjuna Rao K
Mallikharjuna Rao K
printf("%d",i);
}
getch();
}
Output
2 4 6 8 10 12 14
/* WACP to display odd numbers upto 15 using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
for(;i<=15;i+=2)
{
printf("%d",i);
}
getch();
}
Output
1 3 5 7 9 11 13 15
UNIT III
Mallikharjuna Rao K
10
UNIT III
Mallikharjuna Rao K
11
Mallikharjuna Rao K
12
8 is a prime number
/* Write a C program for prime numbers between 1 to 100 */
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, count=0;
for(n = 1;n<=100;n++)
{
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
count++;
break;
}
}
if(count==0 && n!= 1)
printf("%d ",n);
}
getch();
}
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
UNIT III
Mallikharjuna Rao K
13
UNIT III
Mallikharjuna Rao K
14
/* Write a C code to count the total number of digit using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int n, count=0;
printf("Enter a number: ");
scanf("%d",&n);
UNIT III
Mallikharjuna Rao K
15
for(;n!=0;n=n/10)
{
count++;
}
printf("Total digits is: %d",count);
getch();
}
Output:
Enter a number: 456
Total digits is: 3
if ( i <= 1 )
next = i;
else
{
}
printf("%d\n", next);
}
UNIT III
Mallikharjuna Rao K
16
}
Output
Enter a Number:
8
0 1 1 2 3 5 8 13 21...
/* WACP for finding factorial of a given number */
#include <stdio.h>
#include<conio.h>
void main()
{
int i, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
fact = fact * i;
}
printf("Factorial of %d = %d\n", n, fact);
getch();
}
Output
Enter a number to calculate it's factorial
5
Factorial of 5 = 120
Enter a number to calculate it's factorial
6
Factorial of 6 = 720
UNIT III
Mallikharjuna Rao K
17
While Loop
It is the simplest loop.
The While is an entry-controlled loop statement.
The test-condition is evaluated and if the condition is true, then the body
of the loop is executed. After execution of the body, the test-condition is
repetitively checked and if it is true the body is executed.
The process of execution of the body will be continuing till the testcondition becomes false.
If the condition is false, the control exits from the loop body and continue
the remaining statements execution.
The loop body contains a single statement or multiple statements. The
same loop body will be repeated.
The braces are needed to write loop body.
Syntax and Flow Chart
Syntax:
Flow Chart
While (test-condition)
{
statement1;
statement2;
TestCond
ition
.
.
.
False
True
}
Body of the Loop
UNIT III
Mallikharjuna Rao K
18
PROGRAMMING EXAMPLES:
/* WACP to find whether a number is palindrome or not */
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,sum=0,temp;
printf("Enter a number: ");
scanf("%d",&n);
temp=n;
while(n!=0)
{
r=n%10;
sum=sum*10+r;
n=n/10;
}
if(temp==sum)
printf("%d is a palindrome",temp);
else
printf("%d is not a palindrome",temp);
getch();
}
Output:
Enter a number: 1331
1331 is a palindrome
UNIT III
Mallikharjuna Rao K
19
Mallikharjuna Rao K
20
#include<conio.h>
void main()
{
temp=prev+curr;
printf("%5d",temp);
prev=curr;
curr=temp;
i++;
} getch();
}
Output
Enter a number
8
0 1 1 2 3 5 8 13
UNIT III
Mallikharjuna Rao K
21
Do-While
It is exit-controlled loop statement.
On reaching the do statement, the program first executes the loop body
once. At the end of the loop body, the test-condition is evaluated in the
while statement. If the condition is true, the program continues to
evaluate the body of the loop repetitively. This process continues until the
condition is true.
If the test-condition is false the control exits from the loop body and
continues the execution of remaining statements.
Since the condition is tested later, the loop body is executed at least once
before testing the condition.
Syntax and Flow chart
Syntax
Flow chart
do
{
statement1;
Body of the Loop
statement2;
.
.
.
TestCondition
}while(test-condition);
False
True
UNIT III
Mallikharjuna Rao K
22
PROGRAMMING EXAMPLES:
/* WACP for finding factorial of a given number using do-while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int fact=1,n,i=1;
printf("Enter no whose factorial is to be found/n");
scanf("%d",&n);
do
{
fact=fact*i;
i++;
}while(i<=n);
printf("Factorial of %d=%d\n",n,fact);
}
Output
Enter no whose factorial is to be found
5
Factorial of 5 = 120
Enter no whose factorial is to be found
3
Factorial of 3 = 6
UNIT III
Mallikharjuna Rao K
23
UNIT III
Mallikharjuna Rao K
24
UNIT III
false exits
body and
immediate
the while
do-while
It is exit-controlled loop structure
In this the condition is evaluated
after execution of loop body at
least once. i.e. loop body will
execute first then while condition.
The loop body will execute until
the condition is true. If the
condition is failed exits from the
do-while loop and executes the
remaining statements.
Mallikharjuna Rao K
25
UNIT III
Mallikharjuna Rao K
26
INTRODUCTION
In earlier chapters we discussed about the fundamental data types,
namely int, float, char, double and the flavours of int and double. The
variables defined as any one of these data types are limited to define or
store only one value at any given time(compile time/run time). So, they
can be used only to handle limited amounts of data. But in many
applications requesting to handle large amount of data items in terms of
reading, processing and printing.
The computer programs need memory cells to hold data at execution
time. The amount of total memory to store data may differ from one
program to other. The example are:
Maintenance of student details(Regd. No, Marks, Batchetc) at
College or University.
Maintenance of employee details(Name, Designation, department
etc) at one organization.
Weather forecasting i.e. maintenance of temperatures for every
hour in a day, or a month or a year.
List of product details at super markets.
Examples that are denoting importance of arrays:
Example1:
For example consider the below program
#include<stdio.h>
#include<conio.h>
void main()
{
UNIT III
Mallikharjuna Rao K
27
int a=2,b;
clrscr();
a=3+2;
b=4+a;
printf(a=%d\n b=%d,a,b);
getch();
}
From the above program the value of b is printed as 9, in line number 8 the b
value is evaluated is 4 is added with a value. Originally a is initialized as
value 2, but at the time of computing b value the updated value of the
variable a is used in b value computation. The original value 2 of variable a
is override as 5 in line number 8. So one variable can hold only one value at
a time.
Example2:
The variables which we are used so far were ordinary or simple variable
because they can hold once one value at a time .The ordinary variables
are also called as unsubscripted or scalar variables
However there are situations in which we would want to store more than
one value at a time in a single variable. Here arises the need of
subscripted variable or arrays.
Example3:
For example suppose we wish to find average marks obtained by class of
100 students in a class. In such a case we wish to do there are two types
of options
Construct 100 different variables to store marks attained by 100
different students i.e, each variable contain one student marks.
Construct a for loop using a single variable
to store marks
Mallikharjuna Rao K
28
each time the scanf function replace the previous value of marks
.Hence after completion of loop marks variable will have a value
that we entered during the last pass of loop .
We need a powerful data type that would facilitate efficient storing,
accessing and manipulation of data items.
C provides a derived data type called array that can be used for such
applications.
ARRAYS
INTRODUCTION
Arrays are the solutions to the above problems.
Array allows us to represent many quantities with one variable name.
Also arrays are the alternate mechanism to handle groups of related data.
WHAT IS AN ARRAY?
Array is another form of data type.
Definition: An array is an ordered finite collection of similar quantities,
i.e. an array is a collection of similar data type elements.
An array is also called as a subscripted variable.
There can be array of integers, array of floating point numbers, array of
characters etc.
Thus an integer array will have all its elements as integers only.
Another important issue is that an array is a group of continuous memory
locations represented with the same name and same type. To refer a
particular location or element in the array, we specify the name of
the array and the position number of the particular element in the
array.
Points to Remember
UNIT III
Mallikharjuna Rao K
29
Array Initialization:
Ex: int a[5]={1,2,3,4,5}
Here, 5 elements are stored in an array a. The array elements are stored
sequentially in separate locations. The array elements are called by array names
followed by the element numbers.
Calling array elements is as follows
a[0] refers to 1st element i.e. a[0]=1.
a[1] refers to 1st element i.e. a[1]=2.
UNIT III
Mallikharjuna Rao K
30
UNIT III
Mallikharjuna Rao K
31
One-Dimensional Array:
A group of items can be given one variable name using only one
subscript and such a variable is called a one dimensional array or
single subscript variable.
Any one of these elements may be referred to, by giving the name of the
array followed by the position number of the particular element in square
brackets ([ ]).
Remember in C-Langauage the element of any array are numbered
starting with 0, not with 1. Therefore the first element in array mark is
referred to as mark [0], second element is mark [1], and ith element of
the array is referred to as mark [i-1].The value of the subscript are lie
with in the range 0 to (i-1).
Rules for Array Names:
The name of the array is formed in the same way as the name of
the ordinary variable.
Array name cannot begin with a digit.
Array name contains only letter, digit and underscore characters.
The position number contained with in square brackets is called a
subscript. A subscript must be an integer or an integer expression.
For example if we want to represent a set of five numbers, say (35, 40,
20, 57, 21), by an array variable marks as follows.
int
marks
[5] ;( subscript)
Mallikharjuna Rao K
32
35
MARKS[0]
40
MARKS[1]
20
MARKS[2]
57
MARKS[3]
21
MARKS[4]
marks
[5];
float avg
[100];
char
[7];
name
UNIT III
Mallikharjuna Rao K
33
The values in the list are separated by commas .the first value will be
placed in the first position of the array, the second value in the second
position and so on.
Examples:
int a [3] = {1, 4, 9}; will assign the value 1 to a [0], 4 to a [1], 9 to a [2]
char gender [2] = {m,f} will assign the value m to gender [0], f to
gender [1] and 10 to gender [2] where 10 is null character.
int age [5] = {26, 18, 65}; allocate five elements to age, and then
initializes age [0] 26, age [1] 18, age [2] 65 setting the remaining
elements to 0
Note: Array can not be automatically initialized to zero .The programmer must
at least initialize the first element to zero for remaining elements to be
automatically zeroed.
It is not always necessary to specify the size of an array if it is being
initialized.
For example
int num [] = {21, 62, 38, 65, 70};
Will declare num array to contain five elements, and then initializes
num [0] to 21, num [1] to 62, num [1] to 38, num [1] to 65 and, num [1] to 70.
UNIT III
Mallikharjuna Rao K
34
PROGRAMMING EXAMPLES:
/* W A C P for reading elements into an array */
#include<stdio.h>
#include<conio.h>
void main ()
{
int a[5],i;
printf(enter elements into an array\n);
for(i=0;i<5;i++)
{
scanf(%d,&a[i]); // reading elements
}
getch();
}
/* W A C P for reading elements into an array and print the same array
elements*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
clrscr();
printf("enter elements into an array\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]); // reading elements
}
UNIT III
Mallikharjuna Rao K
35
for(i=0;i<5;i++)
{
printf("%d",a[i]); // printing elements
}
getch();
}
/* W A C P for reading elements into an array and display the sum of the
elements */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,sum=0;
clrscr();
printf("enter elements into an array\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
printf("%d element is %d\n",i,a[i]);
sum=sum+a[i];
}
printf("the sum of array elements is %d",sum);
getch();
}
UNIT III
Mallikharjuna Rao K
36
/* WACP for finding the maximum and minimum from a set of numbers */
#include<stdio.h>
#include<conio.h>
void main ()
{
int i, n;
float x[20], max, min;
printf ("\n How many numbers");
scanf ("%d", &n);
for (i=0; i<n; i++)
{
printf ("\n Enter number #%d:", i+1);
scanf ("%f", &x[i]);
}
max=min=x[0];
for (i=1; i<n; i++)
{
if (x[i]>max)
max=x[i];
}
printf ("\n Largest number is %f", max);
for (i=0; i<n; i++)
{
if(x [i] <min)
min=x [i];
}
printf ("\n Smallest element is %f", min);
getch();
UNIT III
Mallikharjuna Rao K
37
}
/* WACP that read in an array of numbers and print in reverse order like if the
input is 23,34,123,7 the output for the input is 7,123,34,23 */
#include<stdio.h>
#include<conio.h>
void main ()
{
int x [20], y [20],i, j, n;
printf (\n How many numbers);
scanf (%d,&n);
for (i=0; i<n; i++)
{
printf (\n Enter number # %d:, i+1);
scanf (%d, &x[i]);
}
for (i=0; i<n; i++)
{
y [n-i-1] =x[i];
}
printf (\nOri Num \t Rev Num\n);
for (j=; j<n; j++)
{
printf (\n %d \t\t\t %d, x[j], y[j]);
}
getch();
}
UNIT III
Mallikharjuna Rao K
38
Multi-dimensional Arrays
A multi-dimensional array can be two-dimensional or three-dimensional
array. Multi-dimensional arrays operate on same principle as one
dimensional array.
Two-dimensional Array: The elements of the array could be represented either as a single row or a
single column. Often, there is a need to store table of values.
C allows us to store a table of values by using two-dimensional arrays. To
identify a particular table element, we must specify two subscripts.
The first subscript identifies the elements row and the second
subscript identifies the elements column.
Example:
A=
A11
A12
A13
A21
A22
A23
A31
A32
A33
Storage and Memory locations for the above matrix is as follows. This is
for our understanding purpose only.
UNIT III
Rno\Cno
Col0
Col1
Col2
Row0
A[0][0]
A[0][1]
A[0][2]
Row1
A[1][0]
A[1][1]
A[1][2]
Row2
A[2][0]
A[2][1]
A[2][2]
Mallikharjuna Rao K
39
A[2][2]
Value
Address
1000
1002
1004
1006
1008
1010
1012
1014
1016
rows columns
Rno\Cno
Mallikharjuna Rao K
40
static int arr [2] [3] = {12, 34, 23, 45, 56, 45};
static int arr [] [3] = {12, 34, 23, 45, 56, 45}; are acceptable
Ex:- int stud [4] [2] = {{1234, 56}, {1212, 33}, {1434, 80}, {1312, 78}};
indexes
S[0][0]
S[0][1]
S[1][0]
S[1][1]
S[2][0]
S[2][2]
S[3][0]
S[3][3]
values
1234
56
1212
33
1434
80
1312
78
5002
5004
5006
5008
5014
5016
Address
5010
5012
Location
UNIT III
Mallikharjuna Rao K
41
Initializing A 3D-array
3D-array can be initialized as
int test_scool [4] [2] [3] = {
{{2, 4, 7}, {8, 3, 4}},
{{5, 6, 7}, {6, 3, 4}},
{{5, 3, 2}, {9, 4, 1}},
{{8, 3, 2}, {2, 3, 3}}
};
PROGRAMMING EXAMPLES:
/* WACP to read elements into 2D Array */
#include<stdio.h>
#include<conio.h>
void main()
{
float a[2][2];
int i,j; // loop variables
printf("Enter the elements of the matrix\n");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
// reading elements
}
}
getch()
}
UNIT III
Mallikharjuna Rao K
42
UNIT III
Mallikharjuna Rao K
43
/* WACP to read elements into two 2D Arrays and print the same */
#include<stdio.h>
#include<conio.h>
void main()
{
float a[2][2], b[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("Enter a%d%d: ",i+1,j+1);
scanf("%f",&a[i][j]);
}
}
printf(" Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("Enter b%d%d: ",i+1,j+1);
scanf("%f",&b[i][j]);
}
}
printf("1st matrix\n");
for(i=0;i<2;++i)
{
UNIT III
Mallikharjuna Rao K
44
for(j=0;j<2;++j)
{
printf("%f",a[i][j]);
}
}
printf("2nd matrix\n");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("%f",b[i][j]);
}
}
getch();
}
Mallikharjuna Rao K
45
Mallikharjuna Rao K
46
}
}
getch();
}
Mallikharjuna Rao K
47
Mallikharjuna Rao K
48
}
getch();
}
Strings
What are strings?
A string is a series of characters enclosed within double quotation marks.
A string may include letters, digits and various special characters such as
+, -, *, $
String constants are also referred as string literals
Ex: abcd, 999 main road, \\n,
C has no built-in string data type.
A string in c is defined as an array of characters ending in the null
character (\0). Therefore a string is an array of characters
Declaring and initializing string variables
The general form is
char string [size];
The size specifies the maximum number of characters in the string_name
Ex:
char name [20];
char color [8];
When the compiler assigns a character string to a character array, it
automatically supplies a null character (\0) at the end of the string.
C permits a character array to be initialized as follows.
char city [ ] = HYDERABAD;
Mallikharjuna Rao K
\0
49
If your wish to read a line containing more than one word from the
terminal use getchar () function.
PROGRAMMING EXAMPLES
/* W A C P for reading charecter elements into an array and display them */
#include<stdio.h>
#include<conio.h>
void main()
{
char ch[10]; int i;
clrscr();
printf("enter character elements into an array\n");
for(i=0;i<5;i++)
{
scanf("%c",&ch[i]);
}
for(i=0;i<5;i++)
{
UNIT III
Mallikharjuna Rao K
50
printf("%c",ch[i]);
}
getch();
}
gets () function:
The gets () function is used to read characters entered at the keyboard until you
press Enter key. Thus, spaces and tabs are perfectly acceptable as part of the input
string.
general form:
gets (variable name);
Programming Example
#include<stdio.h>
#include<conio.h>
void main ()
{
char string [80];
int i, n;
printf (\n Enter a line of text);
gets (string);
printf (\n output);
puts (string);
}
OUTPUT:
Enter a line of text.
computer computer every where computer
output:
UNIT III
Mallikharjuna Rao K
51
String-Handling Function:
The string handling functions are continued in the header file string.h
#include<string.h>
FUNCTION
USE
Strcat()
Strncat()
Strcmp()
Strcmpi()
Strcpy()
Strlen()
UNIT III
Mallikharjuna Rao K
52
Strlwr()
Strupr()
Strrev()
Reverse a string.
Strdup()
duplicate a string.
Srcat() function:
The strcat(string concatenation) function joins two strings to form a third string.
The general form is
strcat(string1,string2);
Where string1,string2 are character arrays
The function appends array string2 to array string1 and terminates string1with a
null.
Ex
#include<stdio.h>
#include<conio.h>
void main ()
{
char str1[20] , str2[20] , str3[40];
printf(\nEnter first string:);
gets(strl);
printf(\nEnter the second string:);
gets(str2);
printf(\nout put);
printf(strcat(atr1,str2)=%s\n,strcat(str1,str2));
printf(\nAccording to srtncaf);
printf(strcat(str1,str2,5)=%s\n,strncaf(str1,str2,5));
}
UNIT III
Mallikharjuna Rao K
53
output:
Enter the first string: Happy
Enter the second string: New year
Output Explanation:
According to strcat:
Strcat(str1,str2)=Happy New Year
According to strncat:
Strncat(str1,str2,5)=Happy New Year New.
Strncat() Function:
The function takes the following form.
Strncat(string1,string2,n);
C allows nesting of strcat function.
Strcat(strca(s1,s2),s3);
strcmp() Function:
The strcmp() function compares two strings to find out whether they are
same or different.
General form is strcmp(string1,string2);
The above function returns an integer .
The function return a value 0 of the two strings are same.
UNIT III
Mallikharjuna Rao K
54
UNIT III
Mallikharjuna Rao K
55