Home > database >  How can I get the sum of the digits in the char array (sum from 2 to 4)? I tried the code below, but
How can I get the sum of the digits in the char array (sum from 2 to 4)? I tried the code below, but

Time:03-07

#include <stdio.h>

void main(void){

    char a[11]= "EN21396304";
    char*ptr1;

    ptr1 = a;
    ptr1 = (ptr1 2);

    char i;
    char sum = 0;

    for(i=0; i<=8; i  ){
        sum = sum   *(ptr1 i);
    }  

    printf("Sum of the digits in the array = %d\n", sum);
}

CodePudding user response:

You are adding ASCII values. You also don't need a separate pointer (ptr1). What you want is this:

#include <stdio.h>

void main(void)
{
    char a[] = "EN21396304";
    int sum = 0;

    for(int i = 2; a[i]; i  ) {
        sum  = (a[i] - '0');
    }  

    printf("Sum of the digits in the array = %d\n", sum);
}

Note that sum should be an int, because int is the most natural and efficient type for the platform and compiler.

  •  Tags:  
  • c
  • Related