This C program has the user enter 10 expressions and the program will return an answer. The output will look something like this:
Type in your expression: 1 2
3
Type in your expression: 1/2
0.5
etc etc
My question is how do I print the output at the end of the loop instead of one at a time. So it will look more like this:
Type in your expression: 1 2
Type in your expression: 1/2
3
0.5
#include<stdio.h>
int main()
{
float value1, value2;
char operator;
int i;
for(i=1;i<=10;i ){
printf("Type in your expression. \n");
scanf ("%f %c %f",&value1,&operator,&value2);
switch(operator)
{
case ' ':
printf("%.2f \n", value1 value2);
break;
case '-':
printf("%.2f \n", value1 - value2);
break;
case '*':
printf("%.2f \n", value1 * value2);
break;
case '/':
printf("%.2f \n", value1 / value2);
break;
default:
printf("Unknown Operator \n");
break;
}
}
}
CodePudding user response:
As said before, you need to store the results in an array
#include<stdio.h>
int main()
{
float value1 = 0, value2 = 0;
char operator = 0;
// array where we will store the results
float results[10] = {0};
for(int i=0;i<10;i ){
printf("Type in your expression. \n");
scanf ("%f %c %f",&value1,&operator,&value2);
switch(operator)
{
case ' ':
results[i] = value1 value2;
break;
case '-':
results[i] = value1 - value2;
break;
case '*':
results[i] = value1 * value2;
break;
case '/':
results[i] = value1 / value2;
break;
default:
printf("Unknown Operator \n");
return 0;
}
}
// print the results in the array
for(int i = 0;i<10;i ){
printf("Result of %d is : %.2f", i, results[i]);
}
}
CodePudding user response:
I would just use an array of structs, to store the operation, and values then print them at the end.
Also your initial loop should be i = 0; i < 10;
rather than i=1; i<=10;
#include <stdio.h>
#include <string.h>
struct MOperation{
float value1;
float value2;
char op;
float result;
};
int main()
{
int i;
struct MOperation operations[10] = {0};
for(i=0;i<10;i ){
struct MOperation temp = {0};
printf("Type in your expression. \n");
scanf ("%f %c %f",&temp.value1,&temp.op,&temp.value2);
switch(temp.op){
case ' ':
temp.result = temp.value1 temp.value2;
break;
case '-':
temp.result = temp.value1 - temp.value2;
break;
case '*':
temp.result = temp.value1 * temp.value2;
break;
case '/':
temp.result = temp.value1 / temp.value2;
break;
default:
printf("Unknown Operator \n");
break;
}
memcpy(&operations[i],&temp,sizeof(struct MOperation));
}
for(i = 0; i<10; i){
printf("operation %.2f %c %.2f = %.2f\n",operations[i].value1,
operations[i].op,
operations[i].value2,
operations[i].result);
}
return 0;
}