Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming Using C Basic Logic. 2 Contents Conditional programming If statement Relational operators Compound statements Loops While.

Similar presentations


Presentation on theme: "Introduction to Programming Using C Basic Logic. 2 Contents Conditional programming If statement Relational operators Compound statements Loops While."— Presentation transcript:

1 Introduction to Programming Using C Basic Logic

2 2 Contents Conditional programming If statement Relational operators Compound statements Loops While / for If-else / switch

3 3 Conditional Programming So far, our programs have simply – read some data – Calculated a result – Printed the result But this could be done by a programmable calculator The advantage of a computer is that it can make decisions based on the data it receives and take different actions

4 4 Conditional Programming For purposes of illustration, we will assume that our calculation of the price of an item now has to account for the age of the buyer since we offer a seniors discount of 10% This means – We now have to enter the age of the customer – Deduct 10% from the price ONLY if the customer is 65 or older

5 5 The IF Statement To make a decision like this, we introduce a new statement, the IF statement The format of this new statement is – If (some_condition) some_statement This evaluates a condition which is either true or false – If true, the statement is executed – If false, the next statement is executed

6 6 The IF Statement To test for someone’s age being 65 or older we could write if(age >= 65) total = total – (total * 0.1); Conditional expressionIf statement Statement to execute if condition is true Spreading over 2 lines increases readability * See ifdemo.c

7 7 Relational Operators These operators allow us to compare values of variables – >greater than – >=greater than or equal to – <less than – <=less than or equal to – ==equal to – !=not equal to

8 8 Relational Operators Note the similarity of the equality operator – == And the assignment operator – = These are a frequent cause of errors in C programs They do not do the same thing

9 9 Relational Operators The precedence of the relational operators is less than that of the arithmetic operators This means that the expression – X + 1 < y *5 Is equivalent to the expression – (X + 1) < (y * 5)

10 10 A New Cash Register Program main() { int quantity, age; double unit_price, tax, total; printf(“Enter product cost\n”); scanf(“%lf”, &unit_price); printf(“Enter quantity purchased\n”); scanf(“%d”, &quantity); printf(“Enter customer age\n”); scanf(“%d”, &age); total = quantity * unit_price; if(age >= 65) total = total – (total * 0.1); tax = total * 0.14; total = total + tax; printf(“The amount due is %d\n”, total); }

11 11 Expressions An expression is a part of a statement which can be evaluated to yield a value – total = total – (total * 0.1); – This contains several expressions total 0.1 total * 0.1 total – (total * 0.1)

12 12 Statements A statement is like a sentence in English A statement can contain several expressions The if statement is followed by one statement which is executed if the condition is true What happens if we want to execute more than one statement if the condidtion is true?

13 13 Compound Statements The solution to this is to combine several statements into a compound statement A compound statement – Starts with { – Contains zero or more statements – Ends with } – Can be used whereever a simple statement is expected – Is called a code block

14 14 Compound Statements We could rewrite our code like this We do not need a semicolon at the end of a code block if(age >= 65) { double discount = total *0.1; total = total – discount; }

15 15 Loops Another way of programming a computer is to get the computer to perform the same series of steps again and again This type of a programming construct is called a loop Loops normally some way to exit them to avoid performing the same series of operations indefinitely

16 16 The While Statement The while statement is one of the simplest ways to create a loop The format is similar to the if statement while(age < 65) scanf(“%d”, &age); Conditional expressionwhile statement Statement to execute while condition is true Spreading over 2 lines increases readability * See whiledemo.c

17 17 The While Statement The while statement executes the statement after it as long as the condition is true When the condition becomes false, the next statement is executed Something in the statement executed usually alters one or more of the variables in the conditional statement so that the loop will not continue forever While loops usually use compound statements

18 18 A Guessing Game main() { int guess, counter; counter = 1; printf(“Guess a number: “); scanf(“%d”, &guess); while(guess != 42) { if(guess > 42 ) printf(“Too high !”); if(guess < 42) printf(“Too low !”); printf(“Try again: “); counter = counter + 1; } if(counter == 1) printf(“WOW, you are either very lucky or you CHEAT!\n”); if(counter != 1) printf(“You win in %d tries.\n”, counter); }

19 19 A Guessing Game This combines a whie loop with two nested if statements within it It uses the same statements we have discussed but brings several statements together This is how we write more complex programs!

20 20 Compound Conditions Sometimes checking just one comparison in a condition is not enough Suppose we wanted to write different messages based on how many guesses someone made – If they make 2 to 5 guesses tell them they are good – If they make 5 to 15 guesses, thell them they are average – If they make 16 to 100 guesses, ask why it took so long

21 21 Compound Conditions We can combine 2 tests into one condition using – &&and – ||or For example, to tell someone they are good we would use if(counter >= 2 && counter < 5) printf(“Very good, you got it in %d turns\n”, counter);

22 22 AND And is indicated by the symbol && A single & does something different, so be careful ! When you AND two values together the result is true – If the first value is true AND the second is true

23 23 OR OR is indicated by the symbol || A single | does something different, so be careful ! When you OR two values together the result is true – If the first value is true OR the second is true

24 24 Truth Tables AND T F TF TF FF OR T F TF TT TF * See andordemo.c

