#include<conio.h> #include<stdio.h> #include<string.h> #include<stdlib.h> void a
ID: 3838557 • Letter: #
Question
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void accept();
void result();
int no1=0,no2=0,sum=0,a[10],b[10],c[5],i=0,r1,r2,x,y,total=0,l1,l2;
char s1[100],s2[100];
void main()
{
char choice;
do
{
accept();
result();
printf("Do You want to add more numbers(y/n)?");
scanf("%c",&choice);
}while(choice=='y'||choice=='Y');
getch();
}
void accept()
{
printf("Enter First Number ");
scanf("%s",s1);
l1=strlen(s1);
if(l1>100)
{
printf("Too Many Digits !! Please try again ");
accept();
}
printf("Enter Second Number ");
scanf("%s",s2);
l2=strlen(s2);
if(l2>100)
{
printf("Too Many Digits !! Please try again ");
accept();
}
no1 = atoi(s1);
no2=atoi(s2);
x=no1;
y=no2;
}
void result()
{
while(no1!=0 || no2!=0)
{
sum=0;
r1=no1%10;
r2=no2%10;
no1=no1/10;
no2=no2/10;
a[i]=r1;
b[i]=r2;
c[i]=0;
sum=sum*10+a[i]+b[i]+c[i];
printf("%d : %d+%d+%d = %d ",i,a[i],b[i],c[i],sum);
i++;
total=total*10+sum;
}
printf(" Number 1 : %d ",x);
printf("Number 2 : %d ",y);
printf("Sum : %d ",x+y);
}
This is my code, but the sum is incorrect, how to use a carry in C language?
For example, when the number is 58 and 67
should be like
8 + 7 + 0 =15
5 + 6 + 1 =12
the sum is 125
Explanation / Answer
#define _CRT_SECURE_NO_WARNINGS
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void accept();
void result();
int carry = 0;
int no1 = 0, no2 = 0, sum = 0, a[10], b[10], c[5], i = 0, r1, r2, x, y, total = 0, l1, l2;
char s1[100], s2[100];
void main()
{
char choice;
do
{
accept();
result();
printf("Do You want to add more numbers(y/n)?");
scanf("%c", &choice);
} while (choice == 'y' || choice == 'Y');
getch();
}
void accept()
{
printf("Enter First Number ");
scanf("%s", s1);
l1 = strlen(s1);
if (l1>100)
{
printf("Too Many Digits !! Please try again ");
accept();
}
printf("Enter Second Number ");
scanf("%s", s2);
l2 = strlen(s2);
if (l2>100)
{
printf("Too Many Digits !! Please try again ");
accept();
}
no1 = atoi(s1);
no2 = atoi(s2);
x = no1;
y = no2;
}
void result()
{
c[i] = 0;
sum = 0;
int j = 1;
while (no1 != 0 || no2 != 0)
{
// 58
// 67
r1 = no1 % 10; //8
r2 = no2 % 10; //7
no1 = no1 / 10; // 5
no2 = no2 / 10; // 6
a[i] = r1; // 8 // 5
b[i] = r2; // 7 // 6
sum = a[i] + b[i] + c[i]; // 15, 12
printf("%d : %d+%d+%d = %d ", i, a[i], b[i], c[i], sum); // 0 8 7 0 15 // 1 5 6 12
if (sum >= 10 && j<1)
{
carry = 1;
sum = sum - 10; // 5
}
total = j*sum + total; //0 + 5
i++;
c[i] = carry;
j = 10;
}
printf(" Number 1 : %d ", x);
printf("Number 2 : %d ", y);
printf("Sum : %d ", total);
}
/*
This is my code, but the sum is incorrect, how to use a carry in C language ?
For example, when the number is 58 and 67
should be like
8 + 7 + 0 = 15
5 + 6 + 1 = 12
the sum is 125
58
67
=125
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.