0% found this document useful (0 votes)
9 views99 pages

C Programming: Control Structures & Arrays

This document covers branching and iteration in C programming, detailing control flow structures such as if-then-else, loops, and arrays. It includes syntax, examples, and problems to solve for each control structure, as well as explanations of one-dimensional and two-dimensional arrays. The content is designed for educational purposes, aimed at helping students understand decision-making in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views99 pages

C Programming: Control Structures & Arrays

This document covers branching and iteration in C programming, detailing control flow structures such as if-then-else, loops, and arrays. It includes syntax, examples, and problems to solve for each control structure, as well as explanations of one-dimensional and two-dimensional arrays. The content is designed for educational purposes, aimed at helping students understand decision-making in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

BRANCHING AND

ITERATION
Module-II

PICT, Pune. Mrs. Madhuri S. Patil


Content:
● Control flow structures: if-then-else, nested if-else, conditional expression,
switch, while loop, do-while loop, for loop, break, continue, goto.
● Arrays: Need of array
● Types of arrays: one dimensional array, two-dimensional array, examples and
operations
● primitive operations on Strings.

PICT, Pune. Mrs. Madhuri S. Patil


Decision Making(conditional statements):
Need of Decision:
● There come situations in real life when
we need to make some decisions and based
on these decisions, we decide what should we
do next.

Need of conditional statements:


● Similar situations arise in programming also where
we need to make some decisions and based on these
decisions we will execute the next block of code.

PICT, Pune. Mrs. Madhuri S. Patil


Types of Control Statement in C:

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of if statement:

PICT, Pune. Mrs. Madhuri S. Patil


if Statement:
It is a two-way decision statement. Depending on whether the value of the expression is ‘true‘ or ‘false‘, it transfers the
control to a particular statement.

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


Problems to solve:
1. Check if a Number is Even or Odd

2. Check if a Person is Eligible to Vote

3. Check if a Person is Eligible to Drive

4. Find the Largest of Two Numbers

5. Check if a Number is Positive, Negative, or Zero

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the if-else statement:

PICT, Pune. Mrs. Madhuri S. Patil


if…else Statement:
This statement allows selecting one of the two available options depending upon the output of the test expression.

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;
} }

PICT, Pune. Mrs. Madhuri S. Patil


Problems to solve:
1. Check if a Year is a Leap Year

2. Check if a Character is a Vowel or Consonant

3. Check if a Student Passed or Failed

4. Check if a Number is Divisible by 5 and 11

5. Check if a Number is Positive, Negative, or Zero

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the Nested if…else Statements:

PICT, Pune. Mrs. Madhuri S. Patil


Nested if…else Statements:
A nested if-else refers to an if or else statement placed inside another if or else block.

Syntax : Example:

