Introduction to Computer Algorithmics and Programming Ceng 113 Program Control Statements.

Slides:



Advertisements
Similar presentations
CSCI 130 Advanced Program Control Chapter 8. Program Controls so far for loop while loop do…while loop.
Advertisements

For loops For loops are controlled by a counter variable. for( c =init_value;c
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
1 Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps.
1 CS 192 Lecture 9 Winter 2003 December 19, 2003 Dr. Shafay Shamail.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
Review: midterm #9 #include void main(void) { int c; c = getchar(); if(c>=48){ if(c
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
UNIT II Decision Making And Branching Decision Making And Looping
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C.
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Chapter 4 Program Control Statements
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Conditional Statement
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Lecture 4 Introduction to Programming. if ( grade ==‘A’ ) cout
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Flow of Control Part 1: Selection
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Chapter 5: Structured Programming
1 Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Week 4 Program Control Structure
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
BY ILTAF MEHDI (MCS, MCSE, CCNA)1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI (MCS, MCSE, CCNA)2 Chapter No: 04 “Loops”
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Introduction to Programming Using C Basic Logic. 2 Contents Conditional programming If statement Relational operators Compound statements Loops While.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
CONTROL FLOW. Introduction  In a program instructions are always executed in the sequential manner.  If programmer wishes to specify the order in which.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
ECE Application Programming
Chapter 4 – C Program Control
CSE 220 – C Programming Loops.
REPETITION CONTROL STRUCTURE
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Flow of Control True and False in C Conditional Execution Iteration
C Program Controls + Flow Structure
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Control Structures Lecture 7.
Looping.
Chapter 4 - Program Control
Loops in C.
Program Control Topics While loop For loop Switch statement
ECE 103 Engineering Programming Chapter 18 Iteration
Presentation transcript:

Introduction to Computer Algorithmics and Programming Ceng 113 Program Control Statements

Selection –if and switch Iteration –while, for, do-while Jump –break, continue, return Label Expression Block –A block begins with a { and ends with a }.

Selection Statements The general form of the if statement is; if (expression) statement; else statement; A statement may consist of a single statement or a block of statements or nothing. The else clause is optional. /* Magic number program #1 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) printf(“** Right **”); }

Selection Statements /* Magic number program #2 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) printf(“** Right **”); else printf(“Wrong”); }

Nested ifs A nested if is an if that is the target of another if or else. if (i) { if (j) statement 1; if (k) statement 2; /* this if */ else statement 3; /* is associated with this else */ } else statement 4; /* associated with if(i) */

Selection Statements /* Magic number program #3 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) { printf(“** Right **”); printf(“%d is the magic number \n”, magic); } else {printf(“Wrong, ”); if (guess > magic) printf(“too high \n”); else printf(“too low \n”); }

The if-else-if Ladder General form is; if (expression) statement; else if (expression) statement;.... else statement;

Selection Statements /* Magic number program #4 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) { printf(“** Right **”); printf(“%d is the magic number \n”, magic); } else if (guess > magic) printf(“Wrong, too high \n”); else printf(“Wrong, too low \n”); }

The ? Alternative We can use the ? Operator to replace if-else statements of the general form: if (condition) expression; else expression; However, the ? is called ternary operator because it requires three operands. Exp1 ? Exp2: Exp3; x = 10; y = x>9 ? 100: 200; x = 10; if (x>9) y = 100; else y = 200;

Sample program /* Magic number program #5 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) { printf(“** Right **”); printf(“%d is the magic number \n”, magic); } else guess > magic ? printf(“High”) : printf(“Low”); }

Sample program /*This program uses the ? operator to square an integer value entered by the user but preserves the sign (10 squared is 100 and -10 squared is -100).*/ #include “stdio.h” void main(void) { int isqrd, i; printf(“enter a number :”); scanf(“%d”, &i); isqrd = i>0 ? i*i : -(i*i); printf(“%d squared is %d”, i, isqrd); }

Sample program #include “stdio.h” int f1(int n); int f2(void); void main(void) { int t; printf(“enter a number: “); scanf(“%d”, &t); /* print proper message */ t ? f1(t) + f2( ) : printf(“zero entered”); } f1(int n) { printf(“%d ”, n); return 0; } f2(void) { printf(“entered”); return 0; } if (t!=0) { f1(t); f2; } else printf(“zero entered”);

switch C has a built-in multiple branch selection statement, switch, which tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. switch (expression) { case constant1: statement sequence break; case constant2: statement sequence break;... default: statement sequence } The default statement is executed if no matches are found. The default is optional. A switch statement can be included maximum 257 case statements. When break statement is encountered in a switch, program execution “jumps” to the line of code following the switch statement.

switch menu() { char ch; printf(“1.Check spelling \n”); printf(“2.Correct spelling errors\n”); printf(“3.Display spelling errors\n”); printf(“Strike any other key to skip \n”); printf(“ Enter your choise: ”); ch = getchar(); /* read the selection from the keyboard*/ switch(ch) { case ‘1’ : check_spelling(); break; case ‘2’: correct_errors(); break; case ‘3’: display_errors(); break; default : printf(“No option selected”); }

switch /*Process a value */ void inp_handler(int i) {int flag; flag = -1; switch(i) { case 1: case 2: case 3: flag= 0; break; case 4: flag= 1; case 5: error(flag); break; default : process(i); }

Nested switch statement switch(x) { case 1: switch(y) { case 0: printf(“divide by zero error”); break; default: process(x, y); } break; case 2:...

Example The programmer has given each medical plan a code: Plan1 = F, Plan2 = B, Plan3 = K and Plan4=E. The company pays for all of Plan1. The individual has to pay for part of the others. Plan2 = amount/4, Plan3 = amount/7, Plan4 = amount/5. Any other codes are considered in error. Write the algorithm and C code to calculate the total amount which the company will be paid to plans.

#include "stdio.h" main() {int total_investment=0, int amount_of_plan=0; char plan_code; printf("\n Enter the selected plan code (F, B, K, E) ="); scanf("%c", &plan_code); printf("\n Enter the amount of total investment for selected plan ="); scanf("%d", &total_investment); switch(plan_code) { case 'F': {amount_of_plan=total_investment; printf("\n The amount of this plan = %d", amount_of_plan); break;} case 'B': {amount_of_plan=total_investment / 4; printf("\n The amount of this plan = %d", amount_of_plan); break;} case 'K': {amount_of_plan=total_investment / 7; printf("\n The amount of this plan = %d", amount_of_plan); break;} case('E'): {amount_of_plan=total_investment / 5; printf("\n The amount of this plan = %d", amount_of_plan); break;} default: printf("\n You selected invalid plan code."); }

#include main() /* count digits, white space, others */ { char c; int i, nwhite, nother, ndigit[10]; nwhite = nother = 0; for (i = 0; i < 10; i++) ndigit[i] = 0; while ((c = getchar()) != ‘.’) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigit[c-'0']++; break; case ' ': case '\n': case '\t': nwhite++; break; default: nother++; break; } printf("digits ="); for (i = 0; i < 10; i++) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); }

Iteration statements Iteration ( also called loops) statements allow a set of instructions to be performed until a certain condition is reached. This condition may be predifened as in the for loop, or open ended as in the while and do-while loops.

The for loop The general form of the for statement is; for (initialization; condition; increment) statement; The initialization is an assignment statement that is used to set the loop control variable. The condition is relational expression that determines when the loop exist. The increment defines how the loop control variable changes each time the loop is repeated. #include stdio.h main() { int x; for(x=1; x<=100;x++) printf(“%d “, x); }

The for loop Sample 1; for(x=100; x!=65; x-=5) { z = x*x; printf(“The square of %d, %d”, x, z); } Sample 2; x = 10; for(y=10; y!=x; y++) printf(“%d”, y); printf(“%d”, y); Sample 3; for(x=0; x!=123; ) scanf(“%d”, &x);

The for loop The infinity loop; You can make an endless loop by leaving the conditional expression empty; for( ; ; ) printf(“ this loop will run forever. \n”); Sample; ch = ‘\0’; for( ; ; ) { ch=getchar(); /* get a character */ if (ch==‘A’) break; /* exit the loop */ } printf(“you typed an A”);

Exercise Create a function which is convert the 0,5,10,15,20, 25, 30...,90, 95, 100 celsius to fahrenheight values in a table. F = ((C/5)*9+32)

Exercise /* This program convert to celsius to fahrenheight.*/ #include int main() { // Define variables int celsius, fahrenheight; // Print the table headers printf("\n Program will be list celcius and fahrenheight convertion table."); printf("\n CelciusFahrenheight"); // Convert the celsius to fahrenheight between 5 and 100. for (celsius = 0; celsius <=100; celsius +=5) { fahrenheight=((celsius/5) * 9 +32); printf("\n %d %d", celsius, fahrenheight); } printf("\n"); return 0; }

The while loop Its general form is; while(condition) statement; The loop iterates while the condition is true. When the condition becomes false, program control passes to the line after the loop code. wait_for_char(void) {char ch; ch = ‘\0’; /*initialize ch */ while(ch != ‘A’) ch = getchar(); return ch; }

The while loop /*add spaces to the end of string */ #include “stdio.h” #include “string.h” void main(void) {char str[40]; int k; strcpy(str, “this is a test”); k = strlen(str); printf(“%d”, k); while (k <40) {str[k] = ‘ ‘; k++; } str[k] = ‘\0’; /*strings need to be terminated in a null */ printf(“%d”, strlen(str)); } *

The do-while loop The do-while loop checks its condition at the bottom of the loop. A do- while loop always executes at least once. do { statement } while(condition); Sample; do { scanf(“%d”, &num); } while(num>100);

menu() { char ch; printf(“1.Check spelling \n”); printf(“2.Correct spelling errors\n”); printf(“3.Display spelling errors\n”); printf(“Strike any other key to skip \n”); printf(“ Enter your choise: ”); do { ch = getchar(); /* read the selection from the keyboard*/ switch(ch) { case ‘1’ : check_spelling(); break; case ‘2’: correct_errors(); break; case ‘3’: display_errors(); break; default : printf(“No option selected”); } } while(ch=‘1’ || ch =‘2’ || ch = ‘3’); }

Exercise Mr.Brown has given a test to his class. He would like to have the avarage score for the class, and the higest and lowest scores. Develop a solution to calculate and print out these values. ( Use a significant value to stop the processing of the loop).

# include void main () { int counter=0, avarage=0, lowest=100, higest=0, total_grades=0, grade; printf("\n Please enter -1 to terminate the program.\n"); printf("\n Enter a student grade ="); scanf("%d", &grade); while (grade != -1) { total_grades = total_grades + grade; counter++; if (lowest > grade ) lowest = grade; if (higest < grade ) higest = grade; printf("\n Enter a student grade ="); scanf("%d", &grade); } printf("\n The higest grade is %d", higest); printf("\n The lowest grade is %d", lowest); printf("\n The avarege grade is %d", (total_grades/counter)); } While loop!

# include void main () { int counter=0, avarage=0, lowest=100, higest=0, total_grades=0, grade; printf("\n Please enter -1 to terminate the program.\n"); do { printf("\n Enter a student grade ="); scanf("%d", &grade); if (grade != -1) { total_grades = total_grades + grade; counter++; if (lowest > grade ) lowest = grade; if (higest < grade ) higest = grade; } }while (grade != -1); printf("\n The higest grade is %d", higest); printf("\n The lowest grade is %d", lowest); printf("\n The avarege grade is %d", (total_grades/counter)); } Do-While loop!

Unconditional Branch The return statement; The return statement is used to return from a function. It is a jump statement because it causes execution to return (jump back) to the point at which the call to the function was made. return expression; The expression is optional.

Unconditional Branch The break statement; This statement has two uses; 1. to terminate a case in the switch statement, 2. to force immediate terminator of a loop, bypassing the normal loop conditional test. #include “stdio.h” void main(void) { int t; for(t=0; t<100; t++) { printf(“%d”, t); if(t==10) break; } for(t=0; t<100; ++t) { count=1; for( ; ; ) { printf(“%d”, count); count++; if(count==10) break; }

Unconditional Branch The exit() function; You can break out of a program by using the standart library function exit().This function causes immediate termination of the entire program, forcing a return to the operating system. void exit(int return_code); The value of return_code is returned to the calling process, which is usually the operating system. Zero is generally used as a returned code to indicate normal program termination.

Unconditional Branch The continue statement; Continue forces the next iteration of the loop. * /*count spaces */ #include “stdio.h” main() { char s[80], *str; int space; printf(“enter a string: “); gets(s); str =s; for(space=0; *str; str++) { if(*str!=‘ ‘) continue; space++; } printf(“%d spaces \n”, space); }

Next Course Arrays and Strings –...