why i need to subtract 48 from every digit??

Hi all
my program works
it works like this u enter some string and my program summarises all digits in entered string

but i have one question why i need to subtract 48 from every digit? (i got that "-48" from solution in the book)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int Summation (char *niz){
	int suma=0;
	for (int i=0; i<=strlen(niz); i++){
		if(isdigit(niz[i])){
			suma+=niz[i]-48; //why -48?
		}
	}
	return suma;
}

#define max 50

void main (){
	char niz[max];
	cin>>niz;
	cout<<"summation of digits in entered array is: "<<Summation (niz);
	getch();
}
Because it is a character array (char), the numbers are being stored as ascii code http://www.asciitable.com/

You can see in the table that the numbers are 48 places away from their equivalent numeral. i.e.

0 is represented by 48
1 is represented by 49
etc...

So, to convert them to an integer, you must subtract 48.

Also, do not use void main(), use int main!!! Void main won't even compile on some compilers (such as mine). It is not correct C++. It should be int main and that should generally return 0 for a correct run, or (traditionally) 1 for an error.
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    //stuff
    if(error in the stuff)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}


Or more normally (if you do not expect errors)
1
2
3
4
5
int main()
{
    //code here.
    return 0;
}
Last edited on
I use int main only when I can expect errors
btw thanks for explanation
Last edited on
I use int main only when I can expect errors - No.

Just ALWAYS use int main().
suma+=niz[i]-'0'; Now you don't have to ask
Topic archived. No new replies allowed.