0% found this document useful (0 votes)
13 views37 pages

Test 1

The document discusses decision-making and branching in C programming, detailing various conditional statements such as 'if', 'if-else', nested 'if-else', and 'else if' ladders. It also covers the 'switch' statement, the 'goto' statement, and looping constructs including 'for', 'while', and 'do-while' loops, along with their syntax and examples. Additionally, it explains jump statements like 'break' and 'continue', and introduces arrays as a collection of similar data types stored in contiguous memory locations.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views37 pages

Test 1

The document discusses decision-making and branching in C programming, detailing various conditional statements such as 'if', 'if-else', nested 'if-else', and 'else if' ladders. It also covers the 'switch' statement, the 'goto' statement, and looping constructs including 'for', 'while', and 'do-while' loops, along with their syntax and examples. Additionally, it explains jump statements like 'break' and 'continue', and introduces arrays as a collection of similar data types stored in contiguous memory locations.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit II

2.1 Decision Making and Branching

Usually C program executes program sequentially. Sometimes, a


program requires checking of certain conditions in program execution. C
provides various key condition statements to check condition and execute
statements according conditional criteria. These statements are called as
'Decision Making Statements' or 'Conditional Statements.

2.1.1. Decision making with If

The if statement is powerful decision- making statement and is used to


control the flow of execution of statement. The if statement may be
implemented in different forms depending on the complexity of condition to
be executed.

The different forms are

 Simple if statement
 If…..else statement
 Nested if..else statement
 Else…..if ladder

2.1.1.1. Simple if statement

It simply checks the condition if it is true it executes set of statements


otherwise
skip out that set of statements.

Syntax

If (test expression)

Statement-block;

Statement-x;

Where the statement–block may be a single statement or a group of


statements.

If the test expression is true, the statement-block will be executed;


otherwise the statement-block will be skipped and the execution will jump
to the statement-x. Note when the condition is true both the statement
block and the statement-x are executed.

Flow chart

No
Test Expression

Yes

Statement Block

Statement X

Example

A=10;
B=5;

if (A>B)

printf(“ A is the largest number”);

If the given condition is satisfied then computer will print the message
“A is the largest number” and if not simply skip this statement.

2.1.1.2. If else

The if…else statement is an extension of the simple if statement.


This type of if contains 2 blocks for true state and false state any one of
them will be selected according to the test condition state.

Syntax

if(condition)
{
True block statements;
}
else
{
False block statements;
}
Statement X;

If the test expression is true, then the true-block statement(s),


immediately following the if statements are executed; otherwise the false-
block statement(s) are executed. In both the case, the control is transferred
subsequently to the statements-x.

Flow Chart
Yes No
Condition

False block
True block statements statements
Example

int x=10, y=20;


if(x > y)
printf(“ x is largest number”, x);
else
printf(“y is largest number “,y);

2.1.1.3.Nested IF ELSE

Nested "if else statements" play an essential role in C programming; It


simply means the use of conditional statements inside another conditional
statement.

Syntax

