-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseparator.c
98 lines (78 loc) · 2.55 KB
/
separator.c
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
long long calculateDigitSum(long long number) {
long long sum = 0;
long long tempNumber = llabs(number); // Handle negative numbers using llabs
// Extract digits and add them
while (tempNumber > 0) {
sum += tempNumber % 10; // Add the last digit to sum
tempNumber /= 10; // Remove the last digit
}
return sum;
}
int isValidInteger(const char *str) {
// Check if empty string
if (str == NULL || *str == '\0') {
return 0;
}
// Check for optional sign
if (*str == '+' || *str == '-') {
str++;
}
// String must contain at least one digit after sign
if (*str == '\0') {
return 0;
}
// Check if all remaining characters are digits
while (*str) {
if (!isdigit(*str)) {
return 0;
}
str++;
}
return 1;
}
int main(void) {
char inputBuffer[100];
long long number;
char continueChoice = 'y';
printf("\n=== Digit Sum Calculator ===\n");
do {
// Get user input
printf("\nEnter an integer (or 0 to exit): ");
// Read input as string
if (fgets(inputBuffer, sizeof(inputBuffer), stdin) == NULL) {
printf("\nError: Failed to read input.\n");
continue;
}
// Remove newline character if present
size_t len = strlen(inputBuffer);
if (len > 0 && inputBuffer[len-1] == '\n') {
inputBuffer[len-1] = '\0';
}
// Validate input
if (!isValidInteger(inputBuffer)) {
printf("\nError: Invalid input. Please enter a valid integer.\n");
continue;
}
// Convert to long long integer
number = atoll(inputBuffer);
// Exit condition
if (number == 0) {
printf("\nExiting program. Goodbye!\n");
break;
}
// Calculate and display the sum of digits
long long digitSum = calculateDigitSum(number);
printf("\nNumber: %lld\nSum of digits: %lld\n", number, digitSum);
// Ask if user wants to continue
printf("\nDo you want to calculate another sum? (y/n): ");
fgets(inputBuffer, sizeof(inputBuffer), stdin);
continueChoice = inputBuffer[0];
} while (continueChoice == 'y' || continueChoice == 'Y');
printf("\nThank you for using the Digit Sum Calculator!\n\n");
return 0;
}