Exercises
Concept Questions
-
Explain the difference between using the conditional operator as an expression versus using it as a control flow statement. Provide an example of correct usage of the
?:operator and an example of incorrect usage. -
Given the following code snippet, identify what the output will be and explain why the conditional operator is or is not appropriate here:
int x = 5;
int y = 10;
int max = (x > y) ? x : y;
printf("Maximum: %d\n", max); -
Describe the fall-through behavior in switch statements. Why is the
breakstatement important, and what happens if it is omitted? -
Explain the relationship between array names and pointers in C. Why can an array be passed to a function that expects a pointer parameter?
-
Consider the following program:
#include <stdio.h>
void printSize(int arr[]);
int main(void)
{
int myArray[50];
printf("In main: sizeof(myArray) = %lu\n", sizeof(myArray));
printSize(myArray);
return 0;
}
void printSize(int arr[])
{
printf("In printSize: sizeof(arr) = %lu\n", sizeof(arr));
}What will the output be? Explain why the two
sizeof()calls return different values. -
You are writing a function to find the maximum value in an array of integers. Why is it necessary to pass the number of values in an array as a separate parameter rather than relying on
sizeof()to determine it?
Walkthrough
Part a) Using tables and diagrams to track your variables and function calls, show how you would go through the execution of this program.
Part b) What is the exact output of the following program?
#include <stdio.h>
int main(void)
{
int number = 256421;
char curr;
while(number > 0){
curr = number%10;
number = number/10;
switch(curr){
case 1:
printf("c");
break;
case 2:
printf("o");
case 3:
printf("n");
break;
case 4:
printf("d");
break;
case 5:
printf("t");
default:
printf("i");
}
}
printf("%s\n",15 > 13?"al":"s");
return 0;
}
Programming
a) Demonstrate the use of a switch statement by using it to implement a function named getGrade that accepts a numeric score (0-100) and prints the corresponding letter grade using the following scale:
- 90-100: A+
- 80-89: A
- 70-79: B
- 60-69: C
- 50-59: D
- Below 50: F
b) Write a function named getDaysInMonth that accepts a month number (1-12) and a year, and returns the number of days in that month. Account for leap years (a year is a leap year if it is divisible by 4, except for years divisible by 100 unless also divisible by 400). Use a switch statement.
c) Write a function named printOddEven that is passed an array of integers and the number of values stored in the array. Function prints the value of each element and whether it is odd or even in the form:
array[<idx>] = <number> which is <odd/even>
For example if your array was: 2 your function would print:
array[0] = 1 which is odd
array[1] = 5 which is odd
array[2] = 2 which is even