0% found this document useful (0 votes)
7 views

Introduction to C (3)

Uploaded by

mborasydn
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)
7 views

Introduction to C (3)

Uploaded by

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

1

3
Structured Program
Development in C

© 2007 Pearson Education, Inc. All rights reserved.


2

Let’s all move one place on.


—Lewis Carroll

The wheel is come full circle.


—William Shakespeare

How many apples fell on Newton’s head before


he took the hint!
—Robert Frost

All the evolution we know of proceeds from the


vague to the definite.
—Charles Sanders Peirce

© 2007 Pearson Education, Inc. All rights reserved.


3

OBJECTIVES
In this chapter you will learn:
▪ To develop algorithms through the process of
top-down, stepwise refinement.
▪ To use the if selection statement and if...else
selection statement to select actions.
▪ To use the while repetition statement to execute
statements in a program repeatedly.
▪ Counter-controlled repetition and sentinel-controlled
repetition.
▪ Structured programming.
▪ The increment, decrement and assignment operators.

© 2007 Pearson Education, Inc. All rights reserved.


4

Software Engineering Observation


Experience has shown that the most difficult part of solving
a problem on a computer is developing the algorithm for the
solution. Once a correct algorithm has been specified, the
process of producing a working C program is normally
straightforward.

Algorithm is the step by step definition of the problem in detail.

© 2007 Pearson Education, Inc. All rights reserved.


Steps in Problem Solving

First produce a general algorithm (you can use


pseudocode). Refine your steps until you get to an easy
sequence.

Pseudocode is an artificial and informal language that helps


programmers develop algorithms. Pseudocode may be an
informal English, combinations of computer languages and
spoken language. Whatever works for you.

© 2007 Pearson Education, Inc. All rights reserved.


Example:
Write an algorithm to determine a student’s final grade and
indicate whether it is passing (>60) or failing. The final grade
is calculated as the average of four marks.

Pseudocode:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 60
Print “FAIL”
else
Print “PASS”
7

Flowchart (grafical representation of an algorithm)

Basic and most common algorithm symbols are shown here.


Diamond is decision symbol. Rectangle is process symbol.
Parallelogram is input-output symbol. Cycle is the terminal symbol.

© 2007 Pearson Education, Inc. All rights reserved.


Example:
Draw the flowchart of an algorithm which finds the sum of two numbers
N and M

© 2007 Pearson Education, Inc. All rights reserved.


Example:
Draw the flowchart of an algorithm which finds the sum of the first 50
numbers

© 2007 Pearson Education, Inc. All rights reserved.


10

Diamond symbol (decision symbol)


– Indicates decision is to be made
– Test the condition, then, follow appropriate path

Contains a test condition that can be


true or false

– Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed

© 2007 Pearson Education, Inc. All rights reserved.


11

The if selection statement


▪ if selection structure is used to choose among alternative courses of
action
if (condition)
statement 1;

▪ If condition true
– Print statement executed and program goes on to next
statement
– If false, print statement is ignored and the program
goes onto the next statement

© 2007 Pearson Education, Inc. All rights reserved.


The if selection statement
▪ General Form: if the condition is true then statement 1 is executed. If
the condition is false then statement 1 is skipped.
If there is only one statement inside the
if (condition) block, there is no need to use braces. Curly
statement 1; braces show the borders of the compound
statement or block.

▪ A compound statement or block, which is composed of a set of


statements enclosed in braces, can also be used.

if (condition) Example
{
statement 1; if (a < 50)
statement 2; {
… count=count +1;
statement n; sum =sum + a;
} }

© 2007 Pearson Education, Inc. All rights reserved.


The if selection statement
▪ if statements can also be nested:

Example:

if (a < 50)
{
count=count +1;
sum = sum + a;
if (b > a)
b = 0;
}

Any if statement can be inside another if statement.

© 2007 Pearson Education, Inc. All rights reserved.


14

The if…else selection statement


▪ if
– Only performs an action if the condition is true
▪ if…else
– Specifies an action to be performed both when the condition is true
and when it is false
▪ Psuedocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”

© 2007 Pearson Education, Inc. All rights reserved.


