Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Worksheet

Module 2A – C Control Structures

GENERAL INSTRUCTIONS:
1. Copy each of the following exercises and save them with the provided filename formats (for organization). Familiarize
yourselves with what you are typing and try to experiment on the provided exercises.
2. You are not required to submit the source codes you will be creating in this worksheet. Store these files in you own
folders for your review.
3. Create a document named SURNAME_ws2.docx, which will contain one screenshot of the interface of each exercise
programs during execution (basically, the command prompt), and your answers to the debugging exercises. Upload
it in the corresponding submission bin in our course page.

Exercise 2-1: if-else selection structures

/*
Save this file as SURNAME_ex2-1.c

This exercise introduces using the if-else if selection structures.


*/

#include<stdio.h>
#include<ctype.h>

int main() {
int grade;

printf("Input a grade from 0 to 100: ");


scanf("%d", &grade);
printf("%d", grade);

if((grade < 0) || (grade > 100)) {


puts("Invalid input. Bye");
return 1;
}

if(grade >= 92) {


puts("Your grade is a 1.00");
} else if(grade >= 88) {
puts("Your grade is a 1.25");
} else if(grade >= 84) {
puts("Your grade is a 1.50");
} else if(grade >= 80) {
puts("Your grade is a 1.75");
} else if(grade >= 76) {
puts("Your grade is a 2.00");
} else if(grade >= 72) {
puts("Your grade is a 2.25");
} else if(grade >= 68) {
puts("Your grade is a 2.50");
} else if(grade >= 64) {
puts("Your grade is a 2.75");
} else if(grade >= 60) {
puts("Your grade is a 3.00");
} else if((grade >= 0) || (grade < 60)) {
puts("Your grade is a 5.00");
} else {
puts("Bye bye");
return 2;
}

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Exercise 2-2: switch selection structure

/*
Save this file as SURNAME_ex2-2.c

This exercise introduces using the switch selection structure.


*/

#include<stdio.h>

int main() {
int int1, int2, result, choice;

printf("This program is a menu-type calculator\n");


printf("Enter the first integer: ");
scanf("%d", &int1);
printf("Enter the second integer: ");
scanf("%d", &int2);
printf("\n");

puts("What operation would you like to do?");


puts("1. Addition");
puts("2. Subtraction");
puts("3. Multiplication");
puts("4. Division");
puts("5. Exit");
printf("Your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
result = int1 + int2;
break;
case 2:
result = int1 - int2;
break;
case 3:
result = int1 * int2;
break;
case 4:
result = int1 / int2;
break;
case 5:
puts("Bye!");
return 0;
break;
default:
puts("Invalid input. Bye!");
return 1;
break;
}

printf("The result is %d\n", result);

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Exercise 2-3: do-while and while statements and additional input validation

/* This exercise introduces using the do-while and while repetition structures.
As well as additional methods for input validation.
Save this file as SURNAME_ex2-3.c */

#include <stdio.h>
#include <stdlib.h>

int main() {
int input, tmp;
double factorial;

factorial = 1;

printf("This program computes the factorial of your input.\n");


printf("Please enter any positive integer: ");

// This block of code does:


// 1. Request the input of the user through scanf
// 2. Validate the input of the user
// 3. Continuously request the input of the user if the previous input was invalid
do {
// The inputstatus variable is declared within the do-while scope.
// It is automatically destroyed after the do-while scope and can no longer be accessed then.
int inputstatus;

// scanf() actually returns the number of items in the argument list successfully matched.
inputstatus = scanf("%d", &input);

// fflush() removes everything left in the input stream


fflush(stdin);

// Reject the input if its value is not a positive or if it was not properly matched by scanf()
if(!(input > 0) || (inputstatus == 0)) {
printf("\nError! Invalid input.\nPlease enter any positive integer: ");
input = 0;
}
} while(!(input > 0));

// Save the value of input to another variable so we can display the original value later on
tmp = input;

// Keep multipying factorial by tmp and subtract 1 from tmp each time until tmp = 0
// Note that factorial is initialized to have a value of 1 first
while(tmp > 0) {
factorial *= tmp--;
}

printf("The factorial of %d is %lg", input, factorial);

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Exercise 2-4: for statement

/*
Save this file as SURNAME_ex2-4.c

This exercise introduces using the for repetition structures


*/

#include <stdio.h>
#include <math.h>

int main() {
int input, i, prime;

prime = 1;

printf("This program computes if your input is prime or not.\n");


printf("Please enter any positive integer: ");

do {
int inputstatus;

inputstatus = scanf("%d", &input);

fflush(stdin);

if(!(input > 0) || (inputstatus == 0)) {


printf("\nError! Invalid input.\nPlease enter any positive integer: ");
input = 0;
}
} while(!(input > 0));

for(i = 2; i <= sqrt(input); i++) {


if(input % i == 0) {
prime = 0;
break;
}
}

if(prime) {
printf("The number %d is prime!", input);
} else {
printf("The number %d is composite!", input);
}

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Exercise 2-5: Basic sentinel-controlled loop

/*
Save this file as SURNAME_ex2-5.c

This exercise introduces basic sentinel-control loops


*/

#include <stdio.h>

int main() {
int grade, students = 0;
double result = 0;

printf("This program computes for the average grade of a number of students\n\n");

do {
printf("Enter grade of student %d or enter -1 to end input: ", students+1);
scanf("%d", &grade);
if(grade != -1) {
result += grade;
students++;
}
} while(grade != -1);

if(students > 0) {
printf("The average of %d students is %.2lf", students, result/students);
}

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Exercise 2-6: break and continue statements

/*
Save this file as SURNAME_ex2-6.c

This exercise introduces the break and continue statements


*/

#include<stdio.h>

int main() {

int input;

printf(“Enter an integer:”);
scanf(“%d”,&input);

do{
if(input<0 || input>10)
break;
if(input==4){
input++;
continue;
}
printf(“%d\n”,input);
input++;
} while(input<=10);
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Debugging Exercises

Selection Control Structures


1. Find the error (s) in each of the following program segments. Write the corrected statements and
concisely explain how you corrected each.

a) if (sales => 5000)


puts("Sales are greater than or equal to $5000")
else
puts("Sales are less than $5000)

b) The following code should print whether a given integer is odd or even:
switch (value) {
case (value % 2 == 0):
puts("Even integer");
case (value % 2 != 0):
puts("Odd integer");
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

2. In the following code, without adding new statements,

a. Correct any errors that would prevent the program from compiling or running.

#include<stdio.h>

int main
{
int num1, num2;
int found = 0;

puts("Enter two integers:");


scanf(“%d %d, &num1, &num2);

puts(“”);

found = num1>num2;

if (found
switch (num1 % num2);
{
case 0:
num2 = num1 / 2;
break;
case 1:
num1 = num2 / 2;
break;
default:
num1 = num1 / num2;
num2 = num1 * num2;
};
else
{
num1 = num1 - num2;
num2 = (num1 + num2) / 10;
}

printf(“%d %d\n”, num1, num2);

return;
}

b. After correcting the code, what is the output if the input is:
i. 16 and 5?
ii. 13 and 27?

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

Repetition Control Structures


3. Find the error (s) in each of the following program segments. Write the corrected statements and concisely
explain how you corrected each.

a) The following code should solve for the product of all integers from 1 to 10.
int x = 1, product = 0;

while ( x <= 10 ); {
product *= x;
++x;
}

b) The following code should output all multiples of 3 from 1 to 100.


for (int x = 3; x <= 100; x%3 == 0; x++ )
printf("%d\n", x);

4. The following program is designed to input two numbers and output their sum. It asks the user if he/she
would like to run the program. If the answer is Y or y, it prompts the user to enter two numbers. After
adding the numbers and displaying the results, it again asks the user if he/she would like to add more
numbers. However, the program fails to do so. Correct the program so that it works properly.

#include<stdio.h>

int main ()
{
char response;
double num1, num2;

puts(“This program adds two numbers:”);


puts(“Would you like to run the program: (Y/y)”);
scanf(“%c”, &response);
puts(“”);

while (response == ‘Y’ && response == ‘y’)


{
printf(“Enter two numbers: ”);
scanf(“%lf %lf”, &num1, &num2);
puts(“”);

printf(“%.2lf + %.2lf = %.2lf\n”, num1, num2, num1–num2);

puts(“Would you like to add again: (Y/y)”);


scanf(“%c”, &response);
puts(“”);
}

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

5. The do…while loop in the following program is supposed to read some numbers until it reaches a
sentinel (in this case, -1). It is supposed to add all the numbers except for the sentinel. If the data looks
like:
12 5 30 48 -1
the program does not add the numbers correctly. Correct the program so that it adds the numbers
correctly.
#include<stdio.h>

int main()
{
int total = 0, count = 0, number;

do
{
scanf(“%d”, &number);
total = total + number;
count++;

} while (number != -1);

printf(“The number of data read is %d\n”, count);


printf(“The sum of the numbers entered is %d\n”, total);

return 0;
}

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

BONUS KNOWLEDGE

Conditional Operator ( ? : )
▪ A more concise way of writing if…else statements.
▪ C’s only ternary operator – takes three operands. These together with the conditional operator form a
conditional expression.

SYNTAX
expression1 ? expression2 : expression3

▪ If expression1 evaluates to true or a nonzero integer, the result of the conditional expression is
expression2. Otherwise, the result is expression3.

Examples:

Top-Down, Stepwise Refinement


▪ Essential to development of well-structured programs.
▪ Begins with pseudocode representation of the top – a single statement that conveys the program’s
overall function:

We will use Example 2A-10b as example

▪ First Refinement – divide the top into series of smaller tasks and list these in the order in which they
need to be performed.

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II


Worksheet
Module 2A – C Control Structures

▪ Second Refinement – commit to specific variables.

▪ This refinement process is stopped when the pseudocode algorithm is specified in sufficient detail for
you to be able to convert into a source code.

CE 25 – MATHEMATICAL METHODS IN CIVIL ENGINEERING II

You might also like