You are on page 1of 23

C Programming and Data Structures

(R20 Syllabus JNTUA,Anantapuramu)


UNIT-I
Syllabus
Introduction to C Language - C language elements, variable declarations and data types,
operators and expressions, decision statements - If and switch statements, loop control statements -
while, for, do-while statements, arrays.
Introduction to C Language
1.1 C language elements or C Tokens

C language
Preprocessor and
Preprocessordirective elements
ss

Keywords Identifiers Constants Strings Special Symbols operators


ex:float,while ex:amount Ex:15.5,150 (ex:”ABC”) { },”,],( +,-,*,/,%

Keywords and identifiers :


All Keywords have fixed meanings and these meanings can not be
changed.Keywords must be written in lowercase.
ANSI C Keywords

auto double int struct break else long switch


case enum register typedef char extern return union
const float short unsigned continue for signed void
default goto sizeof volatile do If Static while

Identifiers refer to the names of variables,functions and arrays.Both uppercase


and lowercase letters are permitted.The underscore character is also permitted in identifiers.

Constants: Constants in c refer to fixed values that do not change during the execution of a program.
Constants

Numeric non numeric

integer real character string


Strings: A String constant is a sequence of character enclosed in double quotes.The characters may be
letters, numbers, special characters and blank space. Example: “Hello”,”1987”, “ Well Done”,’?....!”
Remember that a character constant eg:’x’ is not equalent to the single character string constant.
operators: In order to perform different kind of operators, C uses different operators. An operator indicates
an operation to be performed on data that yields a value.
special symbols: uses the so many special symbols in the ‘C’ language.Example :{,] “,, !

Pre processor: It is a system program that modifies a c program prior to its compilation.
Preprocessor directive: C Program beginning with # that provides an instruction to the pre-processor.

/* converts distances from miles to kilometres */

Preprocessor directive
header file

#include<stdio.h> comments
#include<conio.h>
#define KMS_PER_MILE 1.609 /* conversion constant */
void main()
{ standard identifiers
double miles,kms;
clrscr();
printf(“\n Enter the distance in miles \n”); special symbol
scanf(“%lf”,&miles);
kms = KMS_PER_MILE *miles;

printf(“ that equals %f kilometres \n”,kms);


getch();
}

The # include directive gives a program access to a library. This directive causes the pre-
processor to insert definitions from a standard header file into a program before compilation. The directive
notifies the pre-processor that some names used in the program are found in the standard header
file<stdio.h> comments provide supplementary information making it easier for us to understand the
programs but comments are ignored by the C Preprocessor and compiler.

Variable Declarations: It varies the value during the execution of the program. A variable is a data name
that may be used to store a data value. Unlike constants that remain unchanged during the execution of a
program,
a variable may take different values at different times during execution.
Example: average,total,height,counter_1, class_strength.
Variable names may consists of letter digits and the underscore(_) character subject to the following
conditions.
1. They must begin with a letter.Some systems permit underscore as the first character.
2.ANSI standard recognizes a length of 31 characters. However the length should not be normally more
than eight characters since only the first eight characters are treated as significant by many computers.
3.Uppercase and Lowercase are significant.that is the variable Total is not as the same as total.
4.Variable name should not be a keyword
5.white space is not allowed.
variable _name valid Remarks
first_tag valid --------
char not valid Char is a Keyword
price$ not valid Dollar is illegal
group one not valid Blank space not allowed
int_type valid Keyword may be part of name

Data types: The variety of data types available allow the programmers to select the type appropriate to
the needs of the application as well as the machine .
ANSI C Supports these classes od data type
1.Primary or fundamental data type
2.Derived data types (Arrays,structures pointers,unions)
3.User defined data types
4.Enumerated data type

The Range of the basic four types are given in table.

PRIMARY DATA types


Integral type

integer character
signed unsigned type char
int unsigned int signed char
short int unsigned short int unsigned char
long int unsigned long int

Floating point type

VOID
float double long double

Data type Range of value

Char -128 TO +127


int -32,768 TO +32,767
Float 3.4 e-38 to e+38
double 1.7 e-308 to 1.7 e+308
integer types: : Integers are whole numbers with range of values supported by a particular
machine.Generally, integers occupy one word of storage and since the word sizes of machines vary the size
of an integer that can be stored depends on the computer. If we use a 16 bit word length, the size of the
integer value is limited to the range -32,768 to +32,767. A 32 bit word length can store an integer ranging
from -2,147,483,648 to 2,147,483,647.

short int

int

long int

Type size Range

char or signed char 8 -128 to 127


unsigned char 8 0 to 255
int or signed int 16 -32,768 to +32,767
unsigned int 16 0 to 65535
short int or signed short int 8 -128 to 127
unsigned short int 8 0 to 255
long int or singed long int 32 -2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
float 32 3.4 E-38 to 3.4 to E+38
double 64 1.7 e-308 to 1.7 e+308
long double 80 3.4 E-4932 to 1.1 E+4932

Floating point types


floating point numbers are stroed in 32 bits (on all 16 bit and 32 bit machines) with 6 digits of precision
when the accuracy provided float number is not sufficient, the type double can be used to define the
number. A double data type number uses 64 bits giving a precision of 14 digits. to extend the precision
further, we may use long double which uses 80bits.

Float
double

long double

void type: the type of a function is said to be void when it does not return any value to the calling function.

character type: Characteres are usually stored in 8 bits of internal storage. The qualifier signed or unsigned
may be explicitly applied to char.while unsigned char have values between 0 and 255, signed chars have
values from -128 to +127.

Operators

In order to perform the different kind of operations, c uses different operators.


An operator indicates an operation to be performed on data that yields a value.

Arithmetic operators

The binary arithmetic operators are +,-,*,/ and modulus operator %. Integer truncates
any factional part. The expression x%y Produces the remainder when x is divided by y and thus is zero
when y divides x exactly. The % operator can not be applied to float or double.
Example Program:
write a program to convert days to months and days.
#include<stdio.h>
#include<conio.h>
void main()
{
int months,days;
clrscr();
printf(“\n Enter days \n”);
scanf(“%d”,&days);
months = days/30;
days = days%30;
printf(“\n months = %d days =%d”,months,days);
getch();
}

output:
Enter days
25
months = 8 days = 25

Relational operators: These operators are used to distinguish between two values depending on their
relations. These operations provides the relationship between the two expressions. If the relation is true
then it returns a value 1 otherwise 0 for false relation.
Write a program to use various relational operators and display their return values.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“\n Condition : return values \n”);
printf(“\n 10!=10 : %d”,10!=10);
printf(“\n 10==10 : %d”,10==10);
printf(“\n 10>=10 : %d”,10>=10);
printf(“\n 10<=100 : %d”,10<=100);
printf(“\n 10!=9 : %d”,10!=9);
getch();
}
output
condition : Return values
10!=10 : 0
10==10 : 1
10>=10 : 1
10<=100 :1
10!=9 :1

