Simple calculator program using switch statement.

Hello coders! This is going to be the first project that we will be building using our basics learnt till now. So, Welcome back

Will be creating a simple calculator that takes multiple inputs from the user for addition and subtraction particularly and then performs additions or subtraction depending on the choices made. For division and multiplication will take only two operands.

Code -

#include<stdio.h>

int main()
{
  int choice,n,i;
  float a,b, ans=0;
  printf("**********Simple calculator**********\n");
  printf("Make your choice: \n1. press '1' for addition\n2. press '2' for subtraction\n3. press '3' for multiplication\n4. press '4' for division\n");
  scanf("%d",&choice);
  if (choice==3 || choice== 4){
    printf("Enter operand 1:");
    scanf("%f",&a);
    printf("Enter operand 2:");
    scanf("%f",&b);
    switch(choice)
    {
       case 3: printf("%f",(a*b));
               break;
       case 4: printf("%f",(a/b));
               break;
  }
}
  else if (choice == 1 || choice == 2){
    printf("Enter the total number of operands: ");
    scanf("%d",&n);
    float arr[n];
    for (int i=0; i<n; i++)
  {
    printf("Enter operand %d: ",i);
    scanf("%f",&arr[i]);
    printf("\n");
  }
  switch(choice)
  {
    case 1: for(i=0; i<n; i++){
            ans = ans + arr[i];
          }
          printf("Answer: %f",ans);
          break;
    case 2: ans = arr[0];
          for(i=1; i<=n; i++){
            ans = ans - arr[i];
          }
          printf("Answer: %f",ans);
          break;
   }
 }
 else {
   printf("Invalid Input");
 }
}

Software used-

If you are a beginner then it's better to write your programs on programmers editors and then compile using command prompt. If you do in this way, you get a clear idea of how the instructions are executed, how the executable files are generated. 

Programmers editors- 
  • Atom 
  • Notepad++ 
  • sublime text
There are many more. I used the Atom editor to execute the code. 

Output- 


While executing your code using command prompt, first write gcc <file name> 
If there are no errors, then it creates an executable file with .exe extension.
mention that file in the command prompt. And your file gets executed. 

Hope so you liked this small project. If you have doubt comment down below always ready to clear them. 

Happy learning! 

Comments

Popular post