Thursday, March 25, 2010

Simple C Calculator



Code is compilable for basic integer operations:

x + y

x - y

x * y

x / y

(space reqd between mainline arguments)



Though this code is too simple to share with computer science enthusiasts, but lets build C concepts over a simple snippet:

Code:


#include <stdio.h>
typedef struct {
    int operand1;
    int operand2;
    char inp_operator;   
    
} operation;
void parse_user_input(int arg_index, operation *a, char * mainline_arg);
int string_to_int_conversion(char * string);
int main(int argc, char* argv[])
{
    
    int loop_index;
    operation calc; 
    
    //Extract input digits and end-user's desired operation
    for(loop_index = 1; loop_index <argc; loop_index++)
    {
        //printf(" loop index is %d\n", loop_index);
        //printf("%s\n", argv[loop_index]);
        parse_user_input(loop_index, &calc, argv[loop_index]);
    }
        
    switch (calc.inp_operator)
    {
    case '+':
        printf("%d\n", (calc.operand1 + calc.operand2));
        break;
    case '-':
        printf("%d\n", (calc.operand1 - calc.operand2));
        break;
    case '*':
        printf("%d\n", (calc.operand1 * calc.operand2));
        break;
    case '/':
        printf("%d\n", (calc.operand1 / calc.operand2));
        break;
    default:
        printf("Invalid operands entered as %d, %d, %c, exiting without calculation", calc.operand1, calc.operand2, calc.inp_operator);
    }
    return 0;
}
//Logic for parsing user input storing basic arithmetic operands and operations
void parse_user_input(int arg_index, operation *a, char * mainline_arg)
{
  
  if (arg_index == 1)
  {
     a->operand1 = string_to_int_conversion(mainline_arg); 
     //printf("%d\n", a->operand1);
  }
  
  if (arg_index == 2)
  {
     
     a->inp_operator = mainline_arg[0]; 
     
  }
  if (arg_index == 3)
  {
     a->operand2 = string_to_int_conversion(mainline_arg); 
     //printf("%d\n", a->operand2);
  }
}

//Logic for converting string to decimal if 
//each element entered between 0-9 
int string_to_int_conversion(char * string)
{
    int converted_integer = 0;
    while ((*string != '\0') && (*string >='0') && (*string <='9') )
    {
        converted_integer = (converted_integer * 10) + (*string -'0');
        *string++;
        
    }
 

    return converted_integer;
  
}
Quiz:

1.Use Function polymorphism in above C program
2. Introduce floating point arithmetic in the above code

Mindbox