Program 4:
Aim:
To Write program and design test cases for the following Control
and decision-making statement.
1) For... Loop
2) Do... While
For…Loop :
Example : calculate the sum of numbers from 1 to N, where N is provided
by the user
#include <stdio.h>
int main()
int N, sum = 0;
printf("Enter the value of N: ");
scanf("%d", &N);
for (int i = 1; i <= N; ++i)
sum =sum+ i;
printf("Sum of numbers from 1 to %d is: %d\n", N, sum);
return 0;
}
Test Cases:
1. Test Case 1: Positive Input
● Input: N = 5
● Expected Output: Sum of numbers from 1 to 5 is: 15
2. Test Case 2: Zero as Input
● Input: N = 0
● Expected Output: Sum of numbers from 1 to 0 is: 0
3. Test Case 3: Large Positive Input
● Input: N = 100
● Expected Output: Sum of numbers from 1 to 100 is: 5050
4. Test Case 4: Negative Input (Invalid)
● Input: N = -5
● Expected Output: Invalid input, please enter a positive
integer.
5. Test Case 5: Character Input (Invalid)
● Input: N = A
● Expected Output: Invalid input, please enter a positive
integer.
6. Test Case 6: Fractional Input (Invalid)
● Input: N = 7.5
● Expected Output: Invalid input, please enter a positive
integer.
2) Do... While
#include <stdio.h>
int main()
int N, sum = 0;
char choice;
do
printf("Enter the value of N: ");
if (scanf("%d", &N) != 1 || N <= 0)
printf("Invalid input. Please enter a positive integer.\n");
while (getchar() != '\n');
continue;
}
// Calculate the sum using a do-while loop
int i = 1;
do {
sum += i;
i++;
} while (i <= N);
printf("Sum of numbers from 1 to %d is: %d\n", N, sum);
printf("Do you want to calculate the sum again? (y/n): ");
scanf(" %c", &choice);
sum = 0;
} while (choice == 'y' || choice == 'Y');
return 0;
Test Case Input Expected Output Comments
Sum of numbers from 1 to 5 is:
1 N=5 15 Valid positive input
Sum of numbers from 1 to 0 is:
2 N=0 0 Edge case: zero as input
Test Case Input Expected Output Comments
Sum of numbers from 1 to 100
3 N = 100 is: 5050 Valid large positive input
Invalid input. Please enter a
4 N = -5 positive integer. Invalid negative input
Invalid input. Please enter a
5 N=A positive integer. Invalid character input
Invalid input. Please enter a
6 N = 7.5 positive integer. Invalid fractional input
Test Cases :