Sie sind auf Seite 1von 55

LOOPS ARRAYS STRINGS

CONTROL STRUCTURES
(LOOPS)
&
ARRAYS AND STRINGS

UNIT III

Mallikharjuna Rao K

LOOPS ARRAYS STRINGS

CONTROL STRUCTURES (LOOPS)

INTRODUCTION
FOR LOOP
WHILE LOOP
DO-WHILE LOOP
NESTED LOOPS

UNIT III

Mallikharjuna Rao K

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

Comparison of Loop Choices


Kind

When to Use

C Structure

Counting loop

We know how many loop


repetitions will be needed in
advance.

while, for

Sentinel-controlled
loop

Input of a list of data ended by a


special value

while, for

Endfile-controlled
loop

Input of a list of data from a data


file

while, for

Input validation
loop

Repeated interactive input of a


value until a desired value is
entered.

do-while

General conditional
loop

Repeated processing of data until a


desired condition is met.

while, for

There are THREE kinds of Loops listed below


for

while

do-while

for( expression1;

While(expression)

do

expression2;
expression3)
{

statement(s);
}

statement(s);

statement(s);
}
While(expression);

}
UNIT III

Mallikharjuna Rao K

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

The re-evaluation parameter decides how to make changes in the loop.


To do this increment/decrement operators are used.
The user is allowed to write a single statement or multiple statements in
the loop body.
Various formats of for loop are
Syntax

Output

Remarks

for(;;)

Infinite loop

for loop with No


arguments

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

Infinite loop

i is neither increased
nor decreased

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

Prints values from 1 to 10

i value is increased
from 1 to 10

for( i=10; i>=0; i-- )

Prints values 10 to 0

i value is decreased
from 10 to 0

UNIT III

Mallikharjuna Rao K

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* write a c program for printing numbers from 1 to 15 */


