0% found this document useful (0 votes)
142 views27 pages

C Programming Basics for Students

1) The document discusses three main programming constructs - sequence, branching, and iteration. Sequence refers to a set of statements executed in order, branching allows different code paths based on conditions, and iteration repeats a sequence of statements. 2) Branching is implemented using if/else statements and switch cases to select different code blocks. Nesting if/else statements can cause dangling else problems. 3) Looping is used to repeat a block of code and is controlled using counters, conditions, or sentinels. Common looping statements include while, for, and do/while loops.

Uploaded by

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

C Programming Basics for Students

1) The document discusses three main programming constructs - sequence, branching, and iteration. Sequence refers to a set of statements executed in order, branching allows different code paths based on conditions, and iteration repeats a sequence of statements. 2) Branching is implemented using if/else statements and switch cases to select different code blocks. Nesting if/else statements can cause dangling else problems. 3) Looping is used to repeat a block of code and is controlled using counters, conditions, or sentinels. Common looping statements include while, for, and do/while loops.

Uploaded by

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

PDS Lab

Section 16
Autumn-2017

Tutorial 3

C Programming Constructs
This flowchart shows how to find the roots of a Quadratic equation Ax2+Bx+C = 0

Start

Input
A,B,C

x  B 2  4 AC

B x
x1   
False If True 2A 2A
x0 B x
x2   
2A 2A

Roots are not real Print real roots


x1 , x 2

Stop

© D. Samanta, IIT
There are three things in any programming:

Sequence: A set of statements which would be executed one after another.

Start

Input
A,B,C

x  B 2  4 AC

B x
x1   
False If True 2A 2A
x0 B x
x2   
2A 2A

Roots are not real Print real roots


x1 , x 2

Stop

© D. Samanta, IIT
Branching: Out of many paths, follow one path

Start

Input
A,B,C

x  B 2  4 AC

B x
x1   
False If True 2A 2A
x0 B x
x2   
2A 2A

Roots are not real Print real roots


x1 , x 2

Stop

© D. Samanta, IIT
Iteration: Repeat a sequence for a number of times.

Start

count= 0;
max= -1;

Please enter
[No]
+ve number count<10?
[Yes]
[True] Read a Print the
x<0? number x maximum
from keyboard
[False]
Stop
[False]
max>x? max=x

[True]
count=count+1

© D. Samanta, IIT
Branching

Branching (also called decision ) allows different set of instructions to


be executed depending on the outcome of logical test.

[False] [True]
Logical test

Block 2 Block 1

The if-else statement is used to express decision.

if (logical test)
block 1
else

