|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/midtermSol/mtP1sol.txt
This is just the code for the solutions in one text file.
/*
1. Give me a complete program that will print the phrase "I will pass this class."
and then a newline to the terminal.
*/
#include <stdio.h>
int main(){
printf("I will pass this class\n");
return 0;
}
/*
2.
Give me code (not a complete program) for a loop that will read integers from user input
and will accumulate a sum of all positive even numbers. Terminate that loop when a
non-integer is read and output the sum.
You must declare all variables used in the loop, initialize variables when necessary.
Hint: You will want to set up your loop so that it will run as long as scanf is still
reading integers. Read the C Lesson on the class website if you're not clear on this.
*/
int sum = 0, n;
while (scanf("%d", &n) == 1){
if(n <= 0) continue;
if(n % 2 == 0)
sum = sum + n;
}
printf("sum = %d\n", sum);
/*
3. Write a function named isPrime that takes in a single integer,and returns 1 if the number is prime, and
0 if it isn't. If the user enters a 1 or less, have the function return 0
Hint: Recall that Prime Numbers are numbers that have only 2 factors: 1 and themselves. I
suggest using a loop going from 2 to (but not including) n and check each number if n % i == 0
(assuming we're using i as the counting variable). If that statement is true, then we know that
n isn't prime, so we can go ahead and return 0. If the loop is allowed to completely finish, then
we were unable to find a number that divides n, so the number must be prime. If that happens, we
return 1.
*/
int isPrime(int n){
if(n <= 1) return 0;
for(int i = 2; i < n; i++){
if(n % i == 0)
return 0;
}
return 1;
}
/*
4.
Consider the following array declaration:
int numbers[64];
Assume that the array has been filled with integers. Give me code that sets up a loop that will calculate the
average of all the values in that array, then output the average once the loop finishes.
You must declare all variables (other than the already-declared array) used in the loop, initialize variables when necessary.
You can treat the average as an integer number.
Hint: If you don't remember, you get the average by dividing the sum of all the numbers by the number of elements.
*/
int sum = 0, avg;
for(int i = 0; i < 64; i++){
sum = sum + numbers[i];
}
avg = sum / 64;
printf("Average value: %d\n", avg);
/*
5. Write a function named charFreq that takes in a character array and a single character, and returns
an integer that tells us how many times that character appears.
Hint: This is along the same lines as the myStrlen in the jun22 directory and the charExists in the
jun15 directory of the in-class code.
*/
int charFreq(char s[], char c){
int count = 0;
for(int i = 0; s[i] != '\0'; i++){
if(s[i] == c)
count++;
}
return count;
}
|