CS1100 Computational Engineering

Slides:



Advertisements
Similar presentations
Decisions If statements in C.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Introduction to C Programming
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The University of Texas – Pan American
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
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.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Lecture 4b Repeating With Loops
CSE1301 Sem Selection Lecture 25 Lecture 9: Selection.
Chapter 4 – C Program Control
CNG 140 C Programming (Lecture set 3)
‘C’ Programming Khalid Jamal.
REPETITION CONTROL STRUCTURE
Chapter 4 C Program Control Part I
Chapter 2 - Introduction to C Programming
Lecture 7: Repeating a Known Number of Times
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CS1010 Programming Methodology
Lecture 13 & 14.
Repetition-Counter control Loop
Chapter 2 - Introduction to C Programming
Looping.
CS1100 Computational Engineering
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Structured Program
1) C program development 2) Selection structure
3 Control Statements:.
Chapter 2 - Introduction to C Programming
Statement-Level Control Structures
REPETITION STATEMENTS
2.6 The if/else Selection Structure
CprE 185: Intro to Problem Solving (using C)
Week 3 – Program Control Structure
Chapter 2 - Introduction to C Programming
ECE 103 Engineering Programming Chapter 18 Iteration
Decisions, decisions, decisions
Chapter 4 - Program Control
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Introduction to C Programming
CprE 185: Intro to Problem Solving (using C)
ICS103: Programming in C 5: Repetition and Loop Statements
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

CS1100 Computational Engineering Selection Statements

Decisions with Variables Need for taking logical decisions during problem solving If b^2 – 4ac negative, we should report that the quadratic has no real roots The if-else programming construct provides the facility to make logical decisions Syntax: if (condition) { evaluate this part if true} else { evaluate this part if false} 2

Specified using relational and equality operators Conditions Specified using relational and equality operators Relational: >, <, >=, <= Equality: ==, != Usage: for a,b values or variables a > b, a < b, a >= b, a <= b, a == b, a != b A condition is satisfied or true, if the relational operator, or equality is satisfied. For a = 3, and b = 5: a < b, a <= b, and a != b are true a > b, a >= b, a == b are false 3

Terminates execution and returns argument (1) Completing the program if (discrim < 0) { printf(“no real roots, only complex\n”); exit(1); } else root1 = (−coeff2 + sqrt(discrim))/denom; root2 = (−coeff2 − sqrt(discrim))/denom; Terminates execution and returns argument (1) 4

Statement: a logical unit of instruction/command Statements Statement: a logical unit of instruction/command Program : declarations and one or more statements assignment statement selection statement repetitive statements function calls etc. All statements are terminated by semicolon ( ; ) Note: In C, semi-colon is a statement terminator rather than a separator!

Assignment statement General Form: variable “ = ” expression | constant “;” The declared type of the variable should match the type of the result of expression/constant Multiple Assignment: var1 = var2 = var3 = expression; var1 = (var2 = (var3 = expression)); Assignment operator associates right-to-left.

“scope” of the variable declarations Compound Statements A group of declarations and statements collected into a single logical unit surrounded by braces a block or a compound statement “scope” of the variable declarations part of the program where they are applicable the compound statement variables come into existence just after declaration continue to exist till end of the block unrelated to variables of the same name outside the block block-structured fashion