Example # include<stdio.h>
Start char sex;
int age;
Read sex main()
and age
{
scanf(‘‘%c’’,&sex);
If scanf(‘‘%d’’,&age);
[False] [True]
(sex==’F’) &&
age<21

Print “You are if((sex==‘F’)&&(age<21))


Print “Hi old
Fox!” a pretty printf(//…………);
woman”;
else
© D. Samanta, IIT printf(//…………);
Stop }
Nesting of if-else statement

If (condition 1)
Block 1
if(condition 2)
Block 2
……
if(condition n)
Block n
else

else
Block 2
else
Block 1

Problem may arise if all “if” statement may not have “else” part! Dangling else
problem.

if (exp1) if (exp1)
if(exp2) if(exp2){
statement1; statement1;
else else
statement2; statement2;
}

Rule: An else clause is associated with the closest preceding unmatched if.

© D. Samanta, IIT
Switch : Multiple Branching

switch (expression) {
case const1: statement1
case const2: statement2
…………………
…………………
default: statement
}

Switch statement is used to select a particular statement from a group of alternative


statement(s).

Note: Here, expression should evaluate to an int value


const1, const2, …. Are integer values only

Example:

int letter;
switch(letter = getchar())
{
case ‘A’:
printf(“First letter %c\n”, letter);
break;

case ‘Z’:
printf(“Last letter %c\n”, letter);
break;

default:
printf(“Your letter %c\n”, letter);
break;
}

Note: The use of break statement

© D. Samanta, IIT
Conditional Operator ?:

Example

interest = (balance>5000)? balance×0.15 : balance×0.10;

This is equivalent to:

if =(balance>5000)
interest= balance×0.15;
else
interest= balance×0.10;

© D. Samanta, IIT
Looping

In looping (also called iteration) a group of instructions that are


executed repeatedly while some condition remains true.

There are three ways to control a looping:

Condition Sentinel
controlled Counter controlled
controlled

© D. Samanta, IIT
Example 1: Counter controlled

Read 5 integers and display the value of their summation.

© D. Samanta, IIT
Example 2: Condition controlled

Given an exam marks as input, display the appropriate message based


on the rules below:

• If marks is greater than 49, display “PASS”, otherwise display


“FAIL”

• However, for input outside the 0-100 range, display “WRONG


INPUT” and prompt the user to input again until a valid input is
entered.

© D. Samanta, IIT
Example 3: Sentinel controlled

Read a number of positive integers and display the summation and


average of these integers.

 A negative or zero input indicates the end of input process.

• Input Example: Sentinel


30 16 42 9 Value

• Output Example:
88
29.33
© D. Samanta, IIT
While Statement

The “while” statement is used to carry out looping operations, in


which a group of statements is executed repeatedly, as long as some
condition remains satisfied.

while (condition)
statement (s);

Example 4: Syntax of while statement

while (condition) {
statement_1;
...
statement_N;
}

while ( ) {
printf (“Line no : d.\n”,i);
;
}

Note:
 The while-loop will not be entered if the loop-control expression
evaluates to false (zero) even before the first iteration.
 break can be used to come out of the while loop.

© D. Samanta, IIT
Example 5: while statement with break

float weight;
int flag = 1;

printf ("Enter your weight: ");


scanf ("%f", &weight);

while ( weight > 65.0 ) {


printf ("Go, exercise, ");
printf ("then come back. \n");

printf ("Do you want to continue?");


scanf ("%d", &flag);

if (!flag)
break;
}

© D. Samanta, IIT
Nested while Statement

How would you print the following diagram?

*****
*****
*****

repeat 3 times repeat 5 times


print a row of 5 stars print *

#define ROWS 3
#define COLS 5

row =1;
while (row <= ROWS) {
/* print a row of 5 *’s */
row++;
}

row=1;
while (row <= ROWS) { outer
col=1; loop
while (col <= COLS) {
printf (“*“);
col++; inner
} loop
printf(“\n”);
© D. Samanta, row++;
IIT
}
do-while Statement

do statement while (expression)

main ()
{
int digit=0;
do
printf(“%d\n”,digit++);
while (digit <= 9) ;
}

© D. Samanta, IIT
for Statement

The “for” statement is the most commonly used looping structure in


C.

General syntax:

for ( expr1; expr2; expr3) statement;

expr1 (init) : initialize parameters

expr2 (test): test condition, loop continues if satisfied

expr3 (update): used to alter the value of the parameters


after each iteration

statement (body): body of the loop

for (expr1;expr2;expr3) {
statement
}

Example

int i;
for (i=1; i < 100; i += 2;) {
printf(“%d\t”,i);
}

© D. Samanta, IIT
The comma operator

We can give several statements separated by commas in place of


“expression1”, “expression2”, and “expression3”.

Example

for (fact=1, i=1; i<=10; i++)


fact fact i;

for (sum=0, i=1; i<=N; i++)


sum sum i i;

Specifying “Infinite Loop”

while (1) {
statements
}
for (; ;)
{
statements
}
do {
statements
} while (1);
© D. Samanta, IIT
The break Statement

Break out of the loop { }

can be used with


while
do while
for
switch

Example

int main() {
int fact, i;
fact = 1; i = 1;

while ( i<=10 ) /* Run loop for 10 times */


{
fact = fact * i;
if ( fact > 100 ) {
printf("Factorial of %d above 100", i);
break;
/* break out of the while loop */
}
i++ ;
}
return 1;
}

© D. Samanta, IIT
does not work with
if
else

• Causes immediate exit from a while, do/while, for or


switch structure.

• Program execution continues with the first statement after


the structure.

The continue Statement

• Skips the remaining statements in the body of a


while, for or do/while structure.
 Proceeds with the next iteration of the loop.

 while and do/while


 Loop-continuation test is evaluated immediately after
the continue statement is executed.

• for structure
 expression3 is evaluated, then expression2 is evalu-
ated.

© D. Samanta, IIT
Example

/* a program segment to calculate 10!

fact = 1; i = 1;

while (1) {
;
;
if( 10 )
continue; /* not done yet! Go to loop */
else
break; /* Done! Break the loop
}

© D. Samanta, IIT
Tutorial Problems
Problem 1
Draw the flowchart of the following C program

# include <stdio.h>
main()
{
int a, b, c;
scanf(“%d %d %d ”, &a, &b, &c);

if &&
printf (“\n The largest number is %d”, a );

if b &&
printf (“\n The largest number is %d”, b );

if c &&
printf (“\n The largest number is %d”, c );
}

Problem 2
Are the following two code fragments give same result?

Code 1:
if (section==16)
printf(‘‘you are in section 16’’);

Code 2:
if (section=16)
printf(‘‘you are in section 16’’);

© D. Samanta, IIT
Problem 3
What will be the output of the following code segment? You should assume
suitable values of the variables and then give your answer.

z = 0;
if(n>0)
if(a>b)
z=a;
else z=b;
printf(‘‘Yahoo! %d’’, z);

Case 1: n = 5, a = 9, b = 6
Case 2: n = -5, a = 9, b = 6
Case 3 n = 5, a = 6, b = 9

Problem 4
Your program asks a user to type y or Y to select Yes and n or N to select No.
Which of the following codes is correct to show the option selected by the user?

Code 1
c = getchar();
if(c==‘y’)&&(c==‘Y’) printf(‘‘Yes \n’’);
else printf(‘‘No \n’’);

Code 2
c = getchar();
if(c!=‘n’)||(c!=‘N’) printf(‘‘Yes \n’’);
else printf(‘‘No \n’’);

© D. Samanta, IIT
Problem 5
Write simplified equivalent code for the following.

x = ((a>10)&&(b<5))?a+b:0;

marks>60 ? printf(“passed \n”): printf(“fail \n”);

Problem 6
Write c-program to convert a grade given a marks.

: 90
A: 80 90
: 70 80
: 60 70
: 50 60
: 35 50
: 35

Problem 7
Which of the following nested if statements are logically equivalent to the flow
chart below?

F
a==

T
T T
d> b> x=b

F F
F
x=a c x= c
T

(A) if(a==b)if(d>c) if(b>c)x=b; else if (c==a);else x=c; else x=a;


(B) if(a==b)if(d>c) if(b>c)x=b; else if (c==a); x=c; else x=a;
(C)© D. Samanta, IIT
if(a==b)if(d>c) if(b>c)x=b; else if (c!=a) x=c; else x=a;
(D) if(a==b)if(d>c) if(b>c)x=b; else if (c!=a) x=c; else; else x=a;
(E) None of the above.
Problem 8
How would you print the following Pascal triangle?

*
***
*****
*******
Problem 9
Let n, i and sum be int variables. The user enters a positive value
of n. Which of the following program segments prints the largest
value of sum?

sum = 0; i = 1; while (++i < n) sum += i;


printf("%d", sum);

sum = 0; i = 1; while (i++ < n) sum += i;


printf("%d", sum);

for (sum = 0, i = 1; i < n; i++) sum += i;


printf("%d", sum);

for (sum = 0, i = 1; i <= n; ++i) sum += i;


printf("%d", sum);

© D. Samanta, IIT
Problem 10
Consider the program segment.
int sum = 0;
int i = 0;
while (i < 5)
{
sum = sum + i;
i++;
}
printf(‘‘%d\n’’,sum);

Suppose we replace the while loop in the segment above with a for loop.
Which of the following for loops will result in the same value of sum
printing out?

A. for (int i = 0; i <= 5; i++)


sum = sum + i;

B. for (int i = 1; i <= 5; i++)


sum = sum + i;

C. for (int i = 1; i < 5; i++)


sum = sum + i;

D. for (int i = 2; i < 5; i++)


sum = sum + i;

E. for (int i = 1; i < 6; i++)


sum = sum + i;
© D. Samanta, IIT
Important links:
http://cse.iitkgp.ac.in/~dsamanta/courses/pds/index.html

© D. Samanta, IIT

You might also like