#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1; i<=15; i++)
{
printf("%d",i);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* WACP to display even numbers upto 15 using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0;
clrscr();
for(;i<15;i+=2)
{
UNIT III

Mallikharjuna Rao K

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* WACP to display sum of first five numbers using for loop */


#include<stdio.h>
#include<conio.h>
void main()
{
int i,sum=0;
clrscr();
for(i=1;i<=5;i++)
{
sum=sum+i;
}
printf("%d",sum);
getch();
}
Output:
15
/* Write a c program to check whether the entered number is prime number or
not
Definition of a prime number:
A natural number greater than one has not any other divisors except 1 and
itself. In other word we can say which has only two divisors 1 and
number itself. For example: 5
Their divisors are 1 and 5.
Note: 2 is only even prime number.

UNIT III

Mallikharjuna Rao K

11

LOOPS ARRAYS STRINGS

Logic for prime number in c


We will take a loop and divide number from 2 to number/2. If the number
is not divisible by any of the numbers then we will print it as prime
number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, count=0;
printf("Enter a number: ");
scanf("%d",&n);
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
count++;
break;
}
}
if(count==0 && n!= 1)
printf("%d is a prime number",n);
else
printf("%d is not a prime number",n);
}
Output
Enter a number: 5
5 is a prime number
Enter a number: 8
UNIT III

Mallikharjuna Rao K

12

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* Write a C program to check the entered number is a palindrome number or


not using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int n, r, sum=0, temp;
printf("Enter a number: ");
scanf("%d",&n);
for(temp=n; n!=0; n=n/10)
{
r=n%10;
sum=sum*10+r;
}
if(temp==sum)
printf("%d is a palindrome",temp);
else
printf("%d is not a palindrome",temp);
getch();
}
Output:
Enter a number: 1221
1221 is a palindrome

UNIT III

Mallikharjuna Rao K

14

LOOPS ARRAYS STRINGS

/* Write a C program to reverse a number using for loop */


#include<stdio.h>
#include<conio.h>
void main()
{
int n, r, reverse=0;
printf("Enter any number: ");
scanf("%d",&n);
for(;n!=0; n=n/10)
{
r=n%10;
reverse=reverse*10+r;
}
printf("Reversed of number: %d",reverse);
getch();
}
Output:
Enter any number: 1234
Reversed of number: 4321

/* 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

LOOPS ARRAYS STRINGS

for(;n!=0;n=n/10)
{
count++;
}
printf("Total digits is: %d",count);
getch();
}
Output:
Enter a number: 456
Total digits is: 3

/* WACP for printing Fibonacci Series c language */


#include<stdio.h> #inlcude<conio.h>
void main()
{

int n, first = 0, second = 1, next, i;


printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( i = 0 ; i < n ;i++ )
{

if ( i <= 1 )
next = i;
else
{

next = first + second;


first = second;
second = next;

}
printf("%d\n", next);
}
UNIT III

Mallikharjuna Rao K

16

LOOPS ARRAYS STRINGS

}
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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* WACP for printing Fibonacci Series using while loop */


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a,b,c;
printf("Enter a number: ");
scanf("%d",&n);
a=0;
b=1;
i=1;
while(i<=n)
{
printf("%d ",a);
c = a + b;
a = b;
b = c;
i++;
}
getch();
}
Output
Enter a Number:
8
0 1 1 2 3 5 8 13...
/*WACP for printing first n terms of fibonacci series using while loop */
#include<stdio.h>
UNIT III

Mallikharjuna Rao K

20

LOOPS ARRAYS STRINGS

#include<conio.h>
void main()
{

int i,n, prev=0,curr=1,temp;


clrscr();
printf("Enter a number\n ");
scanf("%d",&n);
printf("%5d%5d", prev,curr);
i=1;
while(i<=n)
{

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* WACP to reverse a number using do-while loop */


#include<stdio.h>
#include<conio.h>
void main()
{
int r,n,rev;
printf("enter a number\n");
scanf("%d",&n);
do
{
r=n%10;
rev=rev*10+r
printf("%d",rev);
n=n/10;
}while(n!=0);
getch();
}
Output:
Enter any number: 1234
Reversed of number: 4321

UNIT III

Mallikharjuna Rao K

24

LOOPS ARRAYS STRINGS

While Vs. Do-While


While
It is entry-controlled loop
structure
In this the condition is
evaluated first. If the
condition true the body of the
loop will execute.
If the condition
from the loop
executes
statements after
loop

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

LOOPS ARRAYS STRINGS

ARRAYS AND STRINGS


INTRODUCTION
ONE DIMENSIONAL ARRAYS
TWO DIMENSIONAL ARRAYS
ONE DIMENSIONAL CHARACTER ARRAYS(STRINGS)
ARRAY OF STRINGS

UNIT III

Mallikharjuna Rao K

26

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

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

attained by 100 students one by one .While executing the loop


UNIT III

Mallikharjuna Rao K

28

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

An array is finite collection of similar elements, each of the same type.


i.e., we cannot have an array of 30 numbers, of which 10 are int, 10 are
float and 10 are chars.
The first element in array numbered as 0, so the last element is one
less than the size of the array.
Before using the array the type and dimensions must be specified.
A subscript is a number used to refer the individual array element. It is
also called as an index.
Definition and Syntax
Definition: array is a collection of similar data types in which each
element is unique one and located in separate memory locations.
Syntax:
Declaration: Data_type_Name Array_variable_Name[];
Here, data type indicates the type of Data, Variable name is name of the
array variable. [] indicates the subscripts which are used to denote the
size of the array.
Examples:
int a[3];

/* integer array of 3 integers */

char ch[10]; /* character array of 10 characters */


float f[5];

/* floating point array of 5 floating points */

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

LOOPS ARRAYS STRINGS

a[2] refers to 1st element i.e. a[2]=3.


a[3] refers to 1st element i.e. a[3]=4.
a[4] refers to 1st element i.e. a[4]=5.
Characteristics of Arrays:
Ex: int a[5]={1,2,3,4,5};
The declaration in a[5] is nothing but creation of 5 variables of integer
types in the memory. Instead of declaring five variables for five values,
the programmer can define them in an array.
All the elements in the array share the same name, and they are
distinguished from one another with the help of an element number.
The element number in an array plays major role for calling each
element.
Any particular element of an array can be modified separately without
disturbing other elements.
Ex: int a[5]={1,2,3,4,5};
If a user wants to replace 5 with 9, this operation need not require change
all other elements expect 5. to do this task the statement a[4]=9 can be
used. The remaining elements are not disturbed.
Any element of an array a[] can be assigned/equated to another ordinary
variable or array variable of its type
Arrays: Varieties
There are three types:
One-Dimensional Arrays(1D Array)
Two-Dimensional Arrays(2D Array)
Multi Dimensional Arrays

UNIT III

Mallikharjuna Rao K

31

LOOPS ARRAYS STRINGS

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)

(data type)(array name)(index)


And computer reserves five storage locations as shown below.
UNIT III

Mallikharjuna Rao K

32

LOOPS ARRAYS STRINGS

35

MARKS[0]

40

MARKS[1]

20

MARKS[2]

57

MARKS[3]

21

MARKS[4]

Accessing one-Dimensional Arrays:


Declaring One-Dimensional Array:
Like other variables in c, an array must be defined before it can be used
to store data. the general form of one dimensional array declaration is
data_type_Name Array_var_name [size];
where type is a valid c data type, such as int, float, char, var_name is the
name of the array. Size specifies the number of elements in the array.
Example:
int

marks

[5];

float avg

[100];

char

[7];

name

Initializing One-Dimensional Array:


Like other type of variables, you can give values to each array element
when the array is first defined.
the general form of array initialization for one dimensional array is
Data_type array_ name [size] = {list of values};

UNIT III

Mallikharjuna Rao K

33

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* 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

LOOPS ARRAYS STRINGS

}
/* 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

LOOPS ARRAYS STRINGS

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.

A two dimensional array may be used to represent a matrix.

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

LOOPS ARRAYS STRINGS

The actual storage and memory locations are


Row,Col

A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1]

A[2][2]

Value

Address

1000

1002

1004

1006

1008

1010

1012

1014

1016

Accessing 2 Dimensional Arrays


Array element in 2D arrays requires two indexes.
Two-Dimensional arrays are declared as follows.
Syntax:
Data_Type var_name [row_size] [column_size];
Ex:

float sales [4] [3];

rows columns

Initializing Two-dimensional array


Two dimensional arrays are used like one-dimensional array.
Ex: int table [2] [2] = {{1, 2}, {3, 4}}
Initializes the elements 1 and 2 to table [0] [0] and table [0] [1] and 3, 4
to table [1] [0] and table [1] [1]

Rno\Cno

It is important to remember that while initializing an array it is necessary


to mention the second (column) dimension, whereas first dimension (row)
is optional.
Thus the declarations,
UNIT III

Mallikharjuna Rao K

40

LOOPS ARRAYS STRINGS

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}};

Memory map is given by

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

Three- dimensional Array:


It contains three dimensions. i.e. three subscripts are defined.
First subscript indicates number of rows.
Second subscript indicates columns.
Third subscript indicates the number of elements each column element
contains.
For example, the following statement creates a 20X3X3 3D array
int marks [20] [3] [3]
each column element contains three elements
3 columns
20 rows
First element of array will be marks [0] [0] [0] and the last element will be
marks [19] [2] [2]

UNIT III

Mallikharjuna Rao K

41

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

/* WACP to read elements into 2D Array and print the same */


#include<stdio.h>
#include<conio.h>
void main()
{
float a[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]); //reading elements
}
}
printf(The Matrix\n");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("%f",a[i][j]); // printing elements
}
}
getch()
}

