Nested Loops in C Programming
Experiment 5: Nested Loops in C
Objectives
Introduction to nested loops.
Theory
This lab explores nested loop structures in C programming.
Task 1: Print prime numbers between two user-given integers.
Outer loop:
forloop.Inner loop:
whileloop (divisibility check).Prime number: No divisors other than 1 and itself.
Task 2: Pattern printing using user-defined row input.
Pattern 1: Left-aligned triangle of stars (nested
forloops).Pattern 2: Alphabet-based pattern (nested
forloops).Left part: grows from 'a'.
Right part: repeats the last character, aligned with spacing.
Codes and Outputs
Problem 1: Prime Numbers
Objective: Print prime numbers between two given integers using 'for' and 'while' loops.
Code snippet (C):
#include <stdio.h> int main() { int start, end; printf("Enter the starting number: "); scanf("%d", &start); printf("Enter the ending number: "); scanf("%d", &end); for (int num = start; num <= end; num++) { if (num < 2) continue; int i = 2; int isPrime = 1; while (i < num) { if (num % i == 0) { isPrime = 0; break; } i++; } if (isPrime) { printf("%d ", num); } } printf("\n"); return 0; }Example:
Input: start = 1, end = 8
Output: 2 3 5 7
Problem 2: Pattern Printing
Pattern [i]: Triangle of Stars
Objective: Print a left-aligned triangle of stars.
Code snippet (C):
#include <stdio.h> int main() { int i, j; for(i = 1; i <= 5; i++) { for(j = 1; j <= i; j++) { printf("* "); } printf("\n"); } return 0; }Output:
* * * * * * * * * * * * * * *
Pattern [ii]: Alphabet Pattern
Objective: Print an alphabet-based pattern.
Code snippet (C):
#include <stdio.h> int main() { int i, j; int n = 5; for(i = 1; i <= n; i++) { for(j = 0; j < i; j++) { printf("%c", 'a' + j); } switch(i) { case 1: printf(" "); break; case 2: printf(" "); break; case 3: printf(" "); break; case 4: printf(" "); break; case 5: printf(" "); break; } char ch = 'a' + i - 1; for(j = 0; j < i; j++) { printf("%c", ch); } printf("\n"); } return 0; }Output:
a a
ab bb
abc ccc
abcd dddd
abcde eeeee
Discussion
Nested loops and conditional logic were practiced.
Prime number identification:
forandwhileloops.Pattern printing: star triangle and alphabet patterns.
Reinforced control structures and output formatting.