The if…else selection statement
▪ The if/else statement allows to execute one set of statements if a
condition is true and a different set if the condition is false.
▪ General Form:
if (condition)
statement1;
else
statement2;

▪ Statements 1 and 2 can also be an empty statement, which is a


semicolon.
if (a < b)
; Empty statement
else
count=count +1;

© 2007 Pearson Education, Inc. All rights reserved.


The if…else selection statement
▪ Example:

if (x > y)
if (y < z)
k++;
else
m++;
else
j++;

Please pay attention to the indentation usage. There is only one


statement in each block. So, there is no need to use braces. Last statement
belongs to the outer if block.

© 2007 Pearson Education, Inc. All rights reserved.


The if…else selection statement
Indentation is just for style and it does not change interpretation.

if (x > y) if (x > y) if (x > y)


if (y < z) if (y < z) {
k++; k++; if (y < z)
else else k++;
j++; j++; }
else
j++;

(same) (same,correct
indentation)

© 2007 Pearson Education, Inc. All rights reserved.


What is the output of the following code? Q
#include <stdio.h>

int main()
{
int x=1, y=2, z=3, k=0, j=0;

if (x > y){
if (y < z)
k++;}
else
j=j+1;

printf("k=%d, j=%d\n", k, j);


return 0;
}
Write a program that reads in four integers from the keyboard and
then calculates the sum of the numbers which are positive. The screen
Q
dialogue should appear as follows:
Input four different integers: 14 8 11 -8
The sum of the positive numbers is: 25

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1, x2, x3, x4;
int sum=0;

printf("Input four different integers: " );


scanf("%d%d%d%d",&x1, &x2, &x3, &x4);
if (x1>0) sum=x1;
if (x2>0) sum=sum+x2;
if (x3>0) sum=sum+x3;
if (x4>0) sum=sum+x4;

printf("The sum of the positive numbers is: %d\n",sum);


system("Pause");
return 0; /* successful termination */
}
Ternary conditional operator (?:)
▪ Takes three arguments (condition, value if true, value if false)
Condition
▪ Example:
printf( "%s\n", grade >= 60 ? "Passed" : "Failed" );

OR

grade >= 60 ? printf( “Passed\n” ) : printf( “Failed\n” );

OR

if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");

© 2007 Pearson Education, Inc. All rights reserved.


What is the output of the following program? Q
main() {
int a = 10, b = 11; int c = (a < b)? a : b;
printf ("%d", c+1);
}

a) 10 b) 9 c) 11 d) 12 e) 13
Write a program that reads in one integer from the keyboard and then Q
prints out a message whether integer is greater than zero or not (by
using ternary operatör) . The screen dialogue should appear as follows:
Input one integer: 14
Greater than zero

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1;

printf("Input one integer: " );


scanf("%d",&x1);

x1 > 0 ? printf("Greater than zero\n" ) : printf("Less than


zero\n");

return 0; /* successful termination */


}
23

The while repetition statement


– Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;

While loop is repeated


until condition
becomes false

– Pseudocode:
While there are more items on my shopping list
Purchase next item and cross it off my list

© 2007 Pearson Education, Inc. All rights reserved.


24

Counter-Controlled Repetition
▪ Counter-controlled repetition
– Loop repeated until counter reaches a certain value
– Definite repetition: number of repetitions is known
if number of repetitions is known a counter is used to
control repetition

© 2007 Pearson Education, Inc. All rights reserved.


25

Example: Ten students took a quiz. The grades (integers in the


range 0 to 100) for this quiz are available to you. Determine the
class average on the quiz. Write pseudocode of the algorithm.

1 Set total to zero