Logical operators The logical relationship between the two expressions are checked with logical
operators.Using these operators two expressions can be joined. After checking the conditions it provides
logical true(1) or false (0) status. The operands could be constants, variables and expressions.
1. The logical AND (&&) operator provides true result when both expressions are true otherwise 0.
2. The logical OR (||) operator provides true result when one of the expressions is true(1) otherwise 0.
3. The logical not operator(!) provides 1, if the condition is true otherwise 0.

Example to illustrate the use of logical operator.


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“\n condition : Return values \n”);
printf(“\n 5>3 && 5<10: %d”,5>3 && 5<10);
printf(“\n 8>5 || 8<2:%d”,8>5||8<2);
printf(“\n !(8==8):%d”,!(8==8));
getch();
}
output:
condition: Return values
5>3 && 5<10 : 1
8>5 || 8<2 :1
!(8==8) :0
Bitwise operators
C supports a set of bitwise operators as listed in the table. These operators can
operate only on an integer operands such as int,char,short, long int etc
operator meaning
>> Right shift operator
<< Left shift operator
^ Bitwise XOR(exclusive OR)
& Bitwise AND
| Bitwise OR

Right shift operator(>>)


write a program to shift inputed data by two bits right.
void main()
{
int x,y;
clrscr();
printf(“\n Read the integer from keyboard\n”);
scanf(“%d”,&x);
x>>=2;
y =x;
printf(“\n The right shifted data is = %d”,y);
getch();
}
output: Read the integer from keyboard
8
The right shifted data is = 2.

Before the execution of the program: The number entered through the keyboard is 8 and is
corresponding binary number is 1000
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
After the execution of the program : As per the above program the inputted data x is to be shifted by 2
bits right side. The answer in binary bits would be as follows.

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

shifting two bits right means the inputted number is to be divided by 2s where s is number of shifts i.e in
short y =n/2s where n =number and s =number of positions to be shifted

y = 8/22 = 2.
Left shift operator(<<)
Write a program to shift inputted data by three bits left.
void main()
{
int x,y;
clrscr();
printf(“\n Read the integer from keyboard\n”);
scanf(“%d”,&x);
x<<=3;
y =x;
printf(“\n The left shifted data is = %d”,y);
getch();
}
output
Read the integer from keyboard 2
the left shifted data is = 16

before the execution of the program:


The number entered through the keboard is 2 and its corresponding binary number is 10. the bits will be as
follows
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

After the execution of the program : As per the above program the inputted data x is to be shifted by 3
bits left side. the answer in binary bits would be as follows.
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

The corresponding decimal number is 16 that is answer should be 16. shifting three bits left means number
is multiplied 8 in short y = n*2s
where n = number
s = number of positions to be shifted
y = 2*23 = 16.
Bitwise AND(&)
Write a program to use bitwise and operator between the two integers and display the result
Table AND
Input output
X Y z
0 0 0
0 1 0
1 0 0
1 1 1

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“\n Enter the integers from keyboard a and b \n”);
scanf(“%d%d”,&a,&b);
c = a & b;
printf(“\n The Answer after ANDing is c = %d”,c);
getch();
}
output:
Enter the integers from keyboard a and b : 8 4
The answer after ANDing is c = 0
Before execution of the program
a=8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

b=4
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

After execution of the program


c=0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
BITWISE OR(|)

write a program to operate OR operation on two integers and display the result.

Input output
X Y z
0 0 0
0 1 1
1 0 1
1 1 1

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“\n Enter the integers from keyboard a and b \n”);
scanf(“%d%d”,&a,&b);
c = a | b;
printf(“\n The Answer after ORing is c = %d”,c);
getch();
}
output:
Enter the integers from keyboard a and b : 8 4
The answer after ORing is c = 12
Before execution of the program
a=8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

b=4
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

After execution of the program


c = 12

0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Bitwise EX-OR(exclusive OR)

write a program to operate EX-OR operation on two integers and display the result.

Input output
X Y z
0 0 0
0 1 1
1 0 1
1 1 0

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“\n Enter the integers from keyboard a and b \n”);
scanf(“%d%d”,&a,&b);
c = a ^ b;
printf(“\n The Answer after EX-ORing is c = %d”,c);
getch();
}
output:
Enter the integers from keyboard a and b : 8 2
The answer after EX-ORing is c = 10
Before execution of the program
a=8
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

b=2
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

After execution of the program


c = 10

0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Unary operators: Unary operators are increment operator(++), decrement operator(--) and minus(-)

Write a program to show the effect of increment operator as suffix


#include<stdio.h>
#include<conio.h>
void main()
{
int a,z, x =10, y =20;
clrscr();
z = x*y++;
a = x*y;
printf(“%d\t%d”,z,a);
getch();
}
output : 200 210
Explanation: In the above program the equation z = x*y++ gives the result 200 because y does not gets
increased. After multiplication ‘y’ increases to 21. The second equation gives result 210.

Write a Program to show the effect of increment operator as prefix


#include<stdio.h>
#include<conio.h>

void main()

