C Programming: Control Structures & Arrays
C Programming: Control Structures & Arrays
ITERATION
Module-II
Syntax : Example:
#include <stdio.h>
if(condition) int main()
{
{ int num = 9;
if (num < 10) {
// if body printf("%d is less than 10", num);
}
// Statements to execute if condition is true if (num > 20) {
printf("%d is greater than 20", num);
} }
return 0;
}
Syntax : Example:
#include <stdio.h>
if (condition) { int main()
{
// code executed when the condition is true if (5 < 10) {
printf("5 is less than 10.");
} }
else {
else { printf("5 is greater that 10.");
}
// code executed when the condition is false
return 0;
} }
Syntax : Example:
Syntax: Example:
#include <stdio.h>
int main()
switch(expression) {
{ int var = 1;
case value1: statement_1; switch (var)
break; {
case 1:
printf("Case 1 is Matched.");
case value2: statement_2;
break;
break; case 2:
. printf("Case 2 is Matched.");
. break;
case value_n: statement_n; default:
break; printf("Default case is Matched.");
break;
}
default: default_statement;
return 0;
} }
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Traffic Light Simulation
3. Grade Calculation
5. Simple Calculator
Syntax: Example:
#include <stdio.h>
printf("Hello students\n");
i++;
}
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Print Numbers from 1 to 10
3. Factorial of a Number
5. Reverse a Number
Syntax: Example:
#include <stdio.h>
do { int main()
{
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Menu-Driven Program
2. Password Validation
Syntax: Example:
#include <stdio.h>
for(initialization; check/test expression; updation)
{
int main()
// body consisting of multiple statements {
} int i = 0;
for (i = 1; i <= 5; i++)
{
printf("Good morning\
n");
}
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Print a Pattern of Stars
2. Fibonacci Series
3. Reverse a String
Syntax: Example:
#include <stdio.h>
int main() {
break; for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d\n", i);
}
printf("Loop exited.\n");
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. User Input Validation
6. Password Validation
Syntax: Example:
#include <stdio.h>
int main() {
int i;
continue;
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; }
printf("%d\n", i);
}
return 0;
}
Syntax: Example:
#include <stdio.h>
Syntax 1 | Syntax 2 int main() {
---------------------------- int i = 0;
goto label; | label:
start:
. | . printf("i = %d\n", i);
. | . i++;
if (i < 5) {
. | . goto start;
label: | goto label; }
printf("Done!\n");
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. prints numbers from 1 to 5 using a goto
5. Password Validation
or
Example:
int matrix[3][4];
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
return 0;
}
int main() {
printf("\n");
return 0;
ability to manage the execution flow is provided by branching statements in the C programming language
1. Branching
Refers to the process in programming where the flow of execution can diverge, or "branch," depending on certain conditions.
2. Iteration
int a = 10;
int b = 20;
int sum = a + b;
a. if Statement
The if statement is used to execute a block of code only if a specified condition is true.
int x = 10;
if (x > 5) {
printf("x is greater than 5");
}
The if-else statement allows for an alternative block of code to be executed if the condition is false.
int x = 10;
if (x > 15) {
printf("x is greater than 15");
} else {
printf("x is less than or equal to 15");
}
int x = 10;
if (x > 15) {
printf("x is greater than 15");
} else if (x > 5) {
printf("x is greater than 5 but less than or equal to 15");
} else {
printf("x is less than or equal to 5");
}
Syntax:
int main() {
int a = 10, b = 20;
int max;
max = (a > b) ? a : b;
return 0;
}
// printf("%s\n", (age >= 18) ? "You are an adult." : "You are a minor.");
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
...
case valueN:
// Code to be executed if expression equals valueN
break;
default:
// Code to be executed if expression doesn't match any case
}
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
switch (day) {
case 1:
printf("Monday\n");
case 2:
printf("Tuesday\n");
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}
Monday
Tuesday
Wednesday
Syntax
do {
// Code to be executed
} while (condition);
Program:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Iteration %d\n", i);
i++;
} while (i <= 5);
return 0;
}
● In a while loop, the condition is checked before the loop body is executed. This means that if the condition is false from the
start, the loop body may never execute.
● In a do-while loop, the body executes first, and then the condition is checked.
int x = 10;
while (x < 5) {
Basic Syntax
#include <stdio.h>
int main() {
int i;
return 0;
}
You can initialize and increment multiple variables within a for loop.
Any part of the for loop (initialization, condition, increment) can be omitted, but the semicolons ; must remain.
for (;;) {
// Infinite loop
}
● You can nest for loops inside each other to handle multi-dimensional data or perform repeated tasks.
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf("i = %d\n", i);
}
return 0;
}
It is used to skip the remaining part of the loop's current iteration and immediately move on to the next iteration.
Syntax;
Continue;
Example;
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip the rest of the loop body if i is even
}
printf("%d\n", i);
}
return 0;
}
If i is even (i.e., i % 2 == 0), the continue statement is executed, which skips the printf statement and moves directly to the next iteration.
Syntax:
goto label;
…
label:
// Code to be executed after the jump
int main() {
int num = 0;
if (num < 0) {
goto error; // Jump to the error label if the number is negative
}
error:
printf("Error: You entered a negative number.\n");
return 1;
}
Features of Arrays:
Fixed Size:
Contiguous Memory:
data_type array_name[size];
float values[] = {1.1, 2.2, 3.3, 4.4}; // Array of floats (size automatically determined)
char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Character array (C-string)
A one-dimensional array is the simplest form of an array in C, representing a linear list of elements of the same data
type.
data_type array_name[size];
Use Case: A one-dimensional array is used to store lists or sequences of values, such as a list of integers, characters,
or floating-point numbers.
Modifying Elements:
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
float average = sum / 5.0;
printf("Sum: %d, Average: %.2f\n", sum, average);
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Declaration and initialization
// Accessing elements
printf("First element: %d\n", numbers[0]); // Output: 10
printf("Third element: %d\n", numbers[2]); // Output: 30
// Modifying an element
numbers[1] = 25;
printf("Modified second element: %d\n", numbers[1]); // Output: 25
return 0;
}
c. Higher-Dimensional Arrays
While less common, C allows the declaration of arrays with more than three dimensions. These are used in very specialized scenarios
and typically involve complex data structures.
a. Two-Dimensional Arrays
A two-dimensional array is often thought of as a table or matrix with rows and columns.
data_type array_name[rows][columns];
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Use Case: Two-dimensional arrays are commonly used for representing data in rows and columns, such as matrices in
mathematical operations, game boards, or tables of data.
Modifying Elements:
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
printf("Element at [0][0]: %d\n", matrix[0][0]); // Output: 1
printf("Element at [2][2]: %d\n", matrix[2][2]); // Output: 9
// Modifying an element
matrix[1][1] = 10;
printf("Modified element at [1][1]: %d\n", matrix[1][1]); // Output: 10
return 0;
}
data_type array_name[size1][size2][size3];
int cube[3][3][3] = {
{
{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}
}
};
Use Case: Three-dimensional arrays can be used in applications like 3D graphics, simulations, or storing data with three varying
dimensions.
PICT, Pune. Mrs. Madhuri S. Patil
3. Character Arrays (Strings):
A character array is a special type of one-dimensional array used to store a sequence of characters, commonly known
as a string.
Declaration:
char array_name[size];
Example:
Use Case: Character arrays are used to store and manipulate strings in C, including tasks like reading input, storing text, or working
with textual data.
Modifying Characters:
String Length:
int length = 0;
while (name[length] != '\0') {
Length++;
}
printf("Length of the string: %d\n", length);
int main() {
char name[6] = "Hello"; // Declaration and initialization
// Accessing characters
printf("First character: %c\n", name[0]); // Output: H
printf("Last character: %c\n", name[4]); // Output: o
// Modifying a character
name[1] = 'a';
printf("Modified string: %s\n", name); // Output: Hallo
return 0;
}
An array of pointers is an array where each element is a pointer. This is particularly useful for managing arrays of
strings or dynamic data structures.
Declaration:
data_type *array_name[size];
Example:
Use Case: Arrays of pointers are often used in scenarios where the size of each data element may vary, such as in storing an array of
strings (where each string can be of different length).
Modifying Strings:
Although C does not support dynamic arrays directly like some other languages, dynamic arrays can be simulated
using pointers and dynamic memory allocation functions like malloc() and realloc().
Declaration:
Example:
Use Case: Dynamic arrays are used when the size of the array needs to be determined during runtime, allowing more flexible and
efficient use of memory.
Reallocating Memory:
Freeing Memory:
free(array);
int main() {
int *numbers;
int size;
return 0;
}
● Array of Pointers: Array where each element is a pointer, useful for dynamic data structures or strings.
● Dynamic Arrays: Arrays with runtime-determined size, achieved through pointers and dynamic memory allocation.
● Declaration and Initialization: Creating arrays and initializing them with values.
● Dynamic Memory Allocation: Creating arrays with a size determined at runtime and managing their memory manually.
● C doesn't have a built-in string data type like some other languages
● it provides several functions in the string.h library to perform operations on character arrays (strings)
Character Array Initialization: You can also initialize each character manually.
Input: Use scanf or gets (although gets is unsafe and should be avoided) to read a string.
char str[50];
printf("%s\n", str);
#include <string.h>
int length = strlen(str);
4. String Copy
● Use the strcpy function to copy one string to another.
#include <string.h>
char source[] = "Hello";
char destination[20];
strcpy(destination, source); // Copies "Hello" to destination
#include <string.h>
6. String Comparison
#include <string.h>
int result = strcmp(str1, str2); // result < 0 because "Hello" < "World"
● Use the strchr function to find the first occurrence of a character in a string.
#include <string.h>
● Use the strstr function to find the first occurrence of a substring in a string.
#include <string.h>
9. String Reverse
#include <stdlib.h>
char str[10];
int main() {
char str1[100], str2[100], result[200];
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Summary