Home > Enterprise >  Calculate the sum of the operation in a string
Calculate the sum of the operation in a string

Time:11-29

Problem Statement

You are given a string S consisting only (Addition),*(Multiplication). The next line will contain two positive values.

Now, Calculate the sum of every operations. See the explanation for more clarification.

Input Format

First line contains a string S, consisting only  (Addition),*(Multiplication) operator.
The second line will contain two positive integers a and b

Constraints

1 <= |S| <= 20, where |S| means the length of S.
1<= a, b <= 50

Output Format

Print the summation which were perform based on String S.

Sample Input 0

type here

* 5 10

Sample Output 0

65

Explanation 0

when S[i] = ' ',Then a b = 5   10 = 15 and sum = 15
when S[i] = '*',Then a*b = 5 * 10 = 50 and sum = 15   50 = 65

Sample Input 1

*** 2 1

Sample Output 1

12

Following is my attempted code

    #include<stdio.h>
    int main(){
    char S[20];
    int a,b,i,sum=0;
    scanf("%s %d %d",S, &a,&b);

    for(i=0; i<=20; i  ){
        if (S[i]= " "){
            sum =a b;
        }
        else{
            sum =a*b;
        }
    }

    printf("%d",sum);
    return 0;
}

CodePudding user response:

You have typos like

    if (S[i]= " "){

where there is used the assignment operator = instead of the equality operator == or using string literals like " " instead of integer character constants. and incorrect expression in the for loop.

At least change the for loop the following way

for ( i = 0; S[i] != '\0';   i ){
    if ( S[i] == ' ' ){
        sum  = a   b;
    }
    else if ( S[i] == '*' ){
        sum  = a * b;
    }
}

Pay attention to that according to the assignment you need to check entered values of a and b that they are in the range [1, 50]. And the call of scanf should be written like

scanf( "s %d %d", S, &a, &b );.

CodePudding user response:

I did not understand how you should write the parameters, but looking at your code I saw a error:

if (S[i]= " "){

here you want to compare the value of S with index i with the plus sign

  1. for compare you need to use ==
  2. S[i] is a char, you need to use ' '

the dobles " " are for char* and not char.

I hope I was helpful.

  • Related