{
int a,z, x =10, y =20;
clrscr();
z = x*++y;
a = x*y;
printf(“%d\t%d”,z,a);
getch();
}
output : 210 210

Write a program to use ‘&’ and ‘sizeof()’ operator and determine the size of integer and float variables.
#include<stdio.h>
#include<conio.h>
void main()
{
int x=2;
float y =2;
clrscr();
printf(“\n Size of x = %d bytes “,sizeof(x));
printf(“\n Size of y = %d bytes”,sizeof(y));
printf(“\n address of x = %u and y = %u”,&x,&y);
getch();
}

assignment operator: we can use the assignment operator within any valid expression. The general form
of assignment operator is
variable_name = expression
Example: x = 1; x = i*x;
 we can assign many variables the same value by using multiple assignments in a single statement.
example : x = y =z =0;
 there is a variation on the assignment statement called compound assignment
example: x = x+10 can be written as x += 10
Example:x = x-100 can be written as x -= 100
Conditional operator: the conditional operator contains a condition followed by two statements or
values.If the condition is true the first statement is executed otherwise the second statement. The
conditional operator sometimes called ternary operators because they take three arguments.
Syntax condition ? (expression1):(expression2);
Example: z = (a>b) ? a:b;

Write a program to determine the value of ‘b’ depending the inputted value of ‘a’. the variable a is used
with conditional operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“\n Enter any integer either above 5 or below 5 \n”);
scanf(“%d”,&a);
b = (a>5?3:4);
printf(“\n calculated value of b is : %d”,b);
getch();
}
output:
Enter any integer either above 5 or below 5
calculated value of b is 3

Write a program to use the conditional operator with two values.


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“ Result = %d”,2==3?4:5);
getch();
}
output: result = 5
Write a program to use the conditional operator with two statements.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
3>2 ? printf(“true”): printf(“false”);
getch();
}
output: true
Expressions: Expression is a combination of operators and operands.If an arithmetic expression contains
more operators then the execution will be performed according to their priorities
Priority of operators and their clubbing
List of operators with priority wise are shown in table.
operators operations Associativity Precedence
( ) Function call Left to right 1st
[ ] Array expression or Square bracket
 structure operator

++ Increment Right to left 2nd


-- decrement
! Not operator
* pointer operator
& Address operator
sizeof sizeof operator

* multiplication Left to right 3rd


/ Division
% Modulo division

+ Addition Left to Right 4th


- Substraction

<< Left shift Left to Right 5th


>> Right shift

< Less than Left to Right 6th


<= Less than or Equal
> Greater
>= Greater than Equal

== Equality Left to Right 7th


!= Inequality

& Bitwise AND Left to Right 8th

^ Bitwise XOR Left to Right 9th

| Bitwise OR Left to Right 10th

&& Logical AND Left to Right 11th

|| Logicall OR Left to Right 12th

?: Conditional operator Right to Left 13

=,*=,-=,&=,+= Assignment operator Right to left 14


^=,|=,<<=,>>=

, comma operator Left to right 15


Execute the Following expression by using priority and associativity
x = 5 * 4 + 8/2

x = 5 * 4 + 8 / 2

1 2

Here 5*4 is solved first through * and / have the same priorities. the operator * occurs before / because of
associativity (left to right )

decision statements
C language supports the control statements as listed below
1.Simple if statement
2.The if-else statement
3.The nested if-else statement
4.Switch case statement.

1.Simple if-statement
C language uses the keyword to execute a set of command lines or one
command line when the logical condition is true. It has only one option.
Syntax
if(condition) /* no-semicolon */ or if(condition) /* no-semicolon */
statement; {
statements;
}

The statement is executed only when the condition is true.In case the
condition is false the compiler skips the lines within the if block. The condition always enclosed within a
pair of parenthesis. The conditional statement should not be terminated with semi colons.

Write a program to check whether the entered number is less than 10 ? If yes, display the same.

Void main()
{
int v;
clrscr();
printf(“\n enter the number \n”);
scanf(“%d”,&v);
if(v<10)
printf(“\n number entered is less than 10 \n”);
getch();
}
output:
enter the number
9
number entered is less than 10
if-else statement:
The if-else takes care of true as well as false conditions.It has two blocks.one
block is true for “if” and it is executed when the condition is true. The other block is of else it is executed
when the condition is false. The “else” can not be used without if.
syntax
if (condition) /* no semi-colon */ or if(condition)
statement; {
else statements;
statement; }
else
{
statements;
}

Read the values of a,b,c through the keyboard add them and after addition check if it is the range of 100-
200 or not. Print the appropriate message.
void main()
{
int a,b,c,d;
clrscr();
printf(“\n Enter three numbers a,b,c\n”);
scanf(“%d%d%d”,&a,&b,&c);
d = a+b+c;
if(d<=200 && d>=100)
printf(“\n Total is %d which is in between the 100-200 \n”,d);
else
printf(“ \n total is %d which is out of range \n”,d);
getch();
}

output: Enter three numbers a,b,c :


50 52 54
Total is 156 which is in between 100-200
Nested-if-else-statement
In order to execute the else block depending upon the certain conditions we
can add repetitively if statements in else block. This kind of nesting will be unlimited.
syntax
if(condition) if(condition)
{ statement;
statements; ---- if-block else
} if(condition)
else statement;
if(condition) or else
{ statement
statements; --- else block
}
else
{
statements;
}

The above block following rules can be described for applying nested if-else-if statements.
1.Nested if else can be chained with one another.
2.If the condition is false control passes to else block where condition is again checked with the if
statement. This process continues if there is no if statement in the last else block.
3.If one of the if statement satisfies the condition , other nested else…if will not be executed.

Write a program to find largest number out of three numbers.Read the numbers through the keyboard
void main()
{
int x,y,z;
clrscr();
printf(“\n Enter three numbers x,y,z \n”);
scanf(“%d%d%d”,&x,&y,&z);
printf(“\n Largest out of three numbers \n”);
if(x>y)
{
if(x>z)
printf(“\n x = %d”,x);
else
printf(“\n z = %d”,z);
}
else
{
if(z>y)
printf(“\n z= %d\n”,z);
else
printf(“\n y = %d”,y);
}
getch();
}
output
Enter three numbers x,y,z
10 20 30
largest out of three numbers is
z = 30
Write a program to calculate energy bill. Read the starting and ending meter readings. The charges are as
follows.
Number of units consumed Rate in Rs
200-500 3.50
100-200 2.50
<100 1.50
#include<stdio.h>
#include<conio.h>
void main()
{
int initial,final,consumed;
float total;
clrscr();
printf(“\n Enter intial and final Readings \n”);
scanf(“%d%d”,&intial,&final);
consumed = final – initial;

if(consumed >= 200 && consumed <=500)


total = consumed*3.50;
else if(consumed>=100 && consumed<=199)
total = consumed*2.50;
else if(consumed<100)
total = consumed*1.50;
printf(“\n Total bill for %d units is %f”,consumed,total);
getch();
}
output:
Enter intial and final Readings
1800 1500
Total bill for 300 units is 1050

The switch statement


The switch statement is a multiway branch statement. The switch statement evaluates
expression and then looks for its value among the case constants.If the value matches with case constant,
this particular case statement is executed If not ,default is executed.Here switch, case and default are
keywords. Every case statement terminates with’:’. The break statement is used to exit from the current
cases structures.
Syntax
switch(variable or expression)
{
case constant A:
statements;
break;
case constant B:
statements;
break;
----------------------------------
------------------------------------
default: statement;
}
Write a Program to provide multiple functions such as 1.Addition 2.Substraction 3.Multiplication 4.
Division by using switch statements.
void main()
{
int a,b,c,ch;
clrscr();
printf(“\n 1.addition \n2.subtraction \n3. multiplication \n 4.division\n 0.exit\n”);
printf(“\n Enter your choice \n”);
scanf(“%d”,&ch);
if(ch<=4 && ch>0)
{
printf(“\n Enter two numbers \n”);
scanf(“%d%d”,&a,&b);
}
switch(ch)
{
case 1: c= a+b;
printf(“\n Addition: %d”,c);
break;
case 2: c= a-b;
printf(“\n substraction : %d”,c);
break;
case 3: c = a*b;
printf(“\n Multiplication: %d”,c);
break;
case 4: c = a/b;
printf(“\n division:%d”,c);
break;
case 0: printf(“\n Terminated by choice \n”);
break;
default: printf(“\n Invalid choice \n”);
}
getch();
}
output:

