Yumi
Yumi

Reputation: 162

Adding the value of character in c

I was to ask to add the value of a number character into an integer, does anyone know how to do that?

#include<stdio.h>
int main()
{
    char num[100];
    int sum=0,n;
    printf("Total number: ");
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        printf("Number %d: ",i+1);
        scanf("%s",&num);
        sum=sum+num;
    }
    printf("Total = %d",sum);
}

Upvotes: 1

Views: 90

Answers (1)

Yumi
Yumi

Reputation: 162

You need to convert a string into integer using (atoi) the numerical representation to add it.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char num[100];
    int sum=0,n;
    printf("Total number: ");
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        printf("Number %d: ",i+1);
        scanf("%s",&num);
        sum+=atoi(num);
    }
    printf("Total = %d",sum);
}

Upvotes: 2

Related Questions