UNIT III

Mallikharjuna Rao K

43

LOOPS ARRAYS STRINGS

/* 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

LOOPS ARRAYS STRINGS

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();
}

/* WACP to add two 3X3 2Dimensional matrices*/


#include<stdio.h>
#include<conio.h>
void main()
{
float a[2][2], b[2][2], c[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)
{
UNIT III

Mallikharjuna Rao K

45

LOOPS ARRAYS STRINGS

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]);
}
}
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
c[i][j]=a[i][j]+b[i][j
}
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
{
for(j=0;j<2;++j)
{
printf("%.1f\t",c[i][j]);
if(j==1)
printf("\n");
UNIT III

Mallikharjuna Rao K

46

LOOPS ARRAYS STRINGS

}
}
getch();
}

/* WACP to multiply two 3X3 Matrcies */


#include <stdio.h>
#include<conio.h>
void main()
{
int m, n, p, q, i, j, k, sum = 0;
int a[10][10], b[10][10], m[10][10];
printf("Enter the Size of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the Size of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf(multiplication not possible \n");
else
{
UNIT III

Mallikharjuna Rao K

47

LOOPS ARRAYS STRINGS

printf("Enter the elements of second matrix\n");


for (i = 0; i < p; i++)
{
for (j = 0; j < q; j++)
{
scanf("%d", &b[i][j]);
}
}
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
{
for (k = 0; k < p; k++)
{
sum = sum + a[i][k]*b[k][j];
}
m[i][j] = sum;
sum = 0;
}
}
printf(Multiplication of two matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
printf("%d\t", multiply[c][d]);
printf("\n");
}
UNIT III

Mallikharjuna Rao K

48

LOOPS ARRAYS STRINGS

}
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;

