c
exercises
exercises.c🔧c
/**
* @file exercises.c
* @brief break, continue, goto Exercises
*
* Practice jump statements in C.
*
* Compile: gcc -Wall exercises.c -o exercises
* Run: ./exercises
*/
#include <stdio.h>
/* ============================================================
* EXERCISE 1: FIND FIRST NEGATIVE
* ============================================================
* Difficulty: Easy
*
* Task: Find the first negative number in an array.
* Return its index, or -1 if none found.
* Use break when found.
*/
int findFirstNegative(int arr[], int size) {
// TODO: Return index of first negative, -1 if not found
// Use break when found
// Your code here
return -1; // Replace this
}
void exercise_1() {
printf("\n=== Exercise 1: Find First Negative ===\n");
int arr1[] = {5, 10, -3, 8, -7};
int arr2[] = {1, 2, 3, 4, 5};
printf("Array 1: First negative at index %d\n",
findFirstNegative(arr1, 5));
printf("Array 2: First negative at index %d\n",
findFirstNegative(arr2, 5));
}
/* ============================================================
* EXERCISE 2: SUM UNTIL ZERO
* ============================================================
* Difficulty: Easy
*
* Task: Sum array elements until you hit zero.
* Use break to stop.
*/
int sumUntilZero(int arr[], int size) {
// TODO: Return sum of elements until 0 is found
// Your code here
return 0; // Replace this
}
void exercise_2() {
printf("\n=== Exercise 2: Sum Until Zero ===\n");
int arr1[] = {5, 10, 15, 0, 20, 25};
int arr2[] = {1, 2, 3, 4, 5};
printf("Array 1: Sum = %d (should be 30)\n", sumUntilZero(arr1, 6));
printf("Array 2: Sum = %d (should be 15)\n", sumUntilZero(arr2, 5));
}
/* ============================================================
* EXERCISE 3: SKIP MULTIPLES
* ============================================================
* Difficulty: Easy
*
* Task: Print numbers 1-20, but skip multiples of 3.
* Use continue.
*/
void skipMultiplesOf3() {
// TODO: Print 1-20, skip multiples of 3
// Your code here
}
void exercise_3() {
printf("\n=== Exercise 3: Skip Multiples of 3 ===\n");
printf("Numbers 1-20 (no multiples of 3): ");
skipMultiplesOf3();
printf("\n");
}
/* ============================================================
* EXERCISE 4: COUNT VOWELS
* ============================================================
* Difficulty: Easy
*
* Task: Count vowels in a string.
* Use continue to skip non-vowels.
*/
int countVowels(char str[]) {
// TODO: Return count of vowels (a, e, i, o, u)
// Handle upper and lowercase
// Your code here
return 0; // Replace this
}
void exercise_4() {
printf("\n=== Exercise 4: Count Vowels ===\n");
printf("'Hello World': %d vowels\n", countVowels("Hello World"));
printf("'AEIOU': %d vowels\n", countVowels("AEIOU"));
printf("'xyz': %d vowels\n", countVowels("xyz"));
}
/* ============================================================
* EXERCISE 5: FIND PAIR SUM
* ============================================================
* Difficulty: Medium
*
* Task: Find if any pair of numbers in array sums to target.
* Print the pair and use break to exit once found.
* Return 1 if found, 0 otherwise.
*/
int findPairSum(int arr[], int size, int target) {
// TODO: Find pair that sums to target
// Print the pair if found
// Use break to exit early
// Your code here
return 0; // Replace this
}
void exercise_5() {
printf("\n=== Exercise 5: Find Pair Sum ===\n");
int arr[] = {2, 7, 11, 15, 3, 6};
int size = 6;
printf("Finding pair for sum 9: ");
if (!findPairSum(arr, size, 9)) printf("Not found\n");
printf("Finding pair for sum 100: ");
if (!findPairSum(arr, size, 100)) printf("Not found\n");
}
/* ============================================================
* EXERCISE 6: VALIDATE PASSWORD
* ============================================================
* Difficulty: Medium
*
* Task: Check if password has at least one digit and one letter.
* Use break when both are found.
*/
int isValidPassword(char password[]) {
// TODO: Return 1 if has digit AND letter, 0 otherwise
// Your code here
return 0; // Replace this
}
void exercise_6() {
printf("\n=== Exercise 6: Validate Password ===\n");
printf("'abc123': %s\n",
isValidPassword("abc123") ? "Valid" : "Invalid");
printf("'password': %s\n",
isValidPassword("password") ? "Valid" : "Invalid");
printf("'12345': %s\n",
isValidPassword("12345") ? "Valid" : "Invalid");
}
/* ============================================================
* EXERCISE 7: REMOVE DUPLICATES COUNT
* ============================================================
* Difficulty: Medium
*
* Task: Count unique elements in a sorted array.
* Use continue to skip duplicates.
*/
int countUnique(int arr[], int size) {
// TODO: Count unique elements in sorted array
// Your code here
return 0; // Replace this
}
void exercise_7() {
printf("\n=== Exercise 7: Count Unique Elements ===\n");
int arr1[] = {1, 1, 2, 2, 2, 3, 4, 4, 5};
int arr2[] = {1, 2, 3, 4, 5};
printf("Unique in {1,1,2,2,2,3,4,4,5}: %d\n", countUnique(arr1, 9));
printf("Unique in {1,2,3,4,5}: %d\n", countUnique(arr2, 5));
}
/* ============================================================
* EXERCISE 8: MATRIX SEARCH
* ============================================================
* Difficulty: Medium
*
* Task: Search for a value in a 2D matrix.
* Use flag or goto to exit both loops when found.
* Print the position.
*/
void searchMatrix(int matrix[][3], int rows, int cols, int target) {
// TODO: Find target and print position (row, col)
// Print "Not found" if not present
// Your code here
}
void exercise_8() {
printf("\n=== Exercise 8: Matrix Search ===\n");
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("Searching for 5: ");
searchMatrix(matrix, 3, 3, 5);
printf("Searching for 10: ");
searchMatrix(matrix, 3, 3, 10);
}
/* ============================================================
* EXERCISE 9: PROCESS COMMANDS
* ============================================================
* Difficulty: Medium
*
* Task: Process an array of commands.
* 'S' = Skip (continue)
* 'X' = Exit (break)
* Other = Process (print)
*/
void processCommands(char commands[], int size) {
// TODO: Process commands
// Skip on 'S', exit on 'X', print others
// Your code here
}
void exercise_9() {
printf("\n=== Exercise 9: Process Commands ===\n");
char cmds[] = {'A', 'B', 'S', 'C', 'X', 'D', 'E'};
printf("Commands: ");
processCommands(cmds, 7);
printf("\n");
}
/* ============================================================
* EXERCISE 10: FIND PRIME IN RANGE
* ============================================================
* Difficulty: Hard
*
* Task: Find the first prime number >= n.
* Use break in inner loop when not prime.
*/
int findNextPrime(int n) {
// TODO: Return first prime >= n
// Your code here
return 0; // Replace this
}
void exercise_10() {
printf("\n=== Exercise 10: Find Next Prime ===\n");
printf("Next prime >= 10: %d\n", findNextPrime(10));
printf("Next prime >= 14: %d\n", findNextPrime(14));
printf("Next prime >= 17: %d\n", findNextPrime(17));
printf("Next prime >= 100: %d\n", findNextPrime(100));
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ BREAK, CONTINUE, GOTO - EXERCISES ║\n");
printf("║ Practice jump statements ║\n");
printf("╚════════════════════════════════════════════════╝\n");
// Uncomment exercises as you complete them:
// exercise_1();
// exercise_2();
// exercise_3();
// exercise_4();
// exercise_5();
// exercise_6();
// exercise_7();
// exercise_8();
// exercise_9();
// exercise_10();
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/* ============================================================
* ANSWER KEY
* ============================================================
*
* EXERCISE 1:
* int findFirstNegative(int arr[], int size) {
* for (int i = 0; i < size; i++) {
* if (arr[i] < 0) {
* return i; // or set index and break
* }
* }
* return -1;
* }
*
* EXERCISE 2:
* int sumUntilZero(int arr[], int size) {
* int sum = 0;
* for (int i = 0; i < size; i++) {
* if (arr[i] == 0) break;
* sum += arr[i];
* }
* return sum;
* }
*
* EXERCISE 3:
* void skipMultiplesOf3() {
* for (int i = 1; i <= 20; i++) {
* if (i % 3 == 0) continue;
* printf("%d ", i);
* }
* }
*
* EXERCISE 4:
* int countVowels(char str[]) {
* int count = 0;
* for (int i = 0; str[i] != '\0'; i++) {
* char c = str[i];
* if (c >= 'A' && c <= 'Z') c += 32; // to lowercase
* if (c != 'a' && c != 'e' && c != 'i' &&
* c != 'o' && c != 'u') continue;
* count++;
* }
* return count;
* }
*
* EXERCISE 5:
* int findPairSum(int arr[], int size, int target) {
* for (int i = 0; i < size - 1; i++) {
* for (int j = i + 1; j < size; j++) {
* if (arr[i] + arr[j] == target) {
* printf("Found: %d + %d = %d\n", arr[i], arr[j], target);
* return 1;
* }
* }
* }
* return 0;
* }
*
* EXERCISE 6:
* int isValidPassword(char password[]) {
* int hasDigit = 0, hasLetter = 0;
* for (int i = 0; password[i] != '\0'; i++) {
* char c = password[i];
* if (c >= '0' && c <= '9') hasDigit = 1;
* if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) hasLetter = 1;
* if (hasDigit && hasLetter) break;
* }
* return hasDigit && hasLetter;
* }
*
* EXERCISE 7:
* int countUnique(int arr[], int size) {
* if (size == 0) return 0;
* int count = 1;
* for (int i = 1; i < size; i++) {
* if (arr[i] == arr[i-1]) continue;
* count++;
* }
* return count;
* }
*
* EXERCISE 8:
* void searchMatrix(int matrix[][3], int rows, int cols, int target) {
* int found = 0;
* for (int i = 0; i < rows && !found; i++) {
* for (int j = 0; j < cols && !found; j++) {
* if (matrix[i][j] == target) {
* printf("Found at (%d, %d)\n", i, j);
* found = 1;
* }
* }
* }
* if (!found) printf("Not found\n");
* }
*
* EXERCISE 9:
* void processCommands(char commands[], int size) {
* for (int i = 0; i < size; i++) {
* if (commands[i] == 'S') continue;
* if (commands[i] == 'X') break;
* printf("%c ", commands[i]);
* }
* }
*
* EXERCISE 10:
* int findNextPrime(int n) {
* if (n <= 2) return 2;
* while (1) {
* int isPrime = 1;
* for (int i = 2; i * i <= n; i++) {
* if (n % i == 0) {
* isPrime = 0;
* break;
* }
* }
* if (isPrime) return n;
* n++;
* }
* }
*
* ============================================================
*/