if (condition1) { #include <stdio.h>


code to be executed 1 int main() {
int num = 10;
if (condition2) { if (num > 0) {
code to be executed 2 if (num % 2 == 0) {
} else { printf("The number is positive and even.\
n");
code to be executed 2 } else {
} printf("The number is positive but odd.\n");
} else { }
} else {
code to be executed 1 printf("The number is not positive.\n");
} }
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Find the Largest of Three Numbers

2. Check the Type of Triangle

3. Find the Grade Based on Marks

4. Determine Leap Year or Not

5. Classify a Character as Vowel, Consonant, or Not an Alphabet

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the Conditional expression(Ternary Operator):

PICT, Pune. Mrs. Madhuri S. Patil


Conditional expression(Ternary Operator):
Writing an if-else statement using the ternary operator (? :).

Syntax (3 ways): Example:


variable = Expression 1 ? Expression2 : Expression 3;
#include <stdio.h>
variable = (condition) ? Expression2 : Expression 3;
int main() {
(condition) ? (variable = Expression 2) : (variable = int num = 10;
Expression 3); int result;

result = (num > 0) ? 1 : 0;

printf("Result: %d\n", result);


return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Check if a Number is Even or Odd

2. Find the Maximum of Two Numbers

3. Check if a Number is Positive, Negative, or Zero

4. Find the Smallest of Three Numbers

5. Assign a Grade Based on Marks

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the switch Statement:

PICT, Pune. Mrs. Madhuri S. Patil


Switch Statement:
Switch case statements follow a selection-control mechanism and allow a value to change control of execution.

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

2. Day of the Week

3. Grade Calculation

4. Month of the Year

5. Simple Calculator

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the while loop:

PICT, Pune. Mrs. Madhuri S. Patil


While loop:
The while Loop is an entry-controlled loop in C programming language. This loop can be used to iterate a part of
code while the given condition remains true.

Syntax: Example:

#include <stdio.h>

while (test expression) int main()


{ {
int i = 0;
// body consisting of multiple statements
} while (i < 5) {

printf("Hello students\n");

i++;
}
return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Print Numbers from 1 to 10

2. Calculate the Sum of Numbers from 1 to N

3. Factorial of a Number

4. Print Multiplication Table

5. Reverse a Number

6. Count Digits in a Number

7. Print Fibonacci Series

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the do-while loop:

PICT, Pune. Mrs. Madhuri S. Patil


do-while loop:
Used to repeat some part of the code till the given condition is fulfilled. Executed at least once no matter what the
condition is.

Syntax: Example:

#include <stdio.h>

do { int main()
{

// body of do-while loop int i = 0;


// do while loop
do {
} while (condition); printf("Hello Students\n");
i++;
} while (i < 3);

return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Problems to solve:
1. Menu-Driven Program

2. Password Validation

3. Guess the Number Game

4. Sum of Positive Numbers

5. Print a Pattern of Stars

6. User Menu with Continuation Option

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the for loop:

PICT, Pune. Mrs. Madhuri S. Patil


for loop:
Used to repeat some part of the code till the given condition is fulfilled. Executed at least once no matter what the
condition is.

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

4. Sum of Even Numbers

5. Print Diamond Pattern

6. Count Vowels in a String

7. Print Pascal's Triangle

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the Break Statement:

PICT, Pune. Mrs. Madhuri S. Patil


Break Statement:
The break statement is one of the four jump statements in the C language. The purpose of the break statement in C
is for unconditional exit from the loop

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

2. Multiplication Table for a Specific Number

3. Guess the Number Game

4. Check for Prime Number

5. Sum of Digits Until Single Digit

6. Password Validation

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the continue Statement:

PICT, Pune. Mrs. Madhuri S. Patil


Continue Statement:
The continue statement in C is a jump statement that is used to bring the program control to the start of the loop.

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


Problems to solve:
1. Print Non-Multiples of 5

2. Skip Negative Input and Print Positive

3. Print Numbers Except Multiples of 7

4. Skip Even Numbers and Print Squares

5. Print Even Numbers in a Range

6. Print Sum of Odd Numbers

7. Print Multiples of 4 but Skip Multiples of 6

PICT, Pune. Mrs. Madhuri S. Patil


Flowchart of the goto Statement:

PICT, Pune. Mrs. Madhuri S. Patil


goto Statement:
The goto statement can be used to jump from anywhere to anywhere within a function. Also referred to as an
unconditional jump statement.

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

2. Skip Even Numbers

3. Prints a 3x3 grid of coordinates using nested loops

4. Prompts the user to enter a positive number

5. Password Validation

6. Print Multiples of 3 Except 9(continue and goto)

7. Find First Prime Number

PICT, Pune. Mrs. Madhuri S. Patil


What is Arrays(need of Array):
An array is a collection of variables in same datatype.

PICT, Pune. Mrs. Madhuri S. Patil


Types of Array

PICT, Pune. Mrs. Madhuri S. Patil


1D Array:

data_type array_name [size];

or

data_type array_name [size1] [size2]...[sizeN];

PICT, Pune. Mrs. Madhuri S. Patil


data_type array_name [size] = {value1, value2, ... valueN};

PICT, Pune. Mrs. Madhuri S. Patil


printf("%d\n", numbers[i]);

PICT, Pune. Mrs. Madhuri S. Patil


Example:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int i;
printf("Array elements are:\n");
for (i = 0; i < 5; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}

PICT, Pune. Mrs. Madhuri S. Patil


2D Array:
Syntax:
data_type array_name [i][j];
OR
data type array_name[size_i] [size_j];

Example:
int matrix[3][4];
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

PICT, Pune. Mrs. Madhuri S. Patil


Example:
#include <stdio.h>
int main() {

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

printf("Matrix elements are:\n");

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n"); // New line after each row
}

return 0;
}

PICT, Pune. Mrs. Madhuri S. Patil


Basic Array Operations:
Following are the basic Array operations.

● Traverse − Print each element in the array one by one.


● Insertion − At the specified index, adds an element.
● Deletion − The element at the specified index is deleted.
● Search − Uses the provided index or the value to search for an element.
● Sort

PICT, Pune. Mrs. Madhuri S. Patil


Traverse
#include <stdio.h>

int main() {

int arr[] = {1, 2, 3, 4, 5};

int N = sizeof(arr) / sizeof(arr[0]);

printf("Array elements using loop: ");

for (int i = 0; i < N; i++)

printf("%d ", arr[i]);

printf("\n");

return 0;

PICT, Pune. Mrs. Madhuri S. Patil


● Insertion

PICT, Pune. Mrs. Madhuri S. Patil


What is branching

ability to manage the execution flow is provided by branching statements in the C programming language

PICT, Pune. Mrs. Madhuri S. Patil


Branching and Iteration are two fundamental concepts in programming, particularly in the context of controlling the flow of a program.

1. Branching

Refers to the process in programming where the flow of execution can diverge, or "branch," depending on certain conditions.

Examples include if, else, else if, and switch statements.

2. Iteration

Refers to the process of repeating a block of code multiple times.

Examples include for, while, and do-while loops.

PICT, Pune. Mrs. Madhuri S. Patil


● Control flow structures:
They are fundamental building blocks that allow you to dictate the order in which
statements are executed in a program. By controlling the flow of execution, you
can make decisions, loop through code multiple times, and manage how your
program responds to different inputs or conditions.

PICT, Pune. Mrs. Madhuri S. Patil


1. Sequential Flow
This is the default mode where statements are executed one after the other in the order they appear in
the program.

int a = 10;

int b = 20;

int sum = a + b;

printf("Sum is %d", sum);

PICT, Pune. Mrs. Madhuri S. Patil


2. Decision-Making (Selection) Structures

structures allow the program to make decisions

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");
}

b. if-else Statement (if-then-else)

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");
}

PICT, Pune. Mrs. Madhuri S. Patil


c. else if Ladder

The else if ladder allows for multiple conditions to be checked sequentially.

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");
}

PICT, Pune. Mrs. Madhuri S. Patil


conditional expression:
A conditional expression is a shorthand way of writing an if-else statement, and it is commonly known as the ternary operator.
The ternary operator is an expression, not a statement.

Syntax:

condition ? expression_if_true : expression_if_false;


This is the expression that is evaluated first. It must be something that results in either true (non-zero) or false (zero).#include <stdio.h>

int main() {
int a = 10, b = 20;
int max;

max = (a > b) ? a : b;

printf("The maximum value is %d\n", max);

return 0;
}

// printf("%s\n", (age >= 18) ? "You are an adult." : "You are a minor.");

PICT, Pune. Mrs. Madhuri S. Patil


Switch:
The switch statement in C is a control flow structure that allows you to execute one out of many possible blocks of code based on the value of a
variable or an expression.

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
}

