Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Simple calculator v1 with how it works prints and comments
- #include<stdio.h>
- int main()
- {
- // c is operator, snum1 and snum2 are entered strings of numbers num1 and num2
- char c, str[20], snum1[20],snum2[20];
- // i is counter, snum2length is length of snum2, num1 and num2 are entered numbers
- int i,snum2length=0,num1,num2;
- printf("\n 1. CALCULATOR \n\n");
- printf("\n 2. Enter first number, operator (+,-,*,/) and second number \n\n");
- scanf("%s",str); // no need for &str because str is address of str[0]
- printf("\n 3. Entered string: %s \n", str);
- // print str[i]
- while(str[i]!='\0'){ // from beginning to end of str
- printf("\n 4. str[%d] = %c \n",i,str[i]);
- i++; // next character of str
- }
- i=0; // reset counter
- // while str[i] is digit and it is not the end of str
- // read snum1[i] from str[i] until str[i] is operator (not digit)
- while(isdigit(str[i]) && str[i]!='\0'){ // from beginning to end of str
- snum1[i]=str[i]; // copy str[i] to snum1[i]
- printf("\n 5. str[%d] = %c \t snum1[%d] = %c \n",i,str[i],i,snum1[i]);
- i++; // next character of str and snum1
- }
- snum1[i]='\0'; // finish snum1
- num1=atoi(snum1); // convert string snum1 to integer num1
- c=str[i]; // read operator c from str[i]
- printf("\n 6. snum1 = %s \n", snum1);
- printf("\n 7. num1 = %d \n", num1);
- printf("\n 8. i = %d \t c = %c \n",i,c);
- i++; // next character of str, this is first character of snum2
- printf("\n 9. i = %d \n",i);
- // while str[i] is digit and it is not the end of str
- // read snum2[i] from str[i] until the end of str
- while(isdigit(str[i]) && str[i]!='\0'){ // from first character of snum2 in str, to end of str
- snum2[snum2length]=str[i]; // copy str[i] to snum2[snum2length]
- printf("\n 10. str[%d] = %c \t snum2[%d] = %c \n",i,str[i],snum2length,snum2[snum2length]);
- i++; // next character of str
- snum2length++; // next character of snum2, increase the lenghth of string snum2
- }
- printf("\n 11. i = %d \t snum2length = %d \n",i,snum2length);
- snum2[snum2length]='\0'; // finish snum2
- i=0; // reset counter
- while(snum2[i]!='\0'){
- printf("\n 12. snum2[%d] = %c \n",i,snum2[i]);
- i++; // next character of snum2
- }
- printf("\n 13. snum2 = %s \n", snum2);
- num2=atoi(snum2); // convert string snum2 to integer num2
- printf("\n 14. num2 = %d \n", num2);
- printf("\n %d %c %d = ",num1,c,num2);
- switch(c) // analyze operator c
- {
- case '+':
- printf("%d \n",num1+num2);
- break;
- case '-':
- printf("%d \n",num1-num2);
- break;
- case '*':
- printf("%d \n",num1*num2);
- break;
- case '/':
- printf("%f \n",(float)num1/num2);
- break;
- default:
- printf("Error! Invalid Operator.");
- }
- printf("\n\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment