Académique Documents
Professionnel Documents
Culture Documents
Start
Is it Right or Wrong?
Wrong
End
where statement may be either a single statement or a block of statements. The else clause is optional.
statement sequence
} else {
statement sequence
}
Wrong
Is it Put X (cross) close to mark and dont the add correct to anything score answer ?
Wrong
Give 1-4 points depending on Put X (cross) the answer mark and dont add anything to score Put X (cross) mark and dont add anything to score
End
If else Statements
#include <stdio.h>
main(void) { int magic = 50; int guess; printf("Guess what 2-digit number is stored: "); scanf("%d",&guess);
if(guess == magic) printf("Good Guess!"); else printf("Sorry, try again!"); return 0; }
If else Statements
Start
#include <stdio.h>
printf("Guess what 2-digit number is stored: "); Is it = Display No Yes scanf("%d",&guess); Display Good
Guess!
to 50? Y/N
End
Nested If Statements
One of the most confusing aspects of if statements in any programming language is nested ifs. A nested if is an if statement that is the object of either an if or else. The reason that nested ifs are so troublesome is that it can be difficult to know what else associates with what if.
Nested If Statements
For example: If(x) If(y) print (1); else print (2); To which if does the else refer?
Nested If Statements
In C, the else is linked to the closes preceding if that does not already have an else statement associated with it. In the previous case, the else is associated with the if(y) statement. To make the else associate with If(x) you must use braces to override its normal association:
If(x) { if(y) printf(1); } else printf(2);
Nested If Statements
else is now associated with the if(x) because it is no longer part of the if(y) object block. Because of Cs scope rules, the else now has no knowledge of the statement because they are no longer
If(x) { if(y) printf(1); } else printf(2);
Nested If Statements
#include <stdio.h>
main(void) { int magic = 50; int guess; printf("Guess what 2-digit number is stored: "); scanf("%d",&guess);
if(guess == magic) printf("Good Guess!"); else { printf("Sorry, try again!"); printf("Sorry, Wrong Guess, Please try again!"); if(guess > magic) printf("Try going lower"); return 0; else printf("Try going higher"); } return 0;
} }
Is it = No Display Sorry, Display Good Yes to 50? Try again! Guess! printf("Guess what 2-digit number is stored: "); Y/N
scanf("%d",&guess);
if(guess == magic) printf("Good Guess!"); else { Display Try printf("Sorry, Wrong Guess, Please try again!"); if(guess > magic) printf("Try going lower"); going Lower! End else printf("Try going higher"); } return 0; }
Thank you!