25 25 Precedence Both && and || have higher precendence than the relational operators Therefore – x < y && x < z Can be rewritten as – (x < y) && (x < z)

26 26 Improved Guessing Game main() { int guess, counter; counter = 1; printf(“Guess a number: “); scanf(“%d”, &guess); while(guess != 42 && counter < 100) { if(guess > 42 ) printf(“Too high !”); if(guess < 42) printf(“Too low !”); printf(“Try again: “); counter = counter + 1; }

27 27 Improved Guessing Game if(counter == 1) printf(“WOW, you are either very lucky or you CHEAT!\n”); if(counter >= 2 && counter < 5) printf(“Very good, you got it in %d turns.\n”, counter); if(counter >= 5 && counter < 15) printf(“You win in %d turns, an average performance.\n”, counter); if(counter >= 15 && counter < 100) printf(“Duh, it took you %d tries to get it!\n”, counter); if(counter == 100 && guess == 42) printf(“You got it in the nick of time.\n”); if(guess != 42) printf(“You lose\n”); }

28 28 The If/Else Statement While everything can be programmed with an if and a while, it is not always convenient We can introduce new statements that make programming easier Previously we used if(guess > 42 ) printf(“Too high !”); if(guess < 42) printf(“Too low !”);

29 29 The If/Else Statement This is really a case where either one test is true or the other is true This can be rewritten using an if/else if(guess > 42) printf(“Too high”); else printf(“Too low”);

30 30 The If/Else Statement The if/else – Evaluates a single condition – If it is true, it executes the first part – If it is false, it executes the second part This reduces the number of comparisons, making the program faster It also makes the program easier to write * See ifelsedemo.c

31 31 The Do/ While Statement The while statement tests its condition at the start of the loop Sometimes, you want to test the condition at the end of the loop You can do this with the do/while statement

32 32 The Do/ While Statement The statement has the format do statement while (some_condition) Since the test to see if the loop should repeat is performed at the end of the loop, the loop executes at least once The statement could be a code block

33 33 The Do/ While Statement One common problem is to read data until a special value is found The following reads data until a zero is entered int n; printf(“enter a number between 1 and 5, zero to stop”); scanf(“%d”, &n); while(n > 0) { printf(“you entered %d\n, enter another”, n); scanf(“%d”, &n); }

34 34 The Do/ While Statement This code requires that the scanf be performed twice The code can be simplified like this int n; scanf(“%d”, &n); do { printf(“enter a number between 1 and 5, zero to stop”); scanf(“%d”, &n); printf(“You entered %d\n”, n); } while (n >= 1 && n <= 5)

35 35 DeMorgan’s Law We used the expression – (n >= 1 && n <= 5) To continue the loop while the number was in the range 1 to 5 What condition would we use to continue the loop for all numbers outside the range 1 to 5?

36 36 DeMorgan’s Law DeMorgan’s law states that to reverse a compound condition we must – Reverse all of the comparisons – Change all ANDs to ORs and vice versa This gives us the reverse expression as – (n 5) * See demorgandemo.c

37 37 The For Statement The while loop requires that you – Initialize a variable to control how many times the loop repeats – Alter the variable every time through the loop – Write a condition to check the value of the variable every time the loop is about to repeat Since this is a common way to make a loop, there is a special loop to do just this

38 38 The For Statement The for statement is a loop which – Sets an initial value for a variable – Checks the value to see if the loop should repeat – Alters the value at the end of the loop The format of the for statement is – for(initial; condition; update) statement; Where – Initial sets the initial value of the variable – Condition tests to see if the loop should continue – Update changes the value of the variable at the end of the loop

39 39 The For Statement A simple loop to print the numbers from 1 to 10 looks like this int i; for(i = 1; i <= 10; i=i+1) printf(“%d\n”, i); This behaves just like our while loop, but is easier to write * See fordemo.c

40 40 The Switch Statement The if statement is suitable for executing a statement if a variable has a specific value What if we want to do different things based on the value of a variable? This is what the switch statement does

41 41 The Switch Statement The format of the switch statement is switch(expression) { case constant1: zero or more statements case constant2: zero or more statements … default: zero or more statements }

42 42 The Switch Statement The switch statement – Evaluates the expression – Compares the expression value to each of the constants in the cases – Executes the statements, starting with the first case matched – Matches only one case – If no cases are matched, then the default is matched, if it is present

43 43 The Switch Statement If a case is matched, it executes statements right into the next case without stopping If we want it to stop at the end of the case, the last statement in the case must be – break; This causes it to leave the current switch statement and to resume executing the statements after the switch

44 44 The Switch Statement This could be used to build a simple menu printf(“enter 1 to types your name, 2 to type your age, 3 to type your address, any other number to stop\n”); scanf(“%d”, option); switch(option) { case 1: scanf(“%s”, name); break; case 2: scanf(“%d”, &age); break; case 3: scanf(“%s”, address); break; }

45 45 Terminology Any statement which allows you to execute one of several alternatives is a selection Any structure which allows a series of statements to be repeated is called iteration

46 46 Goto, Break and Continue You might read books that use these These statements make programs – Hard to read – Hard to debug We use the break only in the switch Avoid the rest until you become an advanced programmer


Download ppt "Introduction to Programming Using C Basic Logic. 2 Contents Conditional programming If statement Relational operators Compound statements Loops While."

Similar presentations


Ads by Google