Pseudocode of algorithm
2 Set grade counter to one
3
4 While grade counter is less than or equal to ten
5 Input the next grade
6 Add the grade into the total
7 Add one to the grade counter
8
9 Set the class average to the total divided by ten
10 Print the class average

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 3.6: fig03_06.c 26
2 Class average program with counter-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter; /* number of grade to be entered next */
9 int grade; /* grade value */
10 int total; /* sum of grades input by user */
Counter to control while loop
11 int average; /* average of grades */
12
13 /* initialization phase */
14 total = 0; /* initialize total */
15 counter = 1; /* initialize loop counter */ Initialize counter to 1
16
17 /* processing phase */
18 while ( counter <= 10 ) { /* loop 10 times */
while loop iterates as long as
19 printf( "Enter grade: " ); /* prompt for input */ counter <= 10
20 scanf( "%d", &grade ); /* read grade from user */
21 total = total + grade; /* add grade to total */
22 counter = counter + 1; /* increment counter */ Increment the counter
23 } /* end while */
24
25 /* termination phase */
26 average = total / 10; /* integer division */
27
Calculate the average
28 printf( "Class average is %d\n", average ); /* display result */
29
30 return 0; /* indicate program ended successfully */
31
32 } /* end function main */ © 2007 Pearson Education,
Inc. All rights reserved.
27

Sentinel Controlled Repetition


▪ if number of repetitions is not known a sentinel
(dummy) value is used to control repetition

▪ Use sentinel value


– Also called signal value, dummy value, or flag value
– Indicates “end of data entry.”
– Loop ends when user inputs the sentinel value
– Sentinel value chosen so it cannot be confused with a
regular input (such as -1 in this case)

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 3.8: fig03_08.c 28
2 Class average program with sentinel-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter; /* number of grades entered */
9 int grade; /* grade value */
10 int total; /* sum of grades */
11
12 float average; /* number with decimal point for average */
13
float type indicates variable
14 /* initialization phase */
can be a non-integer
15 total = 0; /* initialize total */
16 counter = 0; /* initialize loop counter */
17
18 /* processing phase */
19 /* get first grade from user */
20 printf( "Enter grade, -1 to end: " ); /* prompt for input */
21 scanf( "%d", &grade ); /* read grade from user */
22

© 2007 Pearson Education,


Inc. All rights reserved.
23 /* loop while sentinel value not yet read from user */ 29
24 while ( grade != -1 ) {
25 total = total + grade; /* add grade to total */
26 counter = counter + 1; /* increment counter */ while loop repeats until user
27 enters a value of -1
28 /* get next grade from user */
29 printf( "Enter grade, -1 to end: " ); /* prompt for input */
30 scanf("%d", &grade); /* read next grade */
31 } /* end while */
32
33 /* termination phase */
34 /* if user entered at least one grade */ Ensures the user entered at least
35 if ( counter != 0 ) {
one grade
36
37 /* calculate average of all grades entered */
38 average = ( float ) total / counter; /* avoid truncation */
39
Converts total to
40 /* display average with two digits of precision */ float type
41 printf( "Class average is %.2f\n", average );
42 } /* end if */ Prints result with 2 digits
43 else { /* if no grades were entered, output message */ after decimal point
44 printf( "No grades were entered\n" );
45 } /* end else */
46
47 return 0; /* indicate program ended successfully */
48
49 } /* end function main */
© 2007 Pearson Education,
Inc. All rights reserved.
30

Enter grade, -1 to end: 75


Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50

Enter grade, -1 to end: -1


No grades were entered

© 2007 Pearson Education,


Inc. All rights reserved.
What is the expected output of each of the following? Q

© 2007 Pearson Education,


Inc. All rights reserved.
How many 1s, 2s, 3s and 4s will be printed after Q
the execution of the following program segment ?

int sum=0, i=0;


printf ("1");
while (i<50) {
printf ("2"); printf ("3");
printf ("3"); i++; printf ("4"); }

a) (100 1s), (100 2s), (100 3s) and (100 4s)


b) (1 1), (50 2s), (100 3s) and (50 4s)
c) (1 1), (100 2s), (100 3s) and (100 4s)
d) (1 1), (50 2s), (50 3s) and (50 4s)
e) (100 1s), (100 2s), (100 3s) and (50 4s)
33

Performance Tip

Assigning value (Initializing variables )

Initializing variables when they are defined can help


reduce a program’s execution time.
int passes = 0;
int failures = 0;
int student = 1;

© 2007 Pearson Education, Inc. All rights reserved.


34

Assignment Operators
c = c + 3;

Assignment operator

The form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
can be abbreviated as
c += 3;
using the addition assignment operator

© 2007 Pearson Education, Inc. All rights reserved.


35

Examples of other assignment operators:

d -= 4; is equal to (d = d - 4)
e *= 5; is equal to (e = e * 5)
f /= 3; is equal to (f = f / 3)
g %= 9; is equal to (g = g % 9)

© 2007 Pearson Education, Inc. All rights reserved.


36

Increment and Decrement Operators


▪ Increment operator (++)
– Can be used instead of c+=1
▪ Decrement operator (--)
– Can be used instead of c-=1

▪ Preincrement
– Operator is used before the variable (++c or --c)
– Variable value is changed before the expression it is in is evaluated
▪ Postincrement
– Operator is used after the variable (c++ or c--)
– Expression executes before the variable value is changed

© 2007 Pearson Education, Inc. All rights reserved.


37

Increment and Decrement Operators


▪ If c equals 5, then
printf( "%d", ++c );
– Prints 6
Variable is in an
expression
– -------------------------------------------
printf( "%d", c++ );
– Prints 5

In either case, c now has the value of 6

© 2007 Pearson Education, Inc. All rights reserved.


38

Increment and Decrement Operators


▪ When variable not in an expression
– Preincrementing and postincrementing have the same effect
++c;
printf( “%d”, c );
– Has the same effect as
c++;
Variable is not in an
expression
printf( “%d”, c );

© 2007 Pearson Education, Inc. All rights reserved.


39

Operator Sample expression Explanation

++ ++a Increment a by 1, then use the new value of a in the


expression in which a resides.
++ a++ Use the current value of a in the expression in which a
resides, then increment a by 1.
-- --b Decrement b by 1, then use the new value of b in the
expression in which b resides.
-- b-- Use the current value of b in the expression in which b
resides, then decrement b by 1.

Fig. 3.12 | Increment and decrement operators.

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 3.13: fig03_13.c 40
2 Preincrementing and postincrementing */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig03_13.c
7 {
8 int c; /* define variable */
9
10 /* demonstrate postincrement */
11 c = 5; /* assign 5 to c */
12 printf( "%d\n", c ); /* print 5 */
13 printf( "%d\n", c++ ); /* print 5 then postincrement */ c is printed, then incremented
14 printf( "%d\n\n", c ); /* print 6 */
15
16 /* demonstrate preincrement */
17 c = 5; /* assign 5 to c */
18 printf( "%d\n", c ); /* print 5 */
19 printf( "%d\n", ++c ); /* preincrement then print 6 */ c is incremented, then printed
20 printf( "%d\n", c ); /* print 6 */
21
22 return 0; /* indicate program ended successfully */
23
24 } /* end function main */
5
5
6

5
6
6
© 2007 Pearson Education,
Inc. All rights reserved.
What will be the value of the variable length Q
after the following code is executed?

int length = 5; int count = 4;


while (count <=6) {
if (length >= 100) length = length - 2;
else length = count * length;
count++; }

a) 600 b) 100 c) 98 d) 20 e) none of the above


42

Operators Associativity Type

++ (postfix) -- (postfix) right to left postfix

+ - ( type) ++ (prefix) -- (prefix) right to left unary

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

?: right to left conditional

= += -= *= /= %= right to left assignment

Fig. 3.14 | Precedence of the operators encountered so far in the text.


Post increment and decrement operators have highest precedence.
Multiplication have higher precedence than summation and subtraction.

© 2007 Pearson Education, Inc. All rights reserved.


Write four different C statements that each adds 1 to Q
integer variable “x”.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1, x2, x3, x4;
x1=x2=x3=x4=1;
x1=x1+1; %1st
x2+=1; %2nd
x3++; %3th
++x4; %4th
printf("The results are: %d, %d, %d, %d\n",x1,x2,x3,x4);

system("Pause");
return 0; /* successful termination */
}
What is the expected output of each of the following? Q

int i=3;
printf( "%d ", (--i + 3) );
printf( "%d", (i++ + 10) );

Answer:
5 12
What will be the output of the following code segment? Q
int a=1, b=2, c=10;

while (b<c) {
a+=--c-b++;
printf ("%d ", a); }

a) 7 12 15 16 b) 8 13 16 17 c) 8 12 15 17
d) 6 11 14 15 e) 7 11 14 16

© 2007 Pearson Education,


Inc. All rights reserved.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy