Remember: the best way to learn to code is to write code! So letโs practice our loops. Pick one of the following prompts. And most importantly: have fun! If you get done early, pick another one!
Write a program that prompts the user to enter a positive integer n and then computes the sum of the numbers from 1 through n. For example, if the user enters 5, then your programโs output should be:
Compile and run the code below in your own C environment.
#include <stdio.h>
int main (void){
int n, sum;
printf ("Enter a positive integer: ");
scanf ("%d", &n);
/* add your code here. Be sure to declare any additional variables
you need. */
printf("The sum of the numbers from 1 through %d equals %d.", n, sum);
return(0);
}
Write a program that continuously asks the user to enter a nonzero number and adds up all of the numbers entered. The program should terminate when the user enters a zero and then print out the total sum.
Please enter a number: 5
Please enter a number: 11
Please enter a number: -3
Please enter a number: 0
The numbers you entered add up to 13.
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void){
int n, total;
/* Please add your code here. Be sure to declare
any additional variables you need. */h
printf("\nThe numbers you entered add up to %d.", total);
return(0);
}
Write a program that prompts the user for two numbers p and q, then calculates the greatest common divisor of p and q. You may do so using the "brute force" method: If q\(\leq\)p, for example, you simply check each of the divisors q, q-1, q-2, ..., 1, until you find one that divides both p and q.
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void){
int p, q, divisor;
printf("Please enter two numbers to find the GCD: ");
scanf("%d%d", &p, &q);
/* Please add your code here. Be sure to declare any additional
variables you need. */
printf("The greatest common divisor of %d and %d is %d.", p, q, divisor);
return 0;
}
Write a program that determines whether a number entered by the user is prime (again, you may use the โbrute forceโ method, going through all possible divisors 2, 3, 4, โฆ, n).
Compile and run the code below in your own C environment.
#include <stdio.h>
int main(void){
int number, notPrime;
printf("Please enter a number: ");
scanf("%d", &number);
/* Please add your code here. Be sure to declare any
additional variables you need. */
if (notPrime) {
printf("The number %d you entered is not prime.", number);
} else {
printf("The number %d you entered is prime.", number);
}
}