-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathodd_number_triangle.c
105 lines (87 loc) · 3.22 KB
/
odd_number_triangle.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
99
100
101
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
void printTriangle(int maxRows);
void clearInputBuffer();
int main()
{
int choice = 0;
int maxRows = 0;
printf("=== Number Triangle Generator ===\n");
while (1) {
// Display menu
printf("\nMENU:\n\n");
printf("1. Generate number triangle\n");
printf("2. Exit program\n");
printf("\nEnter your choice (1-2): ");
// Get user choice with error handling
if (scanf("%d", &choice) != 1) {
printf("\nError: Invalid input. Please enter a number.\n");
clearInputBuffer();
continue;
}
switch (choice) {
case 1: {
int validInput = 0;
while (!validInput) {
// Get maximum rows from user
printf("\nEnter maximum number of rows (odd number, 1-99) or 0 to return to menu: ");
if (scanf("%d", &maxRows) != 1) {
printf("\nError: Invalid input. Please enter a number.\n");
clearInputBuffer();
continue;
}
// Option to return to main menu
if (maxRows == 0) {
break;
}
// Validate input
if (maxRows < 1) {
printf("\nError: Number of rows cannot be less than 1.\n");
} else if (maxRows > 99) {
printf("\nError: Number of rows cannot exceed 99.\n");
} else {
if (maxRows % 2 == 0) {
printf("\nNote: Converting %d to %d for odd-row pattern.\n",
maxRows, maxRows + 1);
maxRows += 1;
}
// Print the triangle
printTriangle(maxRows);
validInput = 1;
}
}
break;
}
case 2:
printf("\nThank you for using the Number Triangle Generator. Goodbye!\n");
return 0;
default:
printf("\nError: Invalid choice. Please select 1 or 2.\n");
}
clearInputBuffer();
}
return 0;
}
// Function to print the number triangle
void printTriangle(int maxRows) {
// Declare variables for row and column counters
int row, col;
// Print header for the triangle display
printf("\n--- Number Triangle ---\n\n");
// Outer loop: iterate through odd numbers only (1,3,5...)
for(row = 1; row <= maxRows * 2; row += 2)
{
// Inner loop: for each row, print odd numbers from 1 to current row value
for(col = 1; col <= row; col += 2)
{
printf("%d ", col);
}
// Move to next line after completing each row
printf("\n");
}
}
// Function to clear input buffer
void clearInputBuffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}