0

I'm writing a program that takes in your student number(8 digits long), prints each digit on its own new line, and then gets the sum of all the digits in the number (E.g. Student Number - 20305324, Sum - 19)

#include <stdio.h>
#include <string.h>

int main(void) {
  char student_number[8];
  int i = 0;
  int sum = 0;

  printf("Enter your student number: ");
  scanf("%s", student_number);

  // ensures input is only 8 digits - WORKS
  while (strlen(student_number) < 8 || strlen(student_number) > 8){
    printf("Enter your student number: ");
    scanf("%s", student_number);    
  }

  // prints each digit of the student number on a new line - WORKS
  while (student_number[i] != '\0'){
    printf("%c\n", student_number[i]);
    i++;
  }
  

  // sum all the digits in the student number and print - DOESN'T WORK 
  for (i=0;i<8;i++){
    sum = sum + student_number[i];
    printf("%d\n", sum);
  }

  printf("Sum of the numbers is %d", sum);



}

OUTPUT

The problem I'm encountering is when my for loop attempts to add each digit in the student number. The output I expect here is 19, but for some reason the sum evaluates to some bizarre number like 403

}Output

Would someone mind pointing out where exactly the fault in my for loop is or if it is elsewhere? Thanks :)

3
  • 2
    You need char student_number[9] to hold 8 digits, since you need room for the null terminator. And if the user types more than 8 digits you'll overflow, so you need to make it much larger. Commented Jan 28, 2021 at 20:07
  • 1
    sum = sum + student_number[i] - '0'; otherwise you'll be adding the (ASCII) code for '0' (48), '1' (49)... Commented Jan 28, 2021 at 20:08
  • Don't post pictures of text but post text as text. Commented Jan 28, 2021 at 20:22

3 Answers 3

2

Firstly, your array char student_number[8]; cannot hold 8-character string because there are no room for terminating null character. You must allocate one more element.

Then, you should convert the characters to corresponding numbers. Character codes for digits are defined to be continuous, so this can be done by subtracting '0' from the character code.

Also you should set a limit of length of string to read via scanf() to avoid buffer overrun. One more good practice is checking the return values of scanf() to see if something is successfully read.

Fixed code:

#include <stdio.h>
#include <string.h>

int main(void) {
  char student_number[10]; // *** allocate enough elements (one more than needed to catch too long input)
  int i = 0;
  int sum = 0;

  printf("Enter your student number: ");
  if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
    fputs("read error\n", stderr);
    return 1;
  }

  // ensures input is only 8 digits - WORKS
  while (strlen(student_number) < 8 || strlen(student_number) > 8){
    printf("Enter your student number: ");
    if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
      fputs("read error\n", stderr);
      return 1;
    }
  }

  // prints each digit of the student number on a new line - WORKS
  while (student_number[i] != '\0'){
    printf("%c\n", student_number[i]);
    i++;
  }
  

  // sum all the digits in the student number and print -DOESN'T WORK 
  for (i=0;i<8;i++){
    sum = sum + (student_number[i] - '0'); // *** convert characters to numbers before adding
    printf("%d\n", sum);
  }

  printf("Sum of the numbers is %d", sum);



}
Sign up to request clarification or add additional context in comments.

Comments

1

When you read characters as a string, the values of the char objects are codes for the characters. Your C implementation is likely using ASCII codes, in which 48 is the code for “0”, 49 is the code for “1”, 65 is the code for “A”, and so on.

To convert a code x for a digit to the value of the digit, use x - '0'.

Comments

0

I think that the task was to read the number not the string.

void printDigitsAndSum(unsigned number)
{
    unsigned mask = 1;
    unsigned sum = 0;
    while(number / (mask * 10)) mask *= 10;
    while(mask)
    {
        printf("%u\n", number / mask);
        sum += number / mask;
        number %= mask;
        mask /= 10;
    }
    printf("Sum: %u\n", sum);
}

int main(void)
{
    unsigned number;

    if(scanf("%u", &number) == 1)
        printDigitsAndSum(number);
    else printf("Wrong number\n");
}

https://godbolt.org/z/1edceh

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.