PICT, Pune. Mrs. Madhuri S. Patil


#include <stdio.h>

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


Fall-Through Behavior: If you omit the break statement after a case, the execution will "fall through" to the next case, executing all
the code until it encounters a break or the end of the switch block.

switch (day) {
case 1:
printf("Monday\n");
case 2:
printf("Tuesday\n");
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
}

If day is 1, this code would print:

Monday
Tuesday
Wednesday

PICT, Pune. Mrs. Madhuri S. Patil


Do- while loop:
The do-while loop in C is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true.

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


Comparison with while Loop:

● 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) {

printf("This will not print.\n");

PICT, Pune. Mrs. Madhuri S. Patil


For loop:
● The for loop in C is a control flow statement that allows you to repeatedly execute a block of code a specific number of times.
● It is particularly useful when you know in advance how many times you want to iterate through the loop.

Basic Syntax

for (initialization; condition; increment) {


// Code to be executed in each iteration
}
Example

#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 5; i++) {


printf("%d\n", i);
}

return 0;
}

PICT, Pune. Mrs. Madhuri S. Patil


Key Features and Variations

1. Multiple Initializations and Increments:

You can initialize and increment multiple variables within a for loop.

for (int i = 0, j = 10; i < j; i++, j--) {


printf("i = %d, j = %d\n", i, j);
}

