Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Addition of two numbers without propagating Carry?
Addition of two numbers without propagating carry is a digit-wise addition where each position is added independently without carrying over to the next position. For example, adding 7583 and 9642 gives 1611125 (7+9=16, 5+6=11, 8+4=12, 3+2=5).
We scan the numbers from right to left, add corresponding digits, and use a stack to store results so they appear in correct order.
Syntax
void noPropagateCarry(int a, int b);
Algorithm
noPropagateCarry(a, b)
begin
size = max of length of a and length of b
for i in range 1 to size, do
al := last digit of a
bl := last digit of b
push (al + bl) into stack
a := a / 10
b := b / 10
done
pop and print the elements from stack
end
Example
#include <stdio.h>
#include <math.h>
int stack[20];
int top = -1;
void push(int value) {
stack[++top] = value;
}
int pop() {
return stack[top--];
}
int isEmpty() {
return top == -1;
}
int getLength(int n) {
if (n == 0) return 1;
return (int)log10(n) + 1;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
void noPropagateCarry(int a, int b) {
int size = max(getLength(a), getLength(b));
for (int i = 0; i < size; i++) {
int al = a % 10; // last digit of a
int bl = b % 10; // last digit of b
push(al + bl);
a = a / 10;
b = b / 10;
}
printf("Result: ");
while (!isEmpty()) {
printf("%d", pop());
}
printf("<br>");
}
int main() {
int a = 7583, b = 9642;
printf("Adding %d + %d without carry propagation:<br>", a, b);
noPropagateCarry(a, b);
return 0;
}
Adding 7583 + 9642 without carry propagation: Result: 1611125
How It Works
- Extract the rightmost digit of each number using modulo operator (%)
- Add the digits and push the sum onto the stack
- Remove the rightmost digit using integer division (/)
- Repeat until all digits are processed
- Pop and print stack elements to get the final result
Conclusion
This algorithm performs digit-wise addition without carrying over, using a stack to maintain correct digit order. It's useful for understanding positional arithmetic and stack-based algorithms.
Advertisements
