Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views45 pages

Module - 2 PSP Notes...

The document provides an overview of managing input and output operations in C programming, detailing functions for reading and writing characters, formatted input and output, and decision-making statements. It explains the use of functions like getchar, putchar, scanf, and printf, along with their syntax and examples. Additionally, it covers decision-making constructs such as if statements and nested if-else statements, illustrating their usage with examples.

Uploaded by

shobhabk878
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)
10 views45 pages

Module - 2 PSP Notes...

The document provides an overview of managing input and output operations in C programming, detailing functions for reading and writing characters, formatted input and output, and decision-making statements. It explains the use of functions like getchar, putchar, scanf, and printf, along with their syntax and examples. Additionally, it covers decision-making constructs such as if statements and nested if-else statements, illustrating their usage with examples.

Uploaded by

shobhabk878
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/ 45

Module-2 PSP NOTES

MANAGING INPUT AND OUTPUT OPERATIONS


V Swathi,Asst.Prof.,Dept of CSE

1. INTRODUCTION
⮚ Reading, processing and writing of data are three essential functions
of a computer program.
⮚ There are two methods. The first method is to assign the values and
the second method is to use input function scanf to read data and output
function printf to write data.
⮚ Ex: #include<stdio.h> Includes function calls such as printf( ) and
scanf( ) into the source code when compiled.

2. READING A CHARACTER

⮚ The simplest way of all input/output operations is reading a character


from the ‘standard input’ unit (usually keyboard) and writing it to the
‘standard output’ (usually the screen).
⮚ Reading a single character can be done by using the function getchar
and it does not have any parameter.
Syntax:variable_name=getchar();

Where, variable_name is valid and has been declared in char type.

Example:charname;
name=getchar();
⮚ The getchar function can also be used to read the
characters successively until the return key is pressed.
⮚ The character function are contained in the file type ctype.h
and therefore the preprocessor directive #include<ctype.h> is
included.
⮚ And the functions of ctype.h returns 1 if (TRUE) and 0 if (FALSE).

Function Test
isalnum(c) Is c alphanumeric character?
isalpha(c) Is c alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
Module-2 PSP NOTES

isupper(c) Is c a upper case letter?


isspace(c) Is c a white case character?
ispunct(c) Is c a punctuation mark?
isprint(c) Is c a printable character?

