ayetman96
ayetman96

Reputation: 15

Add an array of integers as a whole number in C

I have to write a program that stores a whole number one digit as a time in an array. For example 1234 is a[0] 1, a[1] 2, a[2] 3, a[3] 4. The numbers will be originally stored as char so I need to convert them into type int. The goal is to take 2 positive integers that are 20 or fewer digits in length and output the sum of the numbers.

I must use the paper-and-pencil addition algorithm. The solution must be stored in an array of size 20 and then written on screen. If the output is bigger than an array of size 20 then no output should be given and the screen should display "Integer Overflow."

So far I have this coding completed:

int max;
int max_1;
char number_1[100];
int a;
int max_2;
char number_2[100];
int b;


printf( "\nEnter the total number of digits you wish to display:\n");
scanf_s( "%d", &max);

printf("\nEnter the size of the first integer you wish to add:\n");
scanf("%d", &max_1);
printf("\nEnter the first integer one number at a time seperated by spaces:\n");
while (a = 0, a < max_1, ++a)
{
    scanf_s("%c", number_1[a]);
}

printf("\nEnter the size of the second integer you wish to add:\n");
scanf("%d", &max_2);
printf("\nEnter the second integer one number at a time seperated by spaces:\n");
while (b = 0, b < max_2, ++b)
{
    scanf_s("%c", number_2[b]);
}
    return 0;

I cannot seem to figure out how to convert the numbers that are input into actual integer form since they are all stored separately in the array. Also I am unsure how I would go about converting the integer back into an array of size 20 and how I would figure out if the output would be of size 20 or greater.

I apologize for my long question. I am new to coding and am not overly good with reasoning things out. I am sure there is a simple solution for this however I cannot think of it. Any comments, solutions or suggestions would help.

Upvotes: 0

Views: 1082

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409472

Simple example showing how to read the digits, one by one, directly as integers:

int max_1;
printf("\nEnter the size of the first integer you wish to add:\n");
scanf("%d", &max_1);

int number_1[max_1];  // Use variable-length array

printf("\nEnter the first integer one number at a time seperated by spaces:\n");
for (int i = 0; i < max_1; ++i)
{
    scanf_s("%1d", &number_1[i]);
}

After this, each element in the array number_1 is a single-digit int value. Most significant digit at index 0, least significant digit at index max_1 - 1.

Upvotes: 1

Related Questions