0% found this document useful (0 votes)
83 views

C Program Control Switch Case Break 1

The document summarizes activities from a worksheet on selection constructs in C and C++. It includes pseudocode examples for programs that: 1) determine the winner of a game by comparing scores and printing the winner's name and margin of victory, 2) track deposits and withdrawals from a bank account until the balance goes negative and print the final balance, and 3) find the lowest men's and highest women's scores from alternating data entries, stopping when a man's score of 0 is read.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

C Program Control Switch Case Break 1

The document summarizes activities from a worksheet on selection constructs in C and C++. It includes pseudocode examples for programs that: 1) determine the winner of a game by comparing scores and printing the winner's name and margin of victory, 2) track deposits and withdrawals from a bank account until the balance goes negative and print the final balance, and 3) find the lowest men's and highest women's scores from alternating data entries, stopping when a man's score of 0 is read.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

| Main |< C & C++ if and if-else 4 | C & C++ switch-case-break 6 >| Site Index | Download |

C LAB WORKSHEET 8b
C & C++ Selection: The Conditional Operator And switch-case-break Part 5
Items in this page:

1. The ?:, conditional operator.


2. The switch-case-break construct and flowcharts.
3. Activities, questions and answers.
4. Tutorial reference that should be used together with this worksheet are: C & C++ program control 1 and C & C+
+ program control 2.

More Questions and Activities

