Here is the code of my simple calculator:
#include <stdio.h>
int main(void)
{
int n1, n2;
char op;
do {
printf("Enter which operation you want to do(+, -, *, /) \n"); op = getch();
} while(op!='+' && op!='-' && op!='*' && op!='/');
printf("\n");
switch(op) {
case '+':
printf("You chose to do addition.\n\n");
printf("Number 1: "); scanf("%i", &n1);
printf("Number 2: "); scanf("%i", &n2); printf("\n");
printf("%i + %i = %i\n", n1, n2, n1+n2);
break;
case '-':
printf("You chose to do subtraction.\n\n");
printf("Number 1: "); scanf("%i", &n1);
printf("Number 2: "); scanf("%i", &n2); printf("\n");
printf("%i - %i = %i\n", n1, n2, n1-n2);
break;
case '*':
printf("You chose to do multiplication.\n\n");
printf("Number 1: "); scanf("%i", &n1);
printf("Number 2: "); scanf("%i", &n2); printf("\n");
printf("%i * %i = %i\n", n1, n2, n1*n2);
break;
case '/':
printf("You chose to do division.\n\n");
float dn1, dn2;
printf("Number 1: "); scanf("%f", &dn1);
printf("Number 2: "); scanf("%f", &dn2); printf("\n");
printf("%f / %f = %f\n", dn1, dn2, dn1/dn2);
break;
}
}
As you can see, the program takes the input from the user and makes some calculations accordingly to that. It works nice and as I expected but, I'm taking only two numbers from the user. I want to make the user be able to enter a number as many times as he/she wants.
I thought something like this and it seemed stupid to me.
for(int i=1; i<10; i++) {
printf("Enter number %i: ", i); scanf("%i", &{i}n);
}
I tried to use the for loop initialization variable to create new variables as much as the user wants.
I have a little bit experience in Javascript
and Python
, and I remember something like I could use the initialization variable as a placeholder.