Lecture05 - Copy
Lecture05 - Copy
University of Ottawa
Winter 2025
In-Class Exercise: Go To Brightspace
Outline
Outline
ASCII Table
char myChar;
scanf("%c", &myChar);
Note
Caution! scanf() is known to be fragile for reading characters.
The char Type
When executing this code, if you hit the ENTER key after
entering the first character for the first call of scanf, the code also
automatically executes the second scanf and the ENTER key (the
character '\n') is read and loaded into variable myChar2.
It is recommended that a line “fflush(stdin);” be added before
every call of scanf. But depending on the OS and compiler, this
may or may not solve the issue.
Later we will introduce better ways to read characters.
The char Type
Coding Demonstration
More on Decision Structures
Outline
switch Statement
switch (I)
{
case CONST1: switch, case, default, and break
DoA; are all keywords.
break; I is an expression that evaluates to an
case CONST2: integer.
DoB; CONST1, CONST2 ... are integer literals.
break; DoA, DoB, ... DoX are each a line of
... code or a block of code.
default: If any of them is a block of code, the
DoX; block needs not to be enclosed by
} curly brackets { }.
Arbitrarily many case’s are allowed.
Note
To implement the desired logic of the switch statement, the break
statements must be included. For historical reasons, if the break
statements are not included, the compiler will consider the code
syntactically correct. In this case, the code will have a strange
behaviour: the code under each case after the true case will be
executed.
Highlight
The switch statement can only be used to compare integer expression
against integer values!
Note
If needed, one can nest if/if-else statement inside a switch statement,
or vice versa.
More on Decision Structures
#include <stdio.h>
int main()
{
int x;
printf("enter 1, 2, or 3\n");
scanf("%d", &x);
switch (x)
{
case 1:
printf("You selected option 1\n");
break;
case 2:
printf("You selected option 2\n");
break;
case 3:
printf("You selected option 3\n");
break;
default:
printf("Invalid selection!\n");
}
return 0;
}
More on Decision Structures
Coding Demonstration