1. Write a complete working program that will ask for a #include <stdio.h>
person’s name and his/her game score. Then it will ask for a
second person’s name and score. The program will print the int main(void)
winner’s name and also print by how many points that {
person won. // variables to store the scores
int k, k1;
The following is a sample of a pseudocode. It is edited // strings to store names
many times to achieve the desired program output. char name[20] = "Dummy", name1[20] =
"Dummy";
Declare int variables to store the scores // read & store the first name and score
int k, k1; printf("Enter first name: ");
Declare string variables to store the names scanf_s("%s", name, 19);
char name[20] = "Dummy", name1[20] = printf("Enter first score: ");
"Dummy"; scanf_s("%d", &k, 1);
// read & store the second name and score
Read & store the first name and score
printf("Enter second name: ");
printf("Enter first name: ");
scanf_s("%s", name1, 19);
scanf_s("%s", name, 19); printf("Enter second score: ");
printf("Enter first score: "); scanf_s("%d", &k1, 1);
scanf_s("%d", &k, 1); // if k > k1
Read & store the second name and score if(k > k1)
printf("Enter second name: "); // then
scanf_s("%s", name1, 19); printf("The winner is %s with %d point.
printf("Enter second score: "); \n", name, k-k1);
scanf_s("%d", &k1, 1); // else
Do the comparison, which one is larger else
if(k > k1) printf("The winner is %s with %d point.
Print the winner name and the point \n", name1, k1-k);
else return 0;
}
Print the winner name and the point
Program stop.
2. Write a program that will read a float and a character for #include <stdio.h>
each scanf_s(). The character could be d for deposit or w for
withdrawal. Starting with a balance of zero, add the deposits int main(void)
and subtract the withdrawals until the balance becomes {
negative. Then print by how much the balance went float amount, balance=0.0;
negative. The sample input and output are given below. char transaction;

-----------------Output--------------- scanf_s("%f %c", &amount, &transaction,


100.0 d sizeof(float), sizeof(char));
20.0 d if(transaction == 'd')
60.0 w for(;balance >=0;)
200.0 w {
Your account now is -140.00 dollars. balance = balance + amount;
scanf_s("%f %c", &amount, &transaction,
sizeof(float), sizeof(char));
The following is a pseudocode example for this if(transaction == 'w')
question. {
balance = balance - amount;
Declare variables for the amount in float, balance do
in float and transaction code in char types. {
float amount, balance=0.0; scanf_s("%f %c", &amount,
char transaction; &transaction, sizeof(float), sizeof(char));
Read & store the amount and transaction code. balance = balance - amount;
scanf_s("%f %c", &amount, &transaction, sizeof }while(balance >=0);
(float), sizeof(char)); }
Test the transaction code, if ‘d’ it is deposit. }
printf("Your account now is %.2f dollars.\n",
if(transaction == 'd')
balance);
Test the balance so that it is not negative.
return 0;
for(;balance >=0;) }
If the balance is not negative or positive sum-up
the balance.
balance = balance + amount;
And keep reading the next input of amount and
code.
scanf_s("%f %c", &amount, &transaction, sizeof
(float), sizeof(char));
At the same time keep reading the transaction
code for withdrawal, ‘w’. If the transaction code is
‘w’
if(transaction == 'w')
Minus the withdrawn amount to update the
balance.
balance = balance - amount;
Keep reading and storing the withdrawn amount
using the do-while because we need to terminate
the loop without printing the last input. That is
checking the balance for negative at the end of the
loop.
do
{
scanf_s("%f %c", &amount, &transaction,
sizeof(float), sizeof(char));
balance = balance - amount;
}while(balance >=0);
When the balance is negative, stop the loop and
print the negative balance.
printf("Your account now is %.2f dollars.\n",
balance);
Program stop.
3. Men and women are running races. We need to know what #include <stdio.h>
was the lowest men’s score and the highest women’s score.
Data are given so that men’s scores alternate with those of int main(void)
women: first men’s, then women’s. The program stops when {
a time of zero is read for a man’s score. A sample input and int i=0;
output are given below. float man_score[20], women_score[20],
lowest_man, highest_women;
-----------------Output---------------- scanf_s("%f", &man_score[i], sizeof
7.80 (man_score));
5.70 lowest_man = man_score[i];
5.80 scanf_s("%f", &women_score[i], sizeof
8.95 (women_score));
0.0 highest_women = women_score[i];
Lowest men’s: 5.80 for(;man_score[i] != 0.0;)
Highest women’s: 8.95 {
if(man_score[i] < lowest_man)
lowest_man = man_score[i];
The following is a pseudocode example. if(women_score[i] > highest_women)
highest_women = women_score[i];
Declare variables to store men’s and women’s i++;
scores, lowest men’s score and highest women’s scanf_s("%f", &man_score[i], sizeof
score and for the array’s index. (man_score));
int i = 0; if(man_score[i] == 0.0)
float man_score[20], women_score[20], break;
lowest_men, highest_women; scanf_s("%f", &women_score[i], sizeof
Begin reading & storing men’s score in the (women_score));
}
man_score array.
printf("Lowest men's: %.2f\nHighest women's:
scanf_s("%f", &man_score[i], sizeof
%.2f\n", lowest_man, highest_women);
(man_score)); return 0;
Assign the first element to the lowest_man }
variable to do the comparison for the lowest score.
lowest_man = man_score[i];
Begin reading & storing women’s score.
scanf_s("%f", &women_score[i], sizeof
(women_score));
Assign the first element to the highest_women
variable to do the comparison for the highest
score.
highest_women = women_score[i];
Keep reading and storing the next man’s and
women’s scores while man_score[i] != 0.0.
for(;man_score[i] != 0.0;)
{
scanf_s("%f", &man_score[i], sizeof
(man_score));
scanf_s("%f", &women_score[i], sizeof
(women_score));
}
For every array’s element, find the lowest man
and the highest women scores in the for loop.
Assign the highest women score to
highest_women variable and lowest man score to
lowest_man variable. Don’t forget to increment the
index for every iteration.
for(;man_score[i] != 0.0;)
{
if(man_score[i] < lowest_man)
lowest_man = man_score[i];
if(women_score[i] > highest_women)
highest_women = women_score[i];
i++;
scanf_s("%f", &man_score[i], sizeof
(man_score));
scanf_s("%f", &women_score[i], sizeof
(women_score));
}

The loop need to be terminated when the


man_score == 0.0 without reading the next
women score. So we can use a break statement
here.

for(;man_score[i] != 0.0;)
{
if(man_score[i] < lowest_man)
lowest_man = man_score[i];
if(women_score[i] > highest_women)
highest_women = women_score[i];
i++;
scanf_s("%f", &man_score[i], sizeof
(man_score));
if(man_score[i] == 0.0)
break;
scanf_s("%f", &women_score[i], sizeof
(women_score));
}

Print the result of the highest women’s score and


the lowest man’s score.
printf("Lowest men's: %.2f\nHighest women's:
%.2f\n", lowest_man, highest_women);
Program stop.

4. Ty running the following program.

#include <stdio.h>

int main(void)
{
int i;
for(i = 1; 5 - i; i = i + 1)
printf("%d\n", i);
printf("You are coming to the end of the loop\n");
return 0;
}

The loop runs only 4 times and then stops. What is really
happened here in the loop is that 5 – i is not a condition at all, it
is arithmetic expression. How is that interpreted? Whenever
an arithmetic expression evaluates to zero, that expression is
considered to have a false value. Conversely, whenever an
expression is non-zero, it is considered to be true. Hence, for
the first four values of i, 5 – i has a non-zero or a true value.
When i becomes 5, then 5 – i becomes zero, the expression
becomes false and the loop stops.
Writing condition like this takes fewer instruction cycles from
CPU/processor and the code runs faster than the if conditional
operators were used.
The Conditional Operator (?:), ternary

■ Whenever one value has to be assigned to a variable if a certain condition is true and another has to be
assigned to that same variable if it is false, then the conditional operator can be used. Using the
conditional operator will simplify your coding. The following if-else example is converted to using ?: operator.

#include <stdio.h>

int main(void)
{
// initialize with dummy value...
char x = 'n';
printf("Enter 'y' or non-'y': \n");
scanf_s(" %c", &x);
// the following codes can be converted using ?: operator
if(x == 'y')
printf("If 'y', answer is = 1\n");
else
printf("Else, answer is = 0\n");
return 0;
}

A sample input and output are given below.


#include <stdio.h>

int main(void)
{
// initialize with dummy value...
char x = 'n';
printf("Enter 'y' or non-'y': \n");
scanf_s(" %c", &x);
// using ?: operator
(x == 'y') ? printf("If 'y', answer is = 1\n") : printf("Else, answer is
= 0\n");
return 0;
}

From the program example, if x == 'y' is true, the following printf() will be executed.

printf("If 'y', answer is = 1\n")

Otherwise the second printf() will be executed.

printf("Else, answer is = 0\n")

The switch-case-break Statement

■ An organized way to write if statements that depend on the value of one variable is to use the switch-case-
break statement. The following example shows how the if program is converted to using the switch statement.
The breaks are required for all the cases except for the last one. Also the default case is optional.
#include <stdio.h> #include <stdio.h>

int main(void) int main(void)


{ {
char code = 'd'; char code = 'd';
float balance = 0.0, amount = 0.0; float balance = 0.0, amount = 0.0;
printf("Enter your transaction code, d - deposit, w - withdrawal: printf("Enter your transaction code, d - deposit, w -
\n"); withdrawal: \n");
scanf_s(" %c", &code); scanf_s(" %c", &code);
// the following code can be converted to using // switch-case-break statement...
// switch-case-break statement... switch(code)
if(code == 'd') {
{ case 'd':
printf("Your deposit...\n"); {
balance = balance + amount; printf("Your deposit...\n");
} balance = balance + amount;
else if(code == 'w') break;
{ }
printf("Your withdrawal...\n"); case 'w':
balance = balance - amount; {
} printf("Your withdrawal...\n");
else balance = balance - amount;
printf(" %c code not allowed\n", code); break;
return 0; }
} default:
printf("%c code not allowed. Try again!\n", code);
}
return 0;
}
■ A sample input and output are given below.

■ Try building a flowchart for this switch-case-break program example.


More Activities

1. In the following practice, we will use the data in Table 3. We will use the rate in the Table to construct the logic
for determining the correct rate. ‘r’ will stand for “residential”, ‘c’ will stand for “commercial” and ‘u’ stand for “unit”.

Units used Residential Commercial


0 < units <= 200 0.8 0.6
above 200 0.7 0.3

Table 3

Let us first consider the condition for the case where type is
equal to “residential” only. If the type is residential and unit
of consumption are less than or equal to 200, then the rate
is 0.8, according to the Table. If the units are not less than
or equal to 200, then the rate is made equal to 0.7.
Complete the coding for this part of the logic.

if(u <= 200)


rate = 0.8;
else
rate = 0.7;

if(u <= 200)


rate = _________________;
else
rate = _________________;

| Main |< C & C++ if and if-else 4 | C & C++ switch-case-break 6 >| Site Index | Download |

The C Selection if, if-else, if-else-if, break, conditional/ternary operator and switch-case-break: Part 1 |
Part 2 | Part 3 | Part 4 | Part 5 | Part 6

tenouk.com, 2007

You might also like