For loop assistance + accumulation - c

I'm very new to programming (so I apologize in advance), and I am having trouble figuring out how to make a for loop that will do the following:
I'm asking the user to input two variables (i'll call them x & y), which I then am calculating x/y = z. I want to pose this two variable input question 3 times, and then add up the 3 z to find the average. (The later part about accumulating/averaging I can figure out, but getting a for loop to repeat and give z three times is stumping my extremely novice mind. So far I can only get the for loop to ask for the two variable inputs one time, spit out z, and then terminate (I haven't attempted the averaging of z yet, because I don't have more than one z at this time).
To make things clearer, here's what I've got:
#include <stdio.h>
int main(void)
{
float x, y, z;
int c;
printf ("Enter x: ");
scanf ("%f", &x);
while ( (c = getchar() != '\n') && c != EOF);
printf ("Enter y: ");
scanf ("%f", &y);
while ( (c = getchar() != '\n') && c != EOF);
for (; x <3; x++)
{
z = x / y;
printf("Your average is %f\n", z);
}
printf("Thank you for using the program. Goodbye\n" );
getchar();
return 0;
}
Thanks for your help!!

#include <stdio.h>
int main(void)
{
float z[3];
for (int i = 0; i < 3; ++i)
{
float x, y;
printf ("Enter x: ");
scanf ("%f", &x);
printf ("Enter y: ");
scanf ("%f", &y);
z[i] = x / y;
printf("Your average is %f\n", z[i]);
}
printf("Your overall average is %f\n", (z[0] + z[1] + z[2]) / 3);
printf("Thank you for using the program. Goodbye\n" );
getchar();
return 0;
}

Related

For loop cumulative calculation problem. C programming

Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}

Program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the factorial of n

The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.

GPA Calculator help in C

I am currently in the process of learning C and one of the challenge questions at the end of a chapter has me building a GPA Calculator. Here is the Challenge:
Create a student GPA average calculator. The program should prompt the user to enter up to 30 GPAs, which are stored in a single-dimension array. Each time he or she enters a GPA, the user should have the option to calculate the current GPA average or enter another GPA. Sample data for this program:
GPA: 3.5
GPA: 2.8
GPA: 3.0
GPA: 2.5
Hint: Be careful to not calculate empty array elements into your student GPA average.
I have the program appear to somewhat work but when it calculates the GPA average it calculates wrong. Will someone please take a look at my source code and let me know what I did wrong?
Source Code
#include <stdio.h>
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (x = 0; x < 30; x++)
{
fSum += fGrades[x];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
Output I get is as follows:
GPA Calculater
You can enter up to 30 grades
Please enter a grade and press enter: 3.22
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 3.13
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 2.89
Do you want to calculate the GPA? (Y or N): n
Please enter a grade and press enter: 3.05
Do you want to calculate the GPA? (Y or N): y
Your final GPA is: 0.10
A few things to suggest:
initialize x to 0
in the initial do/while loop, increment x after you have scanf'd in the array
in the loop that calculates fSum, use another counter and go from counter = 0; counter < x; ++counter and use fSum += fGrades[counter];.
Your problem is, that you always sum up 30 elements no matter what.
You should only add as many items that have been entered by the user.
So something like:
#include <stdio.h>
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
int counter = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[counter]);
counter++;
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (counter < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (x = 0; x < counter; x++)
{
fSum += fGrades[x];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
change the loop that calculated fSum to work with another variable instead of x
int i;
for ( i = 0; i < x; i++)
{
fSum += fGrades[ i ];
}//end for loop
There are multiple problems
1) x is not initialized, so scanf in do-while may crash your code
2) x in not incremented in do-while
3) while calculating average, you should sum only entered values, not all 30 values, else your average calculation will be wrong
Modified code as below, please check
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
x = 0;
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
x++;
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
for (y = 0; y < x; y++)
{
fSum += fGrades[y];
}//end for loop
fAverage = fSum / x;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function
You can remove the 'for' loop to calculate the sum of all values. You can calculate the sum into the 'do while' loop. It will make your code more efficient.
#include <stdio.h>
int main()
{
float fGrades[30] = {0};
float fAverage = 0;
int x;
int y = 0;
float fSum = 0;
char cResp = '\0';
int count = 0;
printf("\nGPA Calculater");
printf("\nYou can enter up to 30 grades");
do
{
printf("\nPlease enter a grade and press enter: ");
scanf("%f", &fGrades[x]);
fSum += fGrades[x];
count++;
printf("\nDo you want to calculate the GPA? (Y or N): ");
scanf("\n%c", &cResp);
} while (x < 30 && cResp != 'Y' && cResp != 'y');//end do while loop
fAverage = fSum / count;
printf("\nYour final GPA is: %.2f\n", fAverage);
return 0;
}//end main function

Program runs but asks for input twice

i have written the following program however every time i run it, the for loops do not work until i enter another number. The for loops then run, using the second number entered. why is this happening? no one seems to be having this problem... here is the program:
#include <stdio.h>
#include <math.h>
int main(void)
{
float limit;
float count;
float series1, series2;
printf("Enter a limit for the series ");
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
{
for (series1 = 1, count = 2; count <= limit; count++)
series1 += 1.0/count;
printf ("\nThe sum of the first infinite series is %.4f", series1);
for (series2 = 1, count = 2; count <= limit; count++)
series2 += (1.0/count) * pow ((-1),(count - 1));
printf ("\nThe sum of the second infinite series is %.4f", series2);
printf("\n\nEnter a limit for the series (q to quit) ");
scanf ("%f", &limit);
}
return 0;
}
Your problem is right here:
scanf ("%f", &limit);
while (scanf ("%f", &limit) == 1)
The while loop is going to execute that scanf everytime it starts, so just lose the first scanf.
When you run the while loop while (scanf ("%f", &limit) == 1) it is running scanf ("%f", &limit) == 1 again, after you have already ran it. Try setting the first scanf to output a variable and run the variable in the while loop.

floating point division in C

I am writing a program that needs to do a bit of arithmetic.
Here's what I have so far:
#include <stdio.h>
int main(void){
double h, x, n;
printf("enter h > ");
scanf("%1f", &h);
printf("enter x > ");
scanf("%1f", &x);
/* here's where I believe I'm encountering an error */
n = x/h;
return 0;
}
so let's say I put in h = 0.01 with x = 0.25, I should get n = 0.25/0.01 = 25 right?
I've tried typecasting:
n = (float)x/(float)h;
but it doesn't work...
You have written %1f (that's a digit one) in your scanf calls, but the right format for a double is %lf (that's a lower case L).
Consequently, your numbers aren't being converted properly to doubles, and you can't expect proper results.
The problem is probably due to scanf.
I suggest using fgets instead.
But try:
int main(void){
float h, x, n;
printf("enter h > ");
scanf("%f", &h);
getchar();
printf("enter x > ");
getchar();
scanf("%f", &x);
n = x/h;
return 0;
}
See my comment. You need to specify the l modifier when attempting to read double input.
#include <stdio.h>
inline int flush() {
return fflush(stdout);
}
int main() {
double x, h, n;
printf("enter h> ");
flush();
scanf("%lf", &h);
printf("enter x> ");
flush();
scanf("%lf", &x);
n = x / h;
printf("n: %lf\n", n);
}
The reason is that you have declared h,x,n to be a double and then assigned it to a float.try using float in the variable declaration
#include <stdio.h>
int main(void){
float h, x, n;
printf("enter h > ");
scanf("%f", &h);
printf("enter x > ");
scanf("%f", &x);
n = x/h;
printf("%f",n);
return 0;
}

Resources