2. Omitting Parts of the Loop:

Any part of the for loop (initialization, condition, increment) can be omitted, but the semicolons ; must remain.

for (;;) {
// Infinite loop
}

3. Using break and continue:

break: Immediately exits the loop.


continue: Skips the remaining code in the current iteration and proceeds to the next iteration.
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i); // Print odd numbers
}

PICT, Pune. Mrs. Madhuri S. Patil


4. Nested for Loops:

● You can nest for loops inside each other to handle multi-dimensional data or perform repeated tasks.

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 2; j++) {
printf("i = %d, j = %d\n", i, j);
}
}

PICT, Pune. Mrs. Madhuri S. Patil


break;
A control statement used to immediately terminate the execution of a loop
break statement is encountered inside a loop (like for, while, or do-while) or a switch block,
Syntax:
Break;

Example with for Loop:


#include <stdio.h>

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


‘continue’

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.

PICT, Pune. Mrs. Madhuri S. Patil


goto;
● This statement allows you to jump to another part of the program, usually
within the same function.
● transfer control to a specific label within the same function
● alter the flow of execution in non-linear ways

Syntax:
goto label;

label:
// Code to be executed after the jump

PICT, Pune. Mrs. Madhuri S. Patil


Example:
#include <stdio.h>

int main() {
int num = 0;

printf("Enter a positive number: ");


scanf("%d", &num);

if (num < 0) {
goto error; // Jump to the error label if the number is negative
}

printf("You entered a positive number: %d\n", num);


return 0;

error:
printf("Error: You entered a negative number.\n");
return 1;
}

PICT, Pune. Mrs. Madhuri S. Patil


Arrays:
A collection of elements of the same data type

stored in contiguous memory locations

It allows you to store and manipulate a fixed-size sequence of elements efficiently

Useful for organizing data

Features of Arrays:
Fixed Size:

Contiguous Memory:

Same Data Type:

PICT, Pune. Mrs. Madhuri S. Patil


Declaring Arrays:

data_type array_name[size];

Example: Declaring Arrays:

int numbers[5]; // An array of 5 integers

float values[10]; // An array of 10 floats

char name[20]; // An array of 20 characters (commonly used for strings)

Example: Initializing Arrays

int numbers[5] = {10, 20, 30, 40, 50}; // Array of integers

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)

PICT, Pune. Mrs. Madhuri S. Patil


PICT, Pune. Mrs. Madhuri S. Patil
Need of array:
1. Efficient Data Storage
● Fixed-Size Storage:
● Contiguous Memory Allocation:
2. Simplified Data Management
● Single Variable for Multiple Data
● Ease of Looping
3. Random Access
● Index-Based Access
● Direct Access
4. Data Consistency and Homogeneity
● Homogeneous Data
● Type-Specific Operations
5. Optimized Memory Usage
● Memory Efficiency
● Memory Locality
6. Foundation for Other Data Structures
● Building Block
● Multi-Dimensional Arrays
7. Simplification of Algorithms
● Algorithm Implementation
● Temporary Storage
8. Ease of Passing Data to Functions
● Function Arguments
● Returning Multiple Values
PICT, Pune. Mrs. Madhuri S. Patil
Types of arrays:
arrays are classified based on their dimensionality and the data they hold
1. One-Dimensional Arrays:

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];

int numbers[5] = {10, 20, 30, 40, 50};

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.

PICT, Pune. Mrs. Madhuri S. Patil


Accessing Elements:

int first_element = numbers[0]; // Accessing the first element

Modifying Elements:

numbers[2] = 35; // Changing the value of the third element

Looping Through the Array:

for (int i = 0; i < 5; i++) {


printf("Element at index %d: %d\n", i, numbers[i]);
}

Calculating the Sum and Average:

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);

PICT, Pune. Mrs. Madhuri S. Patil


Example:
#include <stdio.h>

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


2. Multi-Dimensional Arrays:
Multi-dimensional arrays are arrays of arrays, and they allow you to represent more complex data structures like
matrices or tables.

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.

PICT, Pune. Mrs. Madhuri S. Patil


Accessing Elements:

int element = matrix[1][2]; // Accessing element at row 1, column 2

Modifying Elements:

matrix[0][1] = 20; // Changing the value of the element at row 0, column 1

Looping Through the Array:


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
Calculating the Sum of All Elements:
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += matrix[i][j];
}
}
printf("Sum of all elements: %d\n", sum);

PICT, Pune. Mrs. Madhuri S. Patil


Example:
#include <stdio.h>

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


b. Three-Dimensional Arrays
A three-dimensional array extends the concept to three dimensions, representing data in a 3D space (e.g., layers of matrices).

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:

char name[6] = "Hello";

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.

PICT, Pune. Mrs. Madhuri S. Patil


Accessing Characters:

char first_char = name[0]; // Accessing the first character

Modifying Characters:

name[1] = 'a'; // Changing the second character

Looping Through the String:

for (int i = 0; name[i] != '\0'; i++) {


printf("%c ", name[i]);
}

String Length:

int length = 0;
while (name[length] != '\0') {
Length++;
}
printf("Length of the string: %d\n", length);

PICT, Pune. Mrs. Madhuri S. Patil


#include <stdio.h>

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;
}

PICT, Pune. Mrs. Madhuri S. Patil


4. Array of Pointers:

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:

char *names[3] = {"Alice", "Bob", "Charlie"};

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).

PICT, Pune. Mrs. Madhuri S. Patil


Accessing Strings:

char *first_name = names[0]; // Accessing the first string

Modifying Strings:

names[1] = "David"; // Changing the second string to a new string

Looping Through the Array of Strings:

for (int i = 0; i < 3; i++) {

printf("Name %d: %s\n", i+1, names[i]);

PICT, Pune. Mrs. Madhuri S. Patil


5. Dynamic Arrays:

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:

data_type *array_name = (data_type *)malloc(size * sizeof(data_type));

Example:

int *numbers = (int *)malloc(5 * sizeof(int));

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.

PICT, Pune. Mrs. Madhuri S. Patil


Creating a Dynamic Array:

int *array = (int *)malloc(size * sizeof(int));

Reallocating Memory:

array = (int *)realloc(array, new_size * sizeof(int));

Freeing Memory:

free(array);

PICT, Pune. Mrs. Madhuri S. Patil


#include <stdio.h>
#include <stdlib.h> // For malloc and free

int main() {
int *numbers;
int size;

printf("Enter the number of elements: ");


scanf("%d", &size);

// Dynamic memory allocation


numbers = (int *)malloc(size * sizeof(int));

// Check if memory has been allocated successfully


if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initializing and printing the array


for (int i = 0; i < size; i++) {
numbers[i] = i + 1;
printf("Element at index %d: %d\n", i, numbers[i]);
}

// Freeing allocated memory


free(numbers);

return 0;
}

PICT, Pune. Mrs. Madhuri S. Patil


Summary of Array Types:
● One-Dimensional Array: Linear sequence of elements.

● Two-Dimensional Array: Matrix or table-like structure.

● Three-Dimensional Array: Data in 3D space (e.g., cubes of data).

● Character Array (String): Sequence of characters used to represent text.

● 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.

PICT, Pune. Mrs. Madhuri S. Patil


Operations:
Summary of Array Operations

● Declaration and Initialization: Creating arrays and initializing them with values.

● Accessing Elements: Retrieving specific elements using their index.

● Modifying Elements: Changing the value of specific elements.

● Looping Through Arrays: Using loops to iterate over all elements.

● Sum and Average Calculations: Performing arithmetic operations on array elements.

● Dynamic Memory Allocation: Creating arrays with a size determined at runtime and managing their memory manually.

PICT, Pune. Mrs. Madhuri S. Patil


Primitive operations on Strings
● Strings in C are arrays of characters terminated by a null character ('\0').

● 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)

PICT, Pune. Mrs. Madhuri S. Patil


1. String Initialization

Literal Initialization: You can initialize a string using a string literal.

char str[] = "Hello, World!";

Character Array Initialization: You can also initialize each character manually.

char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};

PICT, Pune. Mrs. Madhuri S. Patil


2. String Input/Output

Input: Use scanf or gets (although gets is unsafe and should be avoided) to read a string.

char str[50];

scanf("%s", str); // Reads a word (stops at a whitespace)

Output: Use printf to output a string.

printf("%s\n", str);

PICT, Pune. Mrs. Madhuri S. Patil


3. String Length
Use the strlen function from the <string.h> library to find the length of a string.

#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

PICT, Pune. Mrs. Madhuri S. Patil


5. String Concatenation

● Use the strcat function to concatenate (append) one string to another.

#include <string.h>

char str1[20] = "Hello, ";

char str2[] = "World!";

strcat(str1, str2); // str1 now contains "Hello, World!"

6. String Comparison

● Use the strcmp function to compare two strings lexicographically.

#include <string.h>

char str1[] = "Hello";

char str2[] = "World";

int result = strcmp(str1, str2); // result < 0 because "Hello" < "World"

PICT, Pune. Mrs. Madhuri S. Patil


7. String Search

● Use the strchr function to find the first occurrence of a character in a string.

#include <string.h>

char str[] = "Hello, World!";

char *pos = strchr(str, 'W'); // pos points to the "W" in "World!"

● Use the strstr function to find the first occurrence of a substring in a string.

#include <string.h>

char str[] = "Hello, World!";

char *pos = strstr(str, "World"); // pos points to the "World!" in str

PICT, Pune. Mrs. Madhuri S. Patil


8. String Tokenization
● Use the strtok function to split a string into tokens based on a set of delimiters.
#include <string.h>
char str[] = "Hello, World!";
char *token = strtok(str, " ,!");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ,!");
}

9. String Reverse

● You can write a loop to reverse a string in place.


void reverse(char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}

PICT, Pune. Mrs. Madhuri S. Patil


10. String to Integer Conversion

● Use the atoi function to convert a string to an integer.

#include <stdlib.h>

char str[] = "1234";

int num = atoi(str); // num is 1234

11. Integer to String Conversion

● Use the sprintf function to convert an integer to a string.

char str[10];

int num = 1234;

sprintf(str, "%d", num); // str now contains "1234"

PICT, Pune. Mrs. Madhuri S. Patil


#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100], result[200];

// Input two strings


printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);

// Remove the newline character at the end if present


str1[strcspn(str1, "\n")] = '\0';

printf("Enter the second string: ");


fgets(str2, sizeof(str2), stdin);

// Remove the newline character at the end if present


str2[strcspn(str2, "\n")] = '\0';

// Concatenate the two strings


strcpy(result, str1); // Copy the first string to result
strcat(result, " "); // Add a space between the two strings
strcat(result, str2); // Append the second string to result

// Print the concatenated string and its length


printf("Concatenated String: %s\n", result);
printf("Length of the concatenated string: %lu\n", strlen(result));

return 0;
}
PICT, Pune. Mrs. Madhuri S. Patil
Summary

● String Initialization: Assign or initialize strings.


● String Input/Output: Read or print strings.
● String Length: Measure string length using strlen.
● String Copy: Copy strings using strcpy.
● String Concatenation: Concatenate strings using strcat.
● String Comparison: Compare strings using strcmp.
● String Search: Search for characters or substrings using strchr and strstr.
● String Tokenization: Split strings into tokens using strtok.
● String Reverse: Reverse a string using custom logic.
● String to Integer Conversion: Convert strings to integers using atoi.
● Integer to String Conversion: Convert integers to strings using sprintf.

PICT, Pune. Mrs. Madhuri S. Patil


What is the output of this program:
w=3
n=1
x=6
m=1
y=9
repeat until(n<5)
n=1
n=n+1
Repeat until(n<=5) while(m<5)
w=w+1 Mrs. Madhuri S. Patil
PICT, Pune.

You might also like