char city [ ] = {H, Y, D, E, R, A, B, A, D, \0};


The memory map is given by
H
UNIT III

Mallikharjuna Rao K

\0
49

LOOPS ARRAYS STRINGS

Reading strings from terminal


The scanf( ) function can be used with %s format specification to read in
a string of characters.
Ex: char city [15];
scanf (%s, city);
The problem with the scanf () function is that it is not capable of
receiving multi-word strings. For example if we give the string New
Delhi it reads only string New into the array city, since the blank space
after the word New will terminate the string.
To address such kind of problems is gets () function is used.
Reading a line of text:

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

LOOPS ARRAYS STRINGS

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

LOOPS ARRAYS STRINGS

computer computer every where computer


Writing strings to screen:
printf (%s, city);
Can be used to display the entire contents of the array name
We can also write like
printf (city);
puts () function:
The puts () function words exactly opposite to gets () function.
It outputs a string to the screen memory that is from array we declare until it
reaches the null character.
The general form of puts () function is
puts (variable name);
puts (city);

String-Handling Function:
The string handling functions are continued in the header file string.h
#include<string.h>

FUNCTION

USE

Strcat()

append one string at the end of another.

Strncat()

appends first n characters of a string at the end of


another.

Strcmp()

compares two strings.

Strcmpi()

compare two strings without case sensitivity.

Strcpy()

copies one string over another.

Strlen()

find the length of a string.

UNIT III

Mallikharjuna Rao K

52

LOOPS ARRAYS STRINGS

Strlwr()

converts a string to lower case

Strupr()

converts a string to upper case.

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

LOOPS ARRAYS STRINGS

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);

Strcpy() Function: General form


Strcpy(string1,string2,n);
This function is used to copy the first n characters of string2 into array
string1.

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

LOOPS ARRAYS STRINGS

A negative value of string1 is less than string2.


A positive value of string1 is greater than string2.

Ex:- strcmp(be , btech);


Will return the value of -15 which is numeric difference between ASCII e
&ASCII t
strlen() Function:
The strlen() function returns an integer specifying the no. of characters
in the string.
General form is strlen(string);
Ex:-strlen(test); will return the value 4.

UNIT III

Mallikharjuna Rao K

55

Das könnte Ihnen auch gefallen