1.Addition
2.Substraction
3.Multiplication
4.Division
0.Exit
Enter your choice
4
Enter two numbers: 72 9
Division:8

Loop control Statements


The while loop
syntax
while(condition) /* no semicolon */ or while(condition) /*no semicolon */
statement; {
body of the loop
}
steps of while loops are as follows
1. The test condition us evaluated and if it is true, the body of the loop is executed.
2.On execution of the body, test condition is repetitively checked and if it is true the body is executed.
3.The Process of execution of the body will be continue till the condition becomes false.
4.The control is transferred out of the loop.
Write a Program to print the string “ You have learnt c program “ 9 times using while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int x=1; output: You have learnt C Program(9 times)
clrscr();
while(x<10)
{
printf(“\n You have learnt C Program\n”);
x++;
}
getch();
}

The Do-while loop


The format of do-while loop in c is as follows.
do
{
statements;
}
while(condition);
The difference between the while and do-while loop is in the place where the
condition is to be tested. In the while loops the condition is tested following the while statement
and then body gets executed where as in the do-while, the condition is checked at the end of the loop.
The do-while loop will execute at least one time even if the condition is false initially. The do while loop
executes until the condition becomes false.

Use do-while loop and display a message “ This is a Program of do-while loop”
void main()
{
int i =1;
clrscr();
do
{
printf(“\n This is a Program of do-while loop \n”);
i++;
}
while(i<=5);
getch();
}
output
This is a Program of do-while loop
This is a Program of do-while loop
This is a Program of do-while loop
This is a Program of do-while loop
This is a Program of do-while loop

The for loop:


The for loop allows to execute a set of instructions until a certain condition is satisfied.
Syntax:
for(intitialize counter; test condition; re-evaluation parameter)
{
statements;
}
Example: Write a program to display numbers from 1 to 15 using for loop
Void main()
{
int i;
clrscr();
for(i=1;i<=15;i++)
{
printf(“%d\t”,i);
}
getch();
}

output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation: In the above program counter is initialized with a varaibale I =1.Testing and increase counter
value is done in the for statement itself instead of i++ we can also use I = i+1.

Nested for loops


Write a program to illustrate an example based on nested for loops
void main()
{
int i,j;
clrscr();
for(i=1;i<=3;i++) /* outer loop */
for(j=1;j<=2;j++) /* inner loop */
printf(“\n i * j : %d”,i*j);
getch();
}

output: i * j :1
i*j:2
i*j:2
i*j:4
i*j:3
i*j:6

Write a Program using nested for loops.Print values and messages when any loop ends.

void main()
{
int a,b,c;
clrscr();
for(a=1;a<=2;a++) /* outer loop */
{
for(b=1;b<=2;b++) /* middle loop */
{
for(c=1;c<=2;c++) /* inner loop */
printf( “\n a = %d+b=%d +c = %d: %d”,a,b,c,a+b+c);
printf(“\n Inner loop over \n”);
}
printf(“\n middle loop over \n”);
}
printf(“\n outer loop over \n”);
getch();
}
output:a =1+b=1+c=1:3
a=1+b=1+c=2:4
Inner loop over
a=1+b=2+c=1:4
a=1+b=2+c=2:5
Inner loop over
middle loop over
a =2+b =1+c =1:4
a=2+b =1+c =2:5
Inner loop over

a=2+b=2+c =1:5
a=2+b =2+c=2:6
Inner loop over
middle loop over
a=3+b=1+c=1:5
a=3+b=1+c=2:6
Inner loop over
a=3+b=2+c=1:5
a=3+b=2+c =2:7
Inner loop over
middle loop over
outer loop over

