(recursive solutions only ) I'm using the function : int diff(char str[],int i) the input is the string : 123, the sum of the values in the even indexes is 1 3=4 the sum of the values in the odd indexes is 2 so the difference between the sum of the values of the even index and the sum of the values of the odd index in an array is :4-2= 2.
I have written this in the main but its not right ,how can I fix my code ??? :
printf("Enter a string:");
if(scanf("%s",str)!=1)
{
printf("Input error");
return 1;
}
printf("The difference is: %d", diff(str, 0));
return 0;
and outside the main was the function :
int diff (char str[], int i)
{
if(str[i]=='\0' || i>=100)
return 0;
if(i%2==0)
return (str[i] diff(str,i 1));
else
return (-str[i] diff(str,i 1));
}
CodePudding user response:
Another approach could be:
int diff (const char str[])
{
if (str[0] == '\0')
return 0;
if (str[1] == '\0')
return str[0] - '0';
return str[0] - str[1] diff(str 2);
}
CodePudding user response:
The elements of the string "123" will be stored by your computer as character codes. On modern computers this is usually an ASCII-derived coding which means that 0 has the value 48, 1 is 49, 2 is 50, etc. Since the character codes are in order, you can convert by subtracting the value of the code for 0, that is val = str[i] - '0';
int diff (char str[], int i)
{
if(str[i]=='\0' || i>=100)
return 0;
int value = str[i] - '0';
if(i%2==0)
return (value diff(str,i 1));
else
return (-value diff(str,i 1));
}