Example Program:
#include<stdio.h>
#include<ctype.h>
void main( )
{

char key;
printf(“Enter any key\n”);
key=getchar( );

if(isalpha (key))
printf(“The entered key is a letter\n”);
else if(isdigit(key))
printf(“The entered key is a digit\n”);
else

printf(“The entered key is not


alphanumeric\n”)
Module-2 PSP NOTES

OUTPUT:
⮚ Enter any
key A
The entered key is a letter
⮚ Enter any
key 7
The entered key is a digit
⮚ Enter any key
$
The entered key is not alphanumeric

3. WRITING A CHARACTER

⮚ Writing a single character can be done by using the function putchar.


Syntax:putchar(variable_name);

Where, variable_name is valid and has been declared in char type.

Example:name=’y’;
putchar(name);

Will displaythecharacteryonthescreen

⮚ The characters entered can be converted into reverse i.e., from


upper to lower case and vice versa.
⮚ The functions used to convert are toupper, tolower.

Example Program:
#include<stdio.h>
#include<ctype.h>
void main( )
{
char alphabet;
printf(“Enter any alphabet\n”);
alphabet=getchar( );
if(islower(alphabet))
Module-2 PSP NOTES
putchar(toupper(alphabet));

else

putchar(tolower(alphabet));
}

OUTPUT:
⮚ Enter any alphabet ⮚ Enter any
A alphabet
⮚ A a

⮚ A
Module-2 PSP NOTES

4. FORMATTED INPUT
⮚ Formatted input refers to an input data that has been arranged
in particular format.
⮚ Ex: 152 Rajesh
⮚ In the above example the first part contains integer and the
second part contains characters. This is possible with the help of scanf
function.
Syntax:scanf(“controlstring”,arg1,arg2,…..,argn);

⮚ entere The control string specifies the field form in wh ich data should be
locatio d and the arguments arg1, arg2,…..,argn specifies the address of the
⮚ The widthn where the data is stored.
of the integer number can be specified using %wd.

Example-2:
–scanf(“%2d%2d”,&a, &b);
%2dtwodigitinteger
%2dtwo
digitinteger4567
25 a=45
⮚ The input field may be skipped
b=67 using * in the place of field width.

Example-3:
–scanf(“%2d%*d%2d”,&a,&b);
%2dtwodigitinteger
%*dskipthisinteger4
5 2563
a=45
25isskipped
b=63

⮚ The scanf function can read single character or more than one
character using %c or %s.
Module-2 PSP NOTES

Rules for scanf:


⮚ Each variable to be read must have a specification
⮚ For each field specification, there must be a address of proper type.
⮚ Never end the format string with whitespace. It is a fatal error.
⮚ The scanf will read until:
● A whitespace character is found in numeric specification.
● The maximum number of characters have been read
● An error is detected
● The end of file is reached
⮚ Any non-whitespace character used in the format string must have
a matching character in the user input.

❖ The below table shows the scanf format codes commonly used.

Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[ ] Read a string of word
The l can be used as a prefix for long integer. Ex: %ld

5. FORMATTED OUTPUT
⮚ The printf function is used for printing the captions and results.

Syntax:printf(“controlstring”,arg1,arg2,…..,argn);

⮚ Control string contains three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b.
Module-2 PSP NOTES

⮚ The printf can contain flags (0 + - )


0 🡪 fill in extra positions with 0’s instead of spaces
a=7777
printf(“a = %07d”, a);
Widthof7memoryspaceisallocatedandpadded
%07d withleadingzeroes
0 0 0 7 7 7 7

- 🡪 Left justify text instead of right justify text a=7777;


printf(“a = % -7d”, a);
% -7d
Widthof7memoryspaceisallocatedandprintedfr
7 7 7 7 omleftside(leftjustify)

+ 🡪 Print sign of number (whether positive or negative)


⮚ Example with format specifier %d:
a=10, b=77;
printf(“%d %d”, a , b);

Output:

1077

⮚ Example with format specifier %f:


x=10.776;
printf(“%6.3f %”, x );

%6.3f 6.3fmeanstotally6locationsareallocatedoutofwhich
3isfornumberofdecimal places.
1 0 . 7 7 6
Module-2 PSP NOTES

⮚ Example with \n and \t:


a=10, b=77, c=88;
printf(“a=%d\n b=%d\tc=%d”, a , b, c);
Output:

a=10

b=77

c=88

⮚ Example with size value:


a=10, b=7777, c=88;
printf(“a=%4d\n b=%7d”, a , b);
%4d
Width of 4 memory space is allocated and
1 0 printed from right side

%7d Width of 7 memory space is allocated and printed


from right side (right justify)
7 7 7 7

❖ The below table shows the scanf format codes commonly used.
Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in exponent form
%f Print a floating point value without exponent
%g Print a floating point value with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal integer
%x Print a hexadecimal integer
%[ ] Print a string of word

The l can be used as a prefix for long integer. Ex: %ld


Module-2 PSP NOTES

⮚ General syntax of field-width/size for different data types:


• %wd 🡪 Example: %6d
• %w.pf 🡪 Example %6.2f
• %w.ps 🡪 Example %10.4s
– w means total field size/width
– P means precision (tells how many decimal places to be printed in case
of float) and
– How many characters to be printed in case of strings

Examples:a=9876;
9 8 7 6
printf(“%d”,a);
printf(“%6d”,a); 9 8 7 6

printf(“%-6d”,a);
9 8 7 6
printf(“%3d”,a);
9 8 7 6

NOTE: String input/output function: gets( ) and puts( )


⮚ gets and puts are line oriented input output functions available in the
<stdio.h> header file.
⮚ gets( ): Alternative method to read strings is gets( ) (read it as get
string) function which is an unformatted string input function. Advantage of
gets( ) is it can read multi-word strings.
⮚ Example: char name[10];
gets(name);
Say input is:
N E W Y O R K

The complete string “NEWYORK” is read by gets().

⮚ puts( ): This function can be used to display entire string on monitor


screen without the help of %s specifier.
Example: char name[ ] = “Bengaluru”
puts(name);
puts( ) will display the string value stored in parameter passed to it on monitor. In this
case it is—Bengaluru.
Module2 CProgrammingforProblemSolving

MODULE 2

CHAPTER 2: Decision Making and Branching

1. INTRODUCTION
⮚ C language possesses such decision making capabilities by supporting
the following statements:
1. If statement
2. Switch statement
3. Conditional operator statement
4. goto statement
Expression True
⮚ These statements are popularly known as decision making statements. Also
known as control statements.
False
2. DECISION MAKING (Two-Way Selection Statements)

⮚ The basic decision statement in the computer is the two way selection.
⮚ The decision is described to the computer as conditional statement that can
be answered TRUE or FALSE.
⮚ If the answer is TRUE, one or more action statements are executed.
⮚ If answer is FALSE, the different action or set of actions are executed.
⮚ Regardless of which set of actions is executed, the program continues with
next statement.
⮚ C language provides following two-way selection statements:

1. if statement
2. if – else statement
3. Nested if else statement
4. Cascaded if else (also called else-if ladder)

1. if statement: The general form of simple if statements is shown below.


if(Expression)
{
Statement1;
}
Statement2;
Module2 CProgrammingforProblemSolving

⮚ The Expression is evaluated first, if the value of Expression is true (or non zero)
then Statement1 will be executed; otherwise if it is false (or zero), then Statement1 will
be skipped and the execution will jump to the Statement2.
⮚ Remember when condition is true, both the Statement1 and Statement2 are
executed in sequence. This is illustrated in Figure1.
Note: Statement1 can be single statement or group of statements.

Statement1

Statement2

Figure 1: Flow chart of if statement


Example:
#include<stdio.h>
void main( )
{
int a=20, b=11;
if (a >b) False True
Expression
{
printf(“a is bigger and value is= %d\n”, a);
}
printf(“job over\n”);
}

Output: a is bigger and value is=20


job over
Module2 CProgrammingforProblemSolving

2. if..else statement: The if..else statement is an extension of simple if


statement. General syntax:
if(Expression)
{
(true-
block;)State
ment1;
}
else
{
(false-
block;)State
ment2;

⮚ If the Expression is true (or non-zero) then Statement1 will be


executed; otherwise if it is false (or zero), then Statement2 will be executed.
⮚ In this case either true block or false block will be executed, but not both.
⮚ This is illustrated in Figure 2. In both the cases, the control is
transferred subsequently to the Statement3.

Figure 2: Flow chart of if-else statement

Statement2 Statement1

Statement3
Module2 CProgrammingforProblemSolving

Example:
void main( )
{
int a=10, b=11;
if (a >b)
{
printf(“a is bigger and value is= %d”, a);
}
else
{
printf(“b is bigger and value is= %d”, b);
}
}
Module2 CProgrammingforProblemSolving

Output: b is bigger and value is=11

3. Nested if .. else statement: When a series of decisions are involved, we have to


use more than one if..else statement in nested form as shown below in the general
syntax.

if(Expression1)
{
if(Expression2)
{
Statement1;
}
else
{
Statement2;
}
}
elseif(Expression3)
{
Statement3;
}
else
{
Statement4;
}

⮚ If Expression1 is true, check for Expression2, if it is also true then Statement1


is executed.
⮚ If Expression1 is true, check for Expression2, if it is false then Statement2
is executed.
⮚ If Expression1 is false, then Statement3 is executed.
⮚ Once we start nesting if .. else statements, we may encounter a classic
problem known as dangling else.
⮚ This problem is created when no matching else for every if.
⮚ C solution to this problem is a simple rule “always pair an else to most recent
unpaired if in the current block”.
⮚ Solution to the dangling else problem, a compound statement.
⮚ In compound statement, we simply enclose true actions in braces to make the
Module2 CProgrammingforProblemSolving
second if a compound statement.

Figure 3: Flow chart of Nested if-else statement


Example:
void main( )
{
int A=20,B=15,C=3;
if ( A>B)
{
if (A>C)
{
printf(“largest=%d”, A);
}
Module2 CProgrammingforProblemSolving
else
{
printf(“largest=%d”,C);
}
else
{

if(B>C)
{
printf(“largest=%d”, B);
}
else
{
printf(“largest=%d”, C);
}
}
}
Output: largest=20
4. else-if ladder or cascaded if else: There is another way of putting ifs together
when multipath decisions are involved. A multi path decision is a chain of ifs in which
the statement associated with each else is an if. It takes the following form.

if(Expression1)
{
Statement1;
}
elseif(Expression2)
{
Statement2;
}
elseif(Expression3)
{
Statement3;
}
else
{
Statement4;
}
NextStatement;
Module2 CProgrammingforProblemSolving

⮚ This construct is known as the else if ladder.


⮚ The conditions are evaluated from the top (of the ladder), downwards. As soon as
true condition is found, the statement associated with it is executed and control
transferred to the Next statement skipping the rest of the ladder.
⮚ When all conditions are false then the final else containing the default Statement4
will be executed.

Figure 4: Flow chart of else if ladder statement


Example:
void main( )
{
int choice, a=100, b=5;
printf(“enter 1 for addition 2 for subtraction 3 for multiply 4 for modulus\n”);
scanf(“%d”, &choice);

if(choice==1)
printf(“sum=%d”, a+b);
else if(choice==2)
Module2 CProgrammingforProblemSolving

printf(“difference=%d”, a-b);

else if(choice==3)
printf(“product=%d”, a*b);

else if (choice==4)
printf(“rem=%d”, a%b);
else
printf(“Invalid option”);
}

3. SWITCH STATEMENT

⮚ C language provides a multi-way decision statement so that complex else-if


statements can be easily replaced by it. C language’s multi-way decision statement is
called switch.
General syntax of switch statement is as follows:
switch(choice)
{
caselabel1:block1;
break;ca
selabel2:block2;
break;ca
s elabel3:block-3;
break;default
:default-block;
break;
}

⮚ Here switch, case, break and default are built-in C language words.
⮚ If the choice matches to label1 then block1 will be executed else if it evaluates
to label2 then block2 will be executed and so on.
⮚ If choice does not matches with any case labels, then default block will
be executed.
Module2 CProgrammingforProblemSolving

Figure 5: Flow chart of switch case statement

⮚ The choice is an integer expression or characters.


⮚ The label1, label2, label3,…. are constants or constant expression evaluate to
integer constants.
⮚ Each of these case labels should be unique within the switch statement. block1,
block2, block3, … are statement lists and may contain zero or more statements.
⮚ There is no need to put braces around these blocks. Note that case labels
end with colon(:).
⮚ Break statement at the end of each block signals end of a particular case
and causes an exit from switch statement.
⮚ The default is an optional case when present, it will execute if the value of the
choice does not match with any of the case labels.
Example:
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int ch,a,b,res;
float div;
Module2 CProgrammingforProblemSolving

printf(“Enter two numbers:”);


scanf(“%d%d”,&a,&b);
printf(“1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n 5.Remainder”);
printf(“Enter your choice:\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: res=a+b;
printf(“Result=%d\n”,res);
break;
case 2: res=a-b;
printf(“Result=%d\n”,res);
break;
case 3: res=a*b;
printf(“Result=%d\n”,res);
break;

case 4: div=(float)a/b;
printf(“Result=%f\n”,div);
break;
case 5: res=a%b;
printf(“Result=%d\n”,res);
break;
default: printf(“Wrong choice!!\n”);
exit(0);
}
}
In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so
on.

4. Ternary operator or conditional operator (?:)


⮚ C Language has an unusual operator, useful for making two way decisions.
⮚ This operator is combination of two tokens ? and : and takes three operands.
⮚ This operator is known as ternary operator or conditional operator.
Module2 CProgrammingforProblemSolving

Syntax:
Expression1?Expression2:Expression3

Where,
Expression1 is Condition
Expression2 is Statement Followed if Condition is True
Expression3 is Statement Followed if Condition is False

Meaning of Syntax:
1. Expression1 is nothing but Boolean Condition i.e. it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is executed
5. Expression1 is said to be FALSE if its result is ZERO
Example: Check whether Number is Odd or Even

#include<stdio.h>

void main( )

{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
flag = ((num%2==0)?1:0);
if(flag==0)
printf("\nEven");
else
printf("\nOdd");
}

5. Goto statement
⮚ goto is an unconditional branching statement. The syntax of goto is as follows:
Module2 CProgrammingforProblemSolving

gotolabel;st
atement1;s
t
atement2;l
a bel:
Module2 CProgrammingforProblemSolving

⮚ A label is a valid variable name.


⮚ Label need not be declared and must be followed by colon.
⮚ Label should be used along with a statement to which control is transferred.
⮚ Label can be anywhere in the program either before or after the goto label.
⮚ Here control jumps to label skipping statement1 and statement2 without
verifying any condition that is the reason we call it unconditional jumping
statement.
Example:
void main( )
{
int a=5, b=7;
goto end;
a=a+1;
b=b+1;
end: printf(“a=%d b=%d”, a,b);

}
Module2 CProgrammingforProblemSolving

MODULE 2

CHAPTER 3: Decision Making and Looping

1. INTRODUCTION

Definition of Loop: It is a programming structure used to repeatedly carry out a


particular instruction/statement until a condition is true. Each single repetition of the
loop is known as an iteration of the loop.

Three important components of any loop are:


1. Initialization (example: ctr=1, i=0 etc)
2. Test Condition (example: ctr<=500, i != 0 etc)
3. Updating loop control values (example: ctr=ctr+1, i =i-1)

Pre-test and Post-test loops


⮚ Loops can be classified into two types based on the placement of test-condition.
⮚ If the test-condition is given in the beginning such loops are called pre-test
loops (also known as entry-controlled loops).
⮚ Otherwise if test condition is given at the end of the loop such loops are termed
as post-test loops (or exit controlled loops).
Module2 CProgrammingforProblemSolving

Note Figure 1:
1. Here condition is at the beginning of loop. That is why it is called pre-test loop
2. It is also called as entry controlled loop because condition is tested
before entering into the loop.
3. while is a keyword which can be used here.

Note Figure 2:
1. Here condition is at the end of the loop. That is why it is called post-test loop.
2. It is also called as exit controlled loop because condition is tested after body
of the loop is executed at least once.
3. do and while are keywords which can be used here.

2. LOOPS IN C:
C language provides 3 looping structures namely:
1. while loop
2. do….while loop
3. for loop

The loops may be classified into two general types. Namely:


1. Counter-controlled loop
2. Sentinel-controlled loop

⮚ When we know in advance exactly how many times the loop will be executed, we
use a counter-controlled loop. A counter controlled loop is sometimes called definite
repetition loop.
⮚ In a sentinel-controlled loop, a special value called a sentinel value is used to
change the loop control expression from true to false. A sentinel-controlled loop is often
called indefinite repetition loop.
Module2 CProgrammingforProblemSolving

i. while loop:
⮚ It is a pre-test loop (also known as entry controlled loop). This loop has following
syntax:

while(condition)
{
statement-block;
}

⮚ In the syntax given above ‘while’ is a key word and condition is at beginning of the
loop.
⮚ If the test condition is true the body of while loop will be executed.
⮚ After execution of the body, the test condition is once again evaluated and if it
is true, the body is executed once again.
⮚ This process is repeated until condition finally becomes false and control
comes out of the body of the loop.
Flowchart:
Module2 CProgrammingforProblemSolving

⮚ Here is an example program using while loop for finding sum of 1 to 10.
Example: Before loop

void main() execution:N=10,sum=


{ 0,i=1
N=10;
i=1;
sum=0; First

Round:N=10,sum
while (i<=N)
{ =1,i=2
sum=sum+i;
i=i+1;
}
printf(“%d”, sum);
}

ii. do…. while loop: It is a post-test loop (also called exit controlled loop) it has
two keywords do and while. The General syntax:

Do
{
statement-block;
}while(condition);

⮚ In this loop the body of the loop is executed first and then test condition
is evaluated.
⮚ If the condition is true, then the body of loop will be executed once again.
This process continues as long as condition is true.
⮚ When condition becomes false, the loop will be terminated and control comes
out of the loop.
Flowchart:
Module2 CProgrammingforProblemSolving

Example: The example already discussed with while loop to compute sum of 1 to 10
numbers is given here with do …while loop:
void main( )
{ Before loop execution:N=10,sum= 0,i=1
N=10; FirstRound:
i=1;
sum=0; N=10,sum=1,i=2
do SecondRound:
{
sum=sum+i;
i=i+1;
}
while (i<=N);
printf(“%d”, sum);
}

iii. for loop:


⮚ It is another pre-test loop (also called entry controlled loop) that provides
concise loop control structure. It has one keyword for.
⮚ One important aspect of for loop is all the three components of a loop (viz.
initializing, testing condition and updating (increment/decrement)) is given in the head
of for loop.
Module2 CProgrammingforProblemSolving
General syntax:
for(initialization;test-condition;updation)
{
Body-ofloop;
}

The execution of for statement is as follows.


1. In this loop first initialization of control variable is done first, using assignments
such as i=1, count=0. The variable i count are called loop control variable.
2. The value of control variable is tested using the test condition. The test condition
is evaluated. If the condition is true, the body of the loop is executed; otherwise
loop will be terminated.
3. When the body of the loop is executed, the control transferred back to the for
statement to update the loop variable. And then condition is checked once again.
If condition is true once again body will be executed once again. This process
continues till the value of the control variable fails to satisfy the test condition.

Flowchart:

Example: Same program to find some of 1 to 10 numbers can be written using for loop
as follows:

void main( )
{
int i, N=10, sum=0;
Module2 CProgrammingforProblemSolving

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


{
sum=sum+i;
}
printf(“Total =%d”, sum);
}

Note: In for loops whether both i++ or ++i operations will be treated as pre-increment
only.

Nested for loops:


⮚ In some programming situations within one for loop we have to write another
for loop. Such embedded for loops are called nested for loops.
⮚ Following diagram depicts a nested for loop flowchart.

Example:
Here is an example program segment with sample outputs that illustrates the working
of a nested for loop:
Module2 CProgrammingforProblemSolving

for(rows=1; rows<=4; rows++)


for(cols=1;cols<=3; cols++)
{

printf(“%d %d”, rows, cols);


}

Working:
1. Initiallyvalueofrows=1and1<=4istruesocontrolentersto
innerloop
2. Ininnerloopcols=1and1<=3isalsotruesobodyoftheloop
(i.e.printfgets executed)
Followingaretheoutputsobtainedineveryrepetitionofinner/outerforloops:

Output: Output: Output: Output:

1st round: 2nd


round: 3rd
round: 4th
round:
rows=1,1,1 rows=2,2,2 rows=3,3,3 rows=4,4,4
cols=1,2,3 cols=1,2,3 cols=1,2,3 cols=1,2,3

Initializing, Test condition and Updating: Three Components of a Loop


⮚ Normally all loops should have three components:
1. Initialization (example: i=0; j=1 etc)
2. Test condition (example: ctr<=10, i<=20 etc)
3. Updating (example: ctr=ctr+1, i=i+2 etc)

⮚ If any of these three components are missing program behaves indifferently. For
instance if updating statement is missing loop goes into infinite mode as shown in
following example:

void main( )
{
int ctr=1, N=10;
while(ctr<=N)
Module2 CProgrammingforProblemSolving

{
printf(“Hello World\n”);
printf(“Hi Galaxy\n”);
}
}

Output:itprints,
Hello World

Hello Galaxy
Infinite number of times as ctr value remains 1 forever as

⮚ Let us go through same example with initialization statement missing:


Example:
void main( )
{
int ctr, N=10;
while(ctr<=N)
{
printf(“Hello World\n”);
printf(“Hi Galaxy\n”);
ctr=ctr+1;
}

Output: Loop will not at all get executed as


initial value of ctr is unknown!
So program prints nothing.
Module2 CProgrammingforProblemSolving

3. JUMPS IN LOOPS
Break and continue: break and continue are unconditional control construct.
i. break
⮚ This statement is useful to terminate a loop and transfer control out of
loop under special situations.
⮚ break statement works with while, do….while, for and switch statements.
⮚ Following program syntax diagrammatically represents the working
mechanism of break statement.

Note: If break statement is used in the nested loops, the control will come out from the
inner loop; still the outer loop is active.

Note:
Working of break statement:
Whencondition2istruetheloopgetsterminatedandcontrolistransferredtostatemen
t5(whichisoutsidetheloop). Here we can observe that even though

Example program for break statement:

void main( )

{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
Module2 CProgrammingforProblemSolving

break;
printf(“%d ”,i);
}
Output: 1 2

ii. Continue
⮚ Statement is helpful to skip particular set of statements in loop body and
to continue execution from the beginning of loop.
⮚ Following syntax clearly depicts how control shifts to beginning of a loop
on finding continue statement.

Note:
Working of continue statement:
Whencondition2istruecontinuestatementisexecutedwhichresultsintransferofcontroltobeginningof
while loopskippingstatement4andstatement5.

Example program for continue statement:


void main()
{
int i;
for(i=1;i<=5;i++)
Module2 CProgrammingforProblemSolving

{
if(i==3)
continue;
printf(“%d ”,i);
}
Output: 1 2 4 5

Computation of Binomial co-efficient


Problem: Binomial coefficients are used in the study of binomial distributions and
readability of multicomponent redundant systems. It is given by:
𝑚
B(m,x)=( )
𝑋

𝑚!
𝑋!( ,m>=x
𝑚−𝑋)!
Module2 CProgrammingforProblemSolving

A table of binomial coefficients is required to determine the binomial coefficient for any
set of m and x.

Problem Analysis: The binomial coefficient can be recursively calculated as follows:


B(m,0) = 1

B(m, x) = B(m, x-1) [𝑚−𝑋+1] , X = 1, 2, 3, …., m


𝑋

Further,
B(0, 0) = 1
That is, the binomial coefficient is one when either x is zero or m is zero. The program
below points the table of binomial coefficients for m=10. The program employs one do
loop and one while loop.

Program:

#include<stdio.h>
#define MAX 10
main( )
{
int m, x, binom;

printf(“ m x”);
for(m = 0; m <=10; ++m)
printf(%4d”, m);
printf(“\n \n”);
m = 0;
do
{
printf(“%2d”, m);
x = 0;
binom = 1;
while(x<=m)
{
if(m == 0 || x ==0)
printf(“%4d”, binom);
else
Module2 CProgrammingforProblemSolving
{

binom = binom * (m-x + 1) / x;


printf(“%4d”, binom);
}
x = x + 1;
}
printf(“\n”);
m=m+1;
}
while (m<= MAX);
printf(“ \n”);
}

OUTPUT :

mx 0 1 2 3 4 5 6 7 8 9 10
--------------- -------------------------------------------------------------------------------------------
0 1
1 1 1
2 1 2 1
3 1 3 3 1
4 1 4 6 4 1
5 1 5 10 10 5 1
6 1 6 15 20 15 6 1

OUTPUT:

- --
Module2 CProgrammingforProblemSolving

7 1 7 21 35 35 21 7 1
8 1 8 28 56 70 56 28 8 1
9 1 9 36 84 126 126 84 36 9 1
10 1 10 45 120 210 252 210 120 45 10 1
------------------------------------------------------------------------------------------------------------

Pascal’s Triangle

⮚ One of the most interesting Number Patterns is Pascal's Triangle (named after
Blaise Pascal, a famous French Mathematician and Philosopher).
⮚ To build the triangle, start with "1" at the top, then continue placing
numbers below it in a triangular pattern.
⮚ Each number is the numbers directly above it added together.

#include
<stdio.h> long
factorial(int); int
main()
{
int i, n, c;

printf("Enter the number of rows you wish to see in pascal triangle\n");


scanf("%d",&n);

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


Module2 CProgrammingforProblemSolving

{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");

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


printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));

printf("\n");
}

return 0;
}

long factorial(int n)
{
int c;
long result = 1;

for (c = 1; c <= n; c++) result = result*c;

return result;
}
QUADRATIC EQUATION
⮚ The Quadratic Formula uses the "a", "b", and "c" from "ax2 + bx + c", where "a",
"b", and "c" are just numbers; they are the "numerical coefficients" of the quadratic
equation they've given you to solve.
Module2 CProgrammingforProblemSolving

#include<stdio.h>
#include<math.h
> void main( )
{
float a, b, c, root1, root2, rpart, ipart, disc;
printf("Enter the 3 coefficients:\n”);
scanf(%f%f%f", &a, &b, &c);
if((a*b*c) = = 0)

{
printf("Roots cannot be Determined:\n");
exit(0);
}

disc=(b*b) - (4*a*c);
if(disc == 0)
{
printf("Roots are equal\n");
root1= -b / (2*a);
root2=root1;
printf ("root1 = %f \n", root1);
printf ("root2 = %f \n", root2);
}
else if(disc>0)
{
printf("Roots are real and distinct\n");
root1= (-b + sqrt(disc)) / (2*a);
root2= (-b - sqrt(disc)) / (2*a);
printf ("root1 = %f \n",
root1); printf ("root2 = %f \
Module2 CProgrammingforProblemSolving
n", root2);
Module2 CProgrammingforProblemSolving

}
else
{
printf(“Roots are complex\n ”);
rpart = -b(2*a);
ipart=(sqrt(-disc))/(2*a);
printf(“root1=%f + i %f\n”,rpart,ipart);
printf(“root1=%f - i %f\n”,rpart,ipart);
}
}
Ouput
First Run:
Enter the 3 coefficients:
1
2
1
Roots are equal
Root1 = -1.000000
Root2= -1.000000
Second Run:
Enter the 3 coefficients:
2
3
2
Roots are real and
equal Root1=-0.500000
Root2=-2.000000
Third Run:
Module2 CProgrammingforProblemSolving

Enter the 3 coefficients:


2
2
2
Roots are complex
Root1=-0.500000+i 0.866025
Root2=-0.500000- i 0.866025

Programming examples and Exercises


1. What is the output of following program
segment? N=4;
M=3;
for (i=0, j=0; i<=N || j<=M; i++, j++)
{
printf(“I=%d J=%d\n”, i , j);
}
Answer: I=0 J=0
I=1 j=1
I=2 j=2
I=3 j=3
I=4 j=4
2. What is the value of k when loop completes in following
code? k=1;
while(++k <=n)
{
printf(“%d”, k);
}
a. n+1
b. n-1
c. n+2
Module2 CProgrammingforProblemSolving

d. n
AnswernSuppose

if

n=2,Valueprinted

3. for( i=1,j=3; i<3;i++,j--)


printf(“i=%d, j=%d”, i,j)

Outputis:

Round-1:i=1,j=3

4. sum=0
for(n=1; n!=10; n+=2)
sum = sum+n;

Output is:

Round-1:n=1,1!=10istrue

sum=1

Round-2 n=3,3!=10 is true

sum=4

Round-3n=5,5!

=10istrue

sum=9

Round-4n=7,7!=10is

true

5. what is the output of this output:


segment? int x=5, y=50;
round-
while(x<=y)
1:x=50/510round-
{
2: x=50/105so
x=y/x;
x will toggle between10&5
}
and this loop goes
on infinitelyasx<=y
isalways true!
Module2 CProgrammingforProblemSolving

6. Write for statement to print following sequences:


• 1,2,4,8,16,32
• -4,-2,0,2,4 Ans:

1. for(i=1;i<=32;i=i*2)
printf(“%d”,i);

2. for(i=-4;i<=4;i=i+2)

You might also like