if(test_expression one)
{
if(test_expression two)
{
Statement - 1;
}
else
{
Statement – 2;
}
else
{
Statement – 3;
}
Statement-X;

If the test expression one is true, then check the test expression two if
it is true then statement-1 is executed; otherwise statement-2 is executed.If
the test expression one is false then statement – 3 is executed. In both the
case, the control is transferred subsequently to the statements-x.

Flow chart
Example

#include<stdio.h>
intmain()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if (number1 >= number2)
{
if (number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else
{
printf("Result: %d > %d", number1, number2);
2.1.1.4. ELSE IF ladder

The else ifladder in C programming is used to test a series of


conditions sequentially.Furthermore, if a condition is tested only when all
previous if conditions in the if-else ladder are false. If any of the conditional
expressions evaluate to be true, the appropriate code block will be executed,
and the entire if-else ladder will be terminated.

Syntax

if (test expression1)
{
// statement(s)
}
else if(test expression2)
{
// statement(s)
}
else if (test expression3)
{
// statement(s)
}
.
.
else
{
// statement(s)
}

Flow chart
Example
#include <stdio.h>

int main()

int number1, number2;

printf("Enter two integers: ");

scanf("%d %d", &number1, &number2);

if(number1 == number2)

printf("Result: %d = %d",number1,number2);

else if (number1 > number2)

printf("Result: %d > %d", number1, number2);

2.1.2. Switch

The C programming has a built-in-multi way decision statement known


as a switch. The switch statement tests the value of a given variable against
a list of case values and when a match is found, a block of statement
associated with that case is executed.

Syntax

switch (expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
……..
Default: default-block;
break;
}
statement-x;

 Where, the expression is an integer expression or character


value1, value2, ….areconstants or expressions and are known as
case labels.
 Each of these values should be unique within a switch statement
Block1, block2 are statement list and may contain zero or more
statements.
 The break statement at the end of each block signal the end of a
particular case and causes an exit from switch statement.
 block1, block2 are statement list and may contain zero or more
statements.
 The default is an optional case, when present it will be executed if
the value of the expression does not match with any of the case
values.
 Statement x is a place where the switch control comes to
continue the program.
Flow chart
Example:

#include<conio.h>

void main()

char choice;

printf(“\n enter choice”);

choice=gerchar();

if(choice>=“a”&& choice<=“z”)

choice=32;

switch(choice)

case ‘c’:

printf(“\n computer science”);


Rules for switch statement

 The Switch expression must be in integral type.


 Case labels must be constant expressions.
 Case labels must be unique. No two labels can have the same
value.
 Case labels must end with semicolon.
 The break statement transfers the control out of the switch
statement. The break statement is optional. That is two or more
case labels may belong to the same statements.
 The default label is optional. If present it will be executes when the
expression does not find a matching case label.
 The default may be placed anywhere but usually placed at the end.
 It is permitted to nest switch statements.

2.1.3. The goto statement

It is an unconditional branching statement. That is it transfers control


from one place another without checking any conditions.

 The goto requires a label in order to identify the place where the
branch is to be made.
 A label is any valid variable name and must be followed by a colon.
 The label is placed immediately before the statement when the
control is to be transferred.
 There are 2 types of jump statements. They are
o Forward jump – the “goto” placed first then the label with
statements placed.
o Backward jump – the label with statements placed first then
the “goto” placed.
Syntax

Forward jump
goto label;
…………
…………
Label:
statement;
Backward jump
label:
statement;
…………
…………
goto label;

The label can be anywhere in the program before or after the gotolabel
statement, a loop will be found and some statements will be executed
repeatedly, such a jump is known as a backward jump. If the label is placed
after the goto label, some statements will be skipped and the jump is known
as a forward jump.

Example

#include <stdio.h>

#include<conio.h>

void main()

intx,y;

clrscr();

x=16;

y=12;

if(x==y)

x++;

else
2.2. Decision Making and Looping:
2.2.1. Introduction

Looping statement used to perform repetitive processes. The loop


consists of two statements. They are

 Body of the loop


 Control statement
The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statements in the loop, a control
structure may classify in to two types.

 Entry-controlled loop or Pre-test loop – It checks the condition before to


start the
loop execution. If the condition is false then it will not start the loop.
Ex: while &

for statement

 Exit-controlled loop or Post-test loop- It checks the condition at the end


of the
loop and therefore the body is executed unconditionally for the first
time. Ex: do-

while statement

A looping process includes the following four steps

 Setting and initialization of a condition variable.


 Test for a specified values of the condition variable for execution of
the loop.
 Execution of the statements in the loop.
 Incrementing or updating the condition variable.
The decision making and looping statements in C are follows

 The While statement


 The Do statement
 The For statement

2.2.2. For

A for loop is a repetition control structure that allows you to efficiently


write a loop that needs to execute a specific number of times.
Syntax

for ( init; condition; increment )


{
statement(s);
}

Where

 The init is executed first, and only once. This allows you to declare and
initialize any loop control variables.
 Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and the
flow of control jumps to the next statement just after the 'for' loop.
 After the body of the 'for' loop executes, the flow of control jumps back
up to the increment statement. This statement allows you to update
any loop control variables. This statement can be left blank, as long as
a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then increment step, and
then again condition). After the condition becomes false, the 'for' loop
terminates.

Flow chart
Example

#include <stdio.h>

int main ()

int a;

for( a = 10; a < 20; a = a + 1 )

printf("value of a: %d\n", a);

2.2.3. Nested for loops

Nesting of loops is the feature in C that allows the looping of


statements inside another loop. Any number of loops can be defined inside
another loop, i.e., there is no restriction for defining any number of loops.
The nesting level can be defined at n times.
Syntax

for ( init1; condition1; increment ) //Outer_loop


{
for ( init2; condition2; increment ) //Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

Flow chart

Example

#include <stdio.h>

int main()

int n;

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

for(int i=1;i<=n;i++) // outer loop


{ for(int j=1;j<=10;j++) // inner loop
2.2.4. While

It is an entry controlled loop so that it checks the condition first if it is


true then only it enters into the loop and execute the body of the loop
otherwise it simply exit from the loop.

Syntax

while (test condition)


{
Body of the Loop;
}
statement 2;

 The while is an entry-controlled loop statement. The test-condition is


true, then the body of the loop will be executed, otherwise a
statement2 is executed.
 The process of repeated execution continuous until the test-condition
finally becomes false and the control is transferred out of the loop. The
body of the loop may have one or more statement.
 The braces are need only if the body contains two or more statements.
Flow chart
Example

#include<stdio.h>

#include<conio.h>

void main()

int digit=1;

clrscr();

while(digit<=10)

2.2.5. Do-while statements

The do-while is an exit controlled loop.

 The program proceeds to evaluate the body of the loop first.


 At the end of the loop, the test condition in while is evaluate.
 If the test condition is true, the program continues to evaluate the
body of the loop once again.
 The process continues as long as the condition is true.
Syntax

Do
{
Body of the loop;
}
while(condition);

Flow chart

Example

#include<stdio.h>

#include<conio.h>

void main()

{int count=0;

char c;

do

{c=getchar();
2.2.6. Jumps in loops

Jump statements alter the normal execution path of a program. Jump


statements are used when we want to skip some statements inside loop or
terminate the loop immediately when some condition becomes true. C
programming supports the following jump statements.

Jump Description
Statement
continue The continue statement is used for skipping part of loop's body.
break The break statement is used to stop the execution of loop and switch
case statements.

2.2.6.1. Break
In any loop “break” is used to jump out of loop skipping the code below
it without caring about the test condition. It interrupts the flow of
the program by breaking the loop and continues the execution of code which
is outside the loop.
Do
{
while (test_condition)
{
statement1;
statement1; if (condition)
if (condition ) break;
break;
statement2;
statement2;
}while
}
(test_condition);

for (int-exp; test-exp; update-exp)


{
statement1;
if (condition)
break;
statement2;
}
In all the above cases the compiler skipped out the loop and bringing
the control outside of the loop whenever the “if” statement is true. That is it
brings the control to outside of the loop without completing the remaining
iterations.

2.2.6.2.Continue
The continue statement in C programming works somewhat like
the break statement. Instead of forcing termination, it forces the next
iteration of the loop to take place, skipping any code in between.

Syntax

continue;

Do
while (test_condition)
{
{
statement1;
statement1;
if (condition)
if (condition )
continue;
continue;
statement2;
statement2;
}while
}
(test_condition);
for (int-exp; test-exp; update-exp)
{
statement1;
if (condition)
continue;
statement2;
}
In all the above cases the compiler immediately continue the next
iteration whenever the “if” statement is true. That is it brings the control to
starting of the loop without executing the statement2.
Unit III

3.1. Arrays:

An array is defined as the collection of similar type of data items stored


at contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection of
derived data types, such as pointers, structure, etc. All arrays consist of
contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element

Arrays are broadly classified into three types. They are as follows

 One – dimensional arrays


 Two – dimensional arrays
 Multi – dimensional arrays

2.3.1. One-dimensional

A list of items can be stored in one variable name using only one
subscript such a variable is called as subscripted variable or one dimensional
array.

Declaration of one dimensional array


It gives the name of the array, number of values can be stored in array
and the type of the data can be stored in the array.

Syntax

datatype array-name [size];

where

 datatype – It specifies the type of data to be stored in the array.


 array-name – It specifies the name given to the array.
 size – It specifies the number of values can be stored in the array.

Example1

int value[20];
 It declares the value to be an array of integers containing 20 integer
elements.
Example2

char address[50];

 It declares the address as a character array variable that can hold a


maximum of 50 characters.
 The last element position is always occupied by a null character like”\
0”, so the size should be chosen one more than the actual string being
stored.
Initialization of one-dimensional arrays

An array can be initialized in two ways, which are as follows −

 Compile time initialization

 Runtime initialization

Compile time initialization


Syntax

type array-name[size]={list of values}

The values in the list are separated by commas.

Example

int number[3]={0,0,0};

The size can be omitted. In such case the compiler allocates enough
space for all initialized elements

Example

int counter[]={1,1,1,1}

Example program
#include<stdio.h>

int main ( ){

int a[5] = {10,20,30,40,50};

int i;

printf ("elements of the array are");

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

Output

Elements of the array are

10 0 30 40 50
The output of compile time initialised program will not change during
different runs of the program.

Run time initialization

An array can be explicitly initialized at run time.

Example program

#include<stdio.h>

main ( )

int a[5],i;

printf ("enter 5 elements");

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

scanf("%d", &a[i]);

printf("elements of the array are");

Output

enter 5 elements 10 20 30 40 50

elements of the array are : 10 20 30 40 50


The output of run time initialized program will change for different runs
because; user is given a chance of accepting different values during
execution.

2.3.2. Two dimensional arrays

The two-dimensional array can be defined as an array of arrays. The


2D array is organized as matrices which can be represented as the collection
of rows and columns.
Declaration of two dimensional arrays

Syntax

Datatype array-name[row_size][colmn_size];

Where

 Data type gives the type of data to be stored.


 array name specifies the name of the array variable.
 row size indicates the size of the row of the matrix.
 column size indicates the column size of the matrix.
The data type is common for all elements of the array.A two-
dimensional array a, which contains three rows and four columns can be
shown as follows

Initialization of two dimensional arrays

Multidimensional arrays may be initialized by specifying bracketed


values for each row.

Example

Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {

{0, 1, 2, 3},// initializers for row indexed by 0

{4, 5, 6, 7},// initializers for row indexed by 1

{8, 9, 10, 11}// initializers for row indexed by 2


};

The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example

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

Accessing Two-Dimensional Array Elements

An element in a two-dimensional array is accessed by using the


subscripts, i.e., row index and column index of the array.

For example

intval = a[2][3];
The above statement will take the 4th element from the 3rd row of the
array.

Example program
#include <stdio.h>

int main ()

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

int i, j;

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

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

printf("a[%d][%d] = %d\n", i,j, a[i][j] );

2.3.3. Multidimensional arrays

In C programming we can define multidimensional arrays in simple


words as array of arrays. Data in multidimensional arrays are stored in
tabular form in row major order.

Syntax

data_typearray_name[size1][size2]....[sizeN];

Where

 data_type: Type of data to be stored in the array. Here data_type is


valid C data type
 array_name: Name of the array
 size1, size2,... ,sizeN: Sizes of the dimensions
Examples:

 Two dimensional array: inttwo_d[10][20];


 Three dimensional array: intthree_d[10][20][30];

Size of multidimensional arrays

Total number of elements that can be stored in a multidimensional


array can be calculated by multiplying the size of all the dimensions.
For example:

 int x[10][20] can store total (10*20) = 200 elements.


 int x[5][10][20] can store total (5*10*20) = 1000 elements.

You might also like