Arrays:
Single Dimensional Arrays:
Introduction:
A variable can hold only a single value. But , there are some applications which require to process a group of
data items, that are of same type.
Ex: To hold the marks of 50 students, we have to declare 50 variables. It is very difficult because, when the no. of
variables increase the program length also increases, which leads to again certain drawbacks.
1. Program takes more time.
2. Less efficiency.
The solution to overcome above drawbacks is “arrays”.
Definition:
An array is a collection of homogeneous elements.
(Or)
An array is a group of related data items , that share a common name.
(Or)
An array is a collection of variables of the same type that are referred to through a common name.
All these elements are stored in consecutive memory locations. The array contains all integers or float or char values.
Ex: Consider a class of 20 students for the variable a. Here the marks obtained by 20 students are different, but all of
them are under a common variable’a’.
int a[20];
Here a is array variable name & 20 is array size.
The computer allocates 20 memory locations for the identifier a as follows:
a[0],a[1],a[2],…………………..a[18],a[19].
Every element in an array is accessed by an index. Here the index starts from 0 & goes through up to 19..
The main purpose of array variables are the ability to store more than one value at a time. All arrays consist of
contiguous memory locations. The lowest address refers to the first element & the highest address refers the last
element.
Properties:
The type of an array is the data type of its elements.
The location of an array is the location of its first element.
The length of an array is the no.of data items in that array.
Arrays are of two types: 1) Single Dimensional Arrays.
2) Two Dimensional Arrays
Single Dimensional Arrays:
The following is the syntax to declare an array.
Syntax: datatype varname[size];
Here ‘datatype’ declares the base type of the array, which is the type of each element in the array. ‘Size’
defines how many elements the array will store. Varname is a valid identifier name.
Ex: double bal[50];
The above statement creates an array variable with the name ‘bal’, which can store 50 double precision floating point
values in it.
Def: If an array contains single subscript, then it is called as “One Dimensional Array” or “Single dimensional
Array”.
Ex: if you want to represent a set of 5 values say 10,15,20,25,30 and so by an array variable ‘marks’, then declare the
variable as follows: marks[0]
int marks[5]; marks[1]
marks[2]
marks[3]
marks[4]

The values to the array variables can be assigned as follows using the syntax.
arrayname[index]=value;
The array ‘marks’ store the values as shown below
marks[0]=10 marks[0] 10
marks[1]=15 marks[0] 15
marks[2]=20 marks[0] 20
marks[3]=25 marks[0] 25
marks[4]=30 marks[0] 30

/* C program to read & display array elements*/


#include<stdio.h>
int main()
{
int i,a[10];
for(i=0;i<10;i++)
{
printf("Enter the elements of a[%d]:\n ",i);
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{

printf("The element of a[%d] is : %d\n",i,a[i]);


}
a[9]=25;
printf("Element of a[9] is %d\n",a[9]);
return 0;
}

Multi-dimensional arrays:
There are so many applications which require the information to be stored in the form of a table. Two
dimensional arrays are used for mainly matrix operations. If the array contains two subscripts, then it is called as
“Two dimensional Arrays”.
C also supports multi dimensional arrays. Two dimensional array is the simplest form of multi dimensional
array.
Syntax:
datatype arrayname[rows][cols];
Ex: int a[3][3]; // A two dimensional integer array a of size 3 & 3
Every dimension is kept inside of it’s own set of brackets. The above array ‘a’ will have the following
elements.
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]
Two dimensional arrays are stored in a row column matrix, where the left index indicates the row & right
index indicates the column. The above array a[3][3] is stored in memory as follows:
Left Index a[0][0] a[0][1] a[0][2]
Determines row a[1][0] a[1][1] a[1][2]
Fig: a[2][0] a[2][1] a[2][2] A two dimensional Array

Right index determines columns


/* C program to read & display 2D array elements*/
#include<stdio.h>
int main()
{
int i,j,a[3][3];
printf("Enter Array elements\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The array elements are\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return 0;
}
Test Case:

You might also like