0% found this document useful (0 votes)
11 views

Message

Uploaded by

czechowskyyy
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Message

Uploaded by

czechowskyyy
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
#include <string.h>

typedef struct {
int top;
unsigned long long int* stack;
} Stack;

void initialize(Stack* stack, int size) {


stack->top = -1;
stack->stack = (unsigned long long int*)malloc(size * sizeof(unsigned long long
int));
}

int isEmpty(Stack* stack) {


return stack->top == -1;
}

int isFull(Stack* stack, int size) {


return stack->top == size - 1;
}

void push(Stack* stack, unsigned long long int num) {


stack->stack[++stack->top] = num;
}

unsigned long long int pop(Stack* stack) {


return stack->stack[stack->top--];
}

void addNumbers(char* num1, char* num2, char* result) {


int len1 = strlen(num1);
int len2 = strlen(num2);
int size = len1 > len2 ? len1 : len2;

Stack stack1, stack2, resultStack;


initialize(&stack1, size);
initialize(&stack2, size);
initialize(&resultStack, size + 1);

int i;

for (i = 0; i < len1; i++) {


push(&stack1, num1[i] - '0');
}

for (i = 0; i < len2; i++) {


push(&stack2, num2[i] - '0');
}

int carry = 0;
while (!isEmpty(&stack1) || !isEmpty(&stack2)) {
unsigned long long int digit1 = isEmpty(&stack1) ? 0 : pop(&stack1);
unsigned long long int digit2 = isEmpty(&stack2) ? 0 : pop(&stack2);
unsigned long long int sum = digit1 + digit2 + carry;
carry = sum / 10;
unsigned long long int digit = sum % 10;
push(&resultStack, digit);
}

if (carry > 0) {
push(&resultStack, carry);
}

i = 0;
while (!isEmpty(&resultStack)) {
result[i++] = pop(&resultStack) + '0';
}
result[i] = '\0';

int length = strlen(result);


for (i = 0; i < length / 2; i++) {
char temp = result[i];
result[i] = result[length - 1 - i];
result[length - 1 - i] = temp;
}

free(stack1.stack);
free(stack2.stack);
free(resultStack.stack);
}

int main() {
FILE* file1 = fopen("WE1.TXT", "r");
FILE* file2 = fopen("WE2.TXT", "r");
FILE* output = fopen("WY.TXT", "w");

if (file1 == NULL || file2 == NULL || output == NULL) {


printf("Failed to open files.\n");
return 1;
}

char num1[100];
char num2[100];
char result[101];

while(fgets(num1, sizeof(num1), file1)!=NULL&&fgets(num2, sizeof(num2), file2)!


=NULL){
num1[strcspn(num1, "\n")] = '\0';
num2[strcspn(num2, "\n")] = '\0';
addNumbers(num1, num2, result);
fprintf(output, "%s\n", result);
}

fclose(file1);
fclose(file2);
fclose(output);

printf("Dodawanie wykonane i zapisane do pliku WY.TXT\n");

return 0;
}

You might also like