I am working in an assignment for my intro to programming class.
Here is what my professor is asking:
Change the program without adding another loop, so it determines if the grade entered is valid, and if not, display an error message and keep asking until a valid grade is entered. Change the program, so it counts how many grades scored A, B, C, D, and F. Do NOT use stacked if or if-else constructs. Do NOT use the else if format. Output a table of the count of how many there are for each letter grade.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
/*Ask the user to enter 10 test scores.
The pass mark is 70%.
Calculate the average score, and count how many
of the students have passed the test.
*/
#define SCORES_COUNT 10
#define BAD_SCORE 60
#define PASSING_SCORE 70
#define GOOD_SCORE 80
#define EXCELLENT_SCORE 90
int main()
{
int scores[SCORES_COUNT];
int i, sum = 0, sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0;
for (i = 0; i < SCORES_COUNT; i++)
{
printf("Enter score for student %i: ", i + 1);
scanf("%i", &scores[i]);
if (scores[i] > 100 || scores[i] < 0)
{
printf("\n\tERROR: Invalid number! Enter a score above zero and below one hundred!\n\n");
printf("Enter score for student %i: ", i + 1);
scanf("%i", &scores[i]);
}
}
for (i = 0; i < SCORES_COUNT; i++)
{
if (scores[i] >= EXCELLENT_SCORE)
{
sum++;
}
if (scores[i] >= GOOD_SCORE && scores[i] < EXCELLENT_SCORE)
{
sum1++;
}
if (scores[i] >= PASSING_SCORE && scores[i] < GOOD_SCORE)
{
sum2++;
}
if (scores[i] >= BAD_SCORE && scores[i] < PASSING_SCORE)
{
sum3++;
}
if (scores[i] < BAD_SCORE)
{
sum4++;
}
}
printf("\nGrades Distribution\n");
printf("\nA: %i", sum);
printf("\nB: %i", sum1);
printf("\nC: %i", sum2);
printf("\nD: %i", sum3);
printf("\nF: %i\n", sum4);
system("pause");
return 0;
}
The program works fine, but my teacher told me to not use stacked if or if-else constructs. And since I am a beginner that is the only way I know how to do it.
Can somebody please tell me how can I change all the if constructs, or how can I have the same result without using any if constructs?
Related
First I have to input N, N becomes the first number to be checked.
Input: 79
Output should be: 537.70.
int sum=0;
while(1)
{
scanf("%d", &n);
if(n>=10 && n<80)
{
break;
}
printf("New output:\n");
}
for(i=n;i<=1000;i++)
{
if(i%2==0 && i%6!=0 && i%17!=0)
{
sum+=i;
}
I didnt put (float)sum/N to get average because I'm doing something wrong with sum.
More input output:
Input: 10 Output: 505.21
Input: 44 Output: 521.18
As well as keeping a 'running sum', you also need to keep a count of how many numbers were used, so you can properly calculate the average:
#include <stdio.h>
int main(void)
{
int n;
printf("Enter start number: ");
scanf("%d", &n);
int sum = 0, count = 0;
for (int i = n; i <= 1000; ++i) {
if (!(i % 2) && (i % 6) && (i % 17)) {
sum += i;
++count;
}
}
printf("Average is: %.2f\n", (double)sum / (double)count);
return 0;
}
Input: 79
Output should be: 537.70.
Are you sure about this value? I get 538.70 - but I get the given values for the other test cases you cite.
Is there any way to write this program by only using if-else, else if statements instead of using while.
And I also want all the inputs just in one line, instead of
enter the number1:
enter the number2:
enter the number3:
enter the number4:
enter the number5:
it should be like
Enter 5 numbers: _ _ _ _ _
And when I write the same largest number twice, I want this program to show me the largest number as the second-largest number, too.
For example:
Enter 5 integers: -88 53 41 53 -17
The largest one is: 53
The second largest one is: 53
53 is the multiple of 53
53 and 53 is equal to each other.
53 is an odd number.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sayi = 0;
int sayac = 1;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
//ilk sayinin en buyuk oldugunu kabul ediyoruz.
int enbuyuk = sayi;
int ikinci_buyuk = sayi;
while (sayac != 5)
{
sayac++;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
/*kitapligi ilk sayinin en buyuk oldugunu farz ediyor
* eger ikinci sayi daha buyukse buyuk olanın yerini alacak
* ayrica ikincisinide kontrol edecek
*/
if (sayi > enbuyuk)
{
ikinci_buyuk = enbuyuk;
enbuyuk = sayi;
}
else if (sayi < enbuyuk)
{
// This to avoid if numbers are arranges descending
if (sayac == 2)
{
ikinci_buyuk = sayi;
}
else if (sayi > ikinci_buyuk)
{
ikinci_buyuk = sayi;
}
//This to avoid if the user entered two equal numbers
else if (enbuyuk == ikinci_buyuk)
{
ikinci_buyuk = enbuyuk;
}
}
}
printf("sayac: %d\n", sayac);
printf("En buyuk sayi: %d\n", enbuyuk);
printf("İkinci en buyuk sayi: %d\n", ikinci_buyuk);
if (enbuyuk % ikinci_buyuk != 0)
{
printf("%d %d nin tam kati degildir. is not the multiple of", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d %d nin tam katidir. is the multiple of", enbuyuk, ikinci_buyuk);
}
if (enbuyuk != ikinci_buyuk)
{
printf(" %d ve %d birbirine esit degildir. not equal each other", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d ve %d birbirine esitir. equal each other", enbuyuk, ikinci_buyuk);
}
if (enbuyuk % 2 != 0)
{
printf("%d tek sayidir. odd number", enbuyuk);
}
else
{
printf("%d cift sayidir.even number", enbuyuk);
}
system("pause");
return 0;
}
From the title of your question:
if-else are a conditional code flow structure without any repetition. Without any other instruction (like goto for example) you can't make it a loop like while.
But I think this is not the core of your question. You seem to want to read 5 numbers and check them. For now you do this in a loop and you like to replace that loop with something else.
You can print the one and only prompt and then call a function for each of the 5 numbers to check them.
Since your variables are not translated and your intend is not clear, I'll leave the code inside the function as an exercise for you.
printf("Enter 5 integers: ");
for (int i = 1; i <= 5; ++i)
{
readnumber(/* you might need arguments */);
}
The function will read and check one number. scanf() will read just one number and leave the remainder of the input line for some next call.
void readnumber(/* see above */)
{
if (scanf("%d", &number) == 1)
{
/* handle the number */
}
else
{
/* handle the scan error */
}
}
You can read 5 numbers simply by prompting with a single printf() and reading into 5 variables, or 5 array elements with a single scanf():
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a[5];
int first, second, i, j;
printf("Enter 5 numbers: ");
if (scanf("%d%d%d%d%d", &a[0], &a[1], &a[2], &a[3], &a[4]) != 5) {
printf("Invalid input\n");
return 1;
}
/* I cannot adapt the rest of the code because I cannot understand your language */
/* Here is my quick implementation from the desired output */
/* select the 2 largest numbers */
for (i = 0; i < 2; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] < a[j]) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
first = a[0];
second = a[1];
printf("The largest one is: %d\n", first);
printf("The second largest one is: %d\n", second);
if (second != 0 && first % second == 0)
printf("%d is a multiple of %d\n", first, second);
if (first == second)
printf("%d and %d are equal\n", first, second);
if (first % 2 != 0)
printf("%d is an odd number.\n", first);
return 0;
}
I'm a beginner C programmer and a college freshman.
I need a little help here with a test i'm working on here.
I want to make a nested loop that shows a sorted number. Sorta like this:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
22 23 24 25 26 27 28
... ... ... and so on, depending the limit of rows you input
I already tried to make a crude trial-and-error test code:
int i;
int j;
int limit;
int number1 = 1;
int number2 = 3;
int spesial = 0;
printf("Input limit : ");
scanf("%d", &limit);
for (i=1;i<=limit;i++)
{
for(j=1;j<=i;j++)
{
if (i%2==0)
{
printf("%d ", number2);
number2--;
}
else
{
printf("%d ", number1);
}
number1++;
}
if (i%2==0)
{
number2=(i*6)-i+(spesial*1);
spesial+=1;
}
printf("\n");
}
I managed to make it sorted to the 7th rows, but the rest are not..
help please...
I want to know if we could actually control the position of the output without sorta crude our way like this.
Also, sorry for my English... I'm not really from an English speaking country and this is my first time posting/question in this site.
Thank you for reading this lengthy question and I hope you have a good day and good night.
https://ideone.com/yCxpHo:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int rows;
int i, j;
int n = 0;
printf ("How many rows do you want? ");
if (scanf("%d", & rows) != 1 || rows < 1) return EXIT_FAILURE;
printf ("\n");
for (i = 1; i <= rows; ++ i) {
for (j = 0; j < i; ++ j) {
printf ("%4d", n + (i % 2 == 0 ? i - j : j + 1));
}
printf ("\n");
n = n + i;
}
return EXIT_SUCCESS;
}
It can be more convenient to create another function that will calculate the biggest number of a row (I called it lineMax).
int lineMax(int num){
int cnt=0;
for (int i=1;i<=num;i++)
cnt+=i;
return cnt;
}
void main(){
int i,j,limit;
printf("Input limit : ");
scanf("%d", &limit);
for(i=1;i<=limit;i++){
if(i%2==0){ //right to left
for(j=lineMax(i);j>=lineMax(i-1)+1;j--)
printf("%d ",j);
}
else{ //left to right
for(j=lineMax(i-1)+1;j<=lineMax(i);j++)
printf("%d ",j);
}
printf("\n");
}
}
You are making a lot of special cases with number1, number2 and special. This will not work for bigger numbers.
One way is to calculate count which will give you the value to start from in each loop of j. count += i and then every time print count -j
count = 0;
for (i=1;i<=limit;i++)
{
count += i;
for(j=0;j< i;j++)
{
printf ("%d ",count-j);
}
printf("\n");
}
for some reason I am unable to print out "* " in my program. I want to print out * if the condition is met. the condition is if the rainfall that day is greater than the average.
under the mean column, i am getting weird symbols. i tried debugging to decimals and get -112 for ascii. i dont understand but i tried researching!
I am new to C so please be understanding. Just learned like 2 days ago!!.
Here is my code :
//Assignment one 9/20/2018
//Anthony Lomaistro and David Luong
//luongd5#student.lasalle.edu
//lomaistroa1#student.lasalle.edu
#include <stdio.h>
main() {
int n = 0; //counters for the loops
int x = 0; // counter for the loops
int counter = 0; // counter whenever i need to keep track of increments
int days_input = 0; // how many days we are keeping track of
int number_of_days = 0;
double rainfall_input = 0;
double rainfall_amount = 0; // how much rainfall per day
double rainfall_average = 0; // average of rainfall
double rainfall_total = 0;
double rainfall_counter = 0; // count how many days it rained above the average
int correct = 0;
double rainfall_array[50];//array that contains the user input
char rainfall_condition[50]; // array that contains the *
double sum = 0;
double average = 0;
double percent_days = 0; //rainfall % above average
double valid = 0;
double valid2 = 0;
printf("Welcome to Lomaistro and Luong's Rainfall Program \n");
printf("How many days would you like to keep track of? Please enter a value between 1 and 50: #%d:", n + 1);
//printf(number_of_days);
while (valid == 0) {
scanf_s("%d", &number_of_days);
if ((number_of_days > 50) || (number_of_days <= 0)) { // come back to this, this doesnt do anytihng
printf("Invalid value, please enter in a day that is between 1 and 50 \n");
}
else {
valid = 1;
}
}
//getting the user to enter in the rainfall
for (x = 0; x < number_of_days; x = x + 1) {
valid2 = 0;
while (valid2 == 0) {
printf("Enter rainfall (in inches): ");
scanf_s("%lf", &rainfall_amount);
if ((rainfall_amount >= 0) && (rainfall_amount <= 10)) {
valid2 = 1;
rainfall_array[x] = rainfall_amount;
}
else
printf("Please enter in a valid rainfall amount between 1 and 10");
}
}
//computing average
for (n = 0; n < number_of_days; n = n + 1) {
sum += rainfall_array[n];
average = sum / number_of_days;
}
printf("Mean daily rainfall(in inches): %lf", average);
//seeing if the * should be the array or not
for (n = 0; n < number_of_days; n = n + 1) {
if (rainfall_array[n] > average) {
rainfall_condition[n] = "*";
rainfall_counter = rainfall_counter + 1;
}
else
rainfall_condition[n] = "empty";
}
// print out the thing
printf("\n Days \t Amount \t >Mean \n");
printf("==============================\n");
for (n = 0; n < number_of_days; n = n + 1) {
printf("%d \t %f \t %c \n", n + 1, rainfall_array[n], rainfall_condition[n]);
}
percent_days = rainfall_counter / number_of_days;
percent_days = percent_days * 100;
printf("Number of days that rained above average : %f \n", rainfall_counter);
printf("Percentage of days that rained above average: %f%% \n", percent_days);
system("pause");
}
rainfall_condition is an array of char, but you're putting a pointer to a string literal in there when you use "*". Use '*' for a character literal instead. To be more specific, this line:
rainfall_condition[n] = "*";
Should be:
rainfall_condition[n] = '*';
Turn some warnings on in your compiler; the first line (what you have now) isn't valid C code and you should be seeing a diagnostic message to that effect.
Edit: now that I've read more of the code, it appears you want either a * or an empty in that column? In that case you want to change the variable declaration to:
char *rainfall_condition[50]; // array that contains the *
And then change the print statement to:
printf("%d \t %f \t %s \n", n + 1, rainfall_array[n], rainfall_condition[n]);
I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}