An Example { int i, j, k; i = 1; j =2; k =3; if ( expr ) { int i, k; i = j; printf(“i = %d\n”, i); } This i and k and the previously declared i and k are different. Not a good programming style. // output is 2 Note: No semicolon after } A compound statement can appear wherever a single statement may appear // output is 1

double selection: multiple selection: Selection Statements Three forms: single selection: if ( att < 85 ) grade = “W”; double selection: if (marks < 40 ) passed = 0; /* false = 0 */ else passed = 1; /* true = 1 */ multiple selection: switch statement - to be discussed later no then reserved word

if (<expression>) <stmt1> [ else <stmt2>] Semantics: If Statement if (<expression>) <stmt1> [ else <stmt2>] Semantics: Expression evaluates to “true” stmt1 will be executed Expression evaluates to “false” stmt2 will be executed Else part is optional Expression is “true” -- stmt1 is executed Otherwise the if statement has no effect optional

Sequence and Selection Flowcharts Structure If structure true false Single Entry Single Exit if - else structure true false

Note the semicolon before else ! Grading Example Below 50: D; 50 to 59: C ; 60 to 75: B; 75 above: A int marks; char grade; … if (marks <= 50) grade = ‘D’; else if (marks <= 59) grade = ‘C’; else if (marks <=75) grade = ‘B’; else grade = ‘A’; Note the semicolon before else ! Unless braces are used, an else part goes with the nearest else-less if stmt

Caution in use of “else” if ( marks > 40) if ( marks > 75 ) printf(“you got distinction”); else printf(“Sorry you must repeat the course”); if ( marks > 40) { } /* WRONG */ /*RIGHT*/

Switch Statement A multi-way decision statement Syntax: switch ( expression ) { case const-expr : statements; … [default: statements;] }

Counting Evens and Odds int num, eCount = 0, oCount = 0; scanf (“%d”, &num); while (num >= 0) { switch (num%2) { case 0: eCount++; break; case 1: oCount++; break; } printf( “Even: %d , Odd: %d\n”, eCount, oCount); Counts the number of even and odd integers in the input. Terminated by giving a negative number

Fall Through Switch statement: Break statement: Execution starts at the matching case and falls through the following case statements unless prevented explicitly by break statement Useful for specifying one action for several cases Break statement: Control passes to the first statement after switch A feature requiring exercise of caution

Switch Statement Flowchart Single Entry Single Exit true case a action(s) break false case a case b action(s) case b case z action(s) case z default action(s)

Conditional Operator ( ?: ) Syntax (<expression>)? <stmt1>:<stmt2> Closely related to the if – else statement if (<expression>) <stmt1> else <stat2> Only ternary operator in C E.g.: (marks <40)? passed = 0 : passed = 1; printf (“ passed = %d\n ”, (marks<40)?0:1);

Write a program to check if a given number is prime. Programming Problems Write a program to check if a given number is prime. Write a program to count the number of digits in a given number. Your answer should contain two parts, number of digits before and after the decimal. (Can you do this only with assignments to variables, and decisions?) 19

Repetitive Statements A very important type of statement iterating or repeating a set of operations a very common requirement in algorithms C offers three iterative constructs the while … construct the for construct the do … while construct

while ( <expr> ) <statement> Semantics: The while Construct General form: while ( <expr> ) <statement> Semantics: repeat: Evaluate the “expr” If the “expr” is true execute the “statement” else exit the loop “expr” must be modified in the loop or we have an infinite loop! true false expr body

Computing 2n, n>=0, using while Construct Syntax – while (condition){ statement} #include<stdio.h> main( ) { int n, counter, value; printf (“Enter value for n:”); scanf (“%d”, &n); value = 1; printf (“current value is %d \n”, value); 22

Exercise: try this program and identify problems Contd… counter = 0; while (counter <= n) { value = 2 * value; printf (“current value is %d \n”, value); counter = counter + 1; } n = 0 : both 1 and 2 get printed! n = 2: 1, 2, 4, 8 get printed! The error is that n+1 iterations take place. But instead of n+1 values, n+2 values get printed! Exercise: try this program and identify problems 23

Hand simulate the execution of the program Testing the Program Choose test cases: A few normal values: n = 2, 5, 8, 11 Boundary values: n = 0, 1 Invalid values: n = –1 Hand simulate the execution of the program On paper, draw a box for each variable and fill in the initial values (if any) Simulate exec. of the program one statement at a time For any assignment, write the new value of the variable in the LHS Check if the output is as expected in each test case

#include<stdio.h> main( ) { int n, counter, value; Hand Simulation counter value n #include<stdio.h> main( ) { int n, counter, value; printf (“Enter value for n:”); scanf (“%d”, &n); value = 1; printf (“current value is %d \n”, value); 4 1 Current value is 1 25

while (counter <= n) { value = 2 * value; Contd… condition counter value n 4 1 Current value is 1 counter = 0; while (counter <= n) { value = 2 * value; printf (“current value is %d \n”, value); counter = counter + 1; } T F 5 1 3 4 2 16 32 4 2 8 Current value is 2 Current value is 4 n = 0 : both 1 and 2 get printed! n = 2: 1, 2, 4, 8 get printed! The error is that n+1 iterations take place. But instead of n+1 values, n+2 values get printed! Current value is 8 Current value is 16 Current value is 32 26

Counter – loop runs till counter reaches its limit. More on Loops Loop execution can be controlled in two ways: counter-controlled and sentinel-controlled. Counter – loop runs till counter reaches its limit. Use it when the number of repetitions is known. Sentinel – loop runs till a certain condition is encountered. For example – a special number is read from the input. Use it when the number of repetitions is a property of the input and not of the problem being solved. 27

Reversing a Number: Methodology Print the reverse of a given integer: E.g.: 234  432 Method: Till the number becomes zero, extract the last digit number modulo 10 make it the next digit of the result multiply the current result by 10 and add the new digit

Termnation condition: Stop when x becomes zero Reversing a Number: Illustration x is the given number y is the number being computed x = 56342 y = 0 x = 5634 y = 0*10 + 2 = 2 x = 563 y = 2*10 + 4 = 24 x = 56 y = 24*10 + 3 = 243 x = 5 y = 243*10 + 6 = 2436 x = 0 y = 2436*10 + 5 = 24365 Termnation condition: Stop when x becomes zero x = x/10 y = y*10 + (x%10)

Remember integer division truncates the quotient Reversing a Number: Program main( ){ int x = 0, y = 0; printf ("input an integer :\n"); scanf ("%d", &x); while (x > 0){ y = y*10 + ( x % 10 ); x = (x / 10); } printf ("The reversed number is %d \n", y); Remember integer division truncates the quotient

Perfect Number Detection Perfect number: sum of proper divisors adds up to the number main ( ){ int d=2, n, sum=1; scanf (“%d”, &n); while (d <= (n/2)) { if (n%d == 0) sum += d; d++; } if (sum == n) printf (“%d is perfect\n”, n); else printf (“%d is not perfect\n”, n); d<n will also do, but would do unnecessary work Perfect numbers upto 1,000,000: 6, 28, 496, 8128 only Exercise: Modify to find the first n perfect numbers 31