0% found this document useful (0 votes)
3 views22 pages

Unit 2&3

This document covers programming concepts in C, focusing on loops, arrays, and strings. It explains different types of loops (for, while, do-while), their syntax, and examples, as well as how to declare, initialize, and manipulate arrays and strings. Additionally, it introduces common array operations and string library functions.

Uploaded by

pushpalathan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Unit 2&3

This document covers programming concepts in C, focusing on loops, arrays, and strings. It explains different types of loops (for, while, do-while), their syntax, and examples, as well as how to declare, initialize, and manipulate arrays and strings. Additionally, it introduces common array operations and string library functions.

Uploaded by

pushpalathan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

PPS Unit-II
Unit-II Programming for problem solving
Syllabus:

Loops, Arrays, Strings: Loops: Iteration with for, while, do- while loops, break and
continue statements. Arrays: One and two dimensional arrays, creating, accessing and
manipulating elements of arrays Strings: Introduction to strings, handling strings as array
of characters, string functions available in C arrays of strings.

Notes:

Loops in C

Loops in C programming are used to repeat a block of code until the specified condition
is met. It allows programmers to execute a statement or group of statements multiple
times without writing the code again and again.

Types of Loops in C

There are 3 looping statements in C:

Let's discuss all 3 types of loops in C one by one.

for Loop

for loop is an entry-controlled loop, which means that the condition is checked before
the loop's body executes.

Syntax

for (initialization; condition; updation) {

// body of for loop

}
2
PPS Unit-II
The various parts of the for loop are:

• Initialization: Initialize the variable to some initial value.

• Test Condition: This specifies the test condition. If the condition evaluates to
true, then body of the loop is executed. If evaluated false, loop is terminated.

• Update Expression: After the execution loop’s body, this expression


increments/decrements the loop variable by some value.

• Body of Loop: Statements to repeat. Generally enclosed inside {} braces.

Flowchart of for Loop

Example:

#include <stdio.h>

int main() {

int i;

// Loop to print numbers from 1 to 5

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

printf( "%d ", i + 1);

return 0;

Output

12345
3
PPS Unit-II

while Loop

A while loop is also an entry-controlled loop in which the condition is checked before
entering the body.

Syntax

while (condition) {

// Body of the loop

Only the condition is the part of while loop syntax, we have to initialize and update loop
variable manually.

Flowchart of while loop:

Example:

#include <stdio.h>

int main() {

// Initialization expression

int i = 0;

// Test expression

while(i <= 5) {

printf("%d ", i + 1);

// update expression

i++;
4
PPS Unit-II
}

return 0;

Output

123456

do-while Loop

The do-while loop is an exit-controlled loop, which means that the condition is checked
after executing the loop body. Due to this, the loop body will execute at least
once irrespective of the test condition.

Syntax

do {

// Body of the loop

} while (condition);

Like while loop, only the condition is the part of do while loop syntax, we have to do the
initialization and updating of loop variable manually.

Flowchart of do-while Loop

Example:

#include <stdio.h>

int main() {

// Initialization expression

int i = 0;

do

{
5
PPS Unit-II
// loop body

printf( "%d ", i);

// Update expression

i++;

// Condition to check

} while (i <= 10);

return 0;

Output

0 1 2 3 4 5 6 7 8 9 10

Infinite Loop

An infinite loop is executed when the test expression never becomes false, and the body
of the loop is executed repeatedly. A program is stuck in an Infinite loop when the
condition is always true. Mostly this is an error that can be resolved by using Loop Control
statements.

Using for loop:

#include <stdio.h>

int main () {

// This is an infinite for loop as the condition expression is blank

for ( ; ; ) {

printf("This loop will run forever.");

return 0;

Output

This loop will run forever.


This loop will run forever.
This loop will run forever.
...

Using While loop:

#include <stdio.h>
6
PPS Unit-II
int main() {

while (1)

printf("This loop will run forever.\n");

return 0;

Output

This loop will run forever.


This loop will run forever.
This loop will run forever.
...

Using the do-while loop:

#include <stdio.h>

int main() {

do {

printf("This loop will run forever.");

} while (1);

return 0;

Output

This loop will run forever.


This loop will run forever.
This loop will run forever.
...

Nested Loops

Nesting loops means placing one loop inside another. The inner loop runs fully for each
iteration of the outer loop. This technique is helpful when you need to perform multiple
iterations within each cycle of a larger loop, like when working with a two-dimensional
array or performing tasks that require multiple levels of iteration.

Example:

#include <stdio.h>

int main() {
7
PPS Unit-II
int i, j;

// Outer loop runs 3 times

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

// Inner loop runs 2 times for each outer loop iteration

for (j = 0; j < 2; j++) {

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

return 0;

Output

i = 0, j = 0

i = 0, j = 1

i = 1, j = 0

i = 1, j = 1

i = 2, j = 0

i = 2, j = 1

Loop Control Statements

Loop control statements in C programming are used to change execution from its
normal sequence.

Name Description

break The break statement is used to terminate the loop statement.

When encountered, the continue statement skips the remaining body


continue
and jumps to the next iteration of the loop.

goto goto statement transfers the control to the labeled statement.

Example:

#include <stdio.h>
8
PPS Unit-II
int main() {

int i;

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

if (i == 3) {

// Exit the loop when i equals 3

break;

printf("%d ", i);

printf("\n");

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

if (i == 3) {

// Skip the current iteration when i equals 3

continue;

printf("%d ", i);

printf("\n");

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

if (i == 3) {

// Jump to the skip label when i equals 3

goto skip;

printf("%d ", i);

skip:

printf("\nJumped to the 'skip' label %s", "when i equals 3.");

return 0;

}
9
PPS Unit-II
Output

012

0124

012

Jumped to the 'skip' label when i equals 3.

Arrays in C
An array is a collection of elements of the same data type stored in contiguous
memory locations.

It allows you to store multiple values under a single variable name.

Example:

int marks[5] = {85, 90, 78, 92, 88};

This creates an array of 5 integers:

Index: 0 1 2 3 4

Value: 85 90 78 92 88

Advantages of Arrays

Access elements easily using indices


Efficient memory usage
Easier sorting, searching, and iteration
Compact and organized code

Declaring an Array

Syntax:

data_type array_name[size];

Example:

int num[10];

float price[5];

char grade[3];

Initializing Arrays

Method 1 – Immediate Initialization

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

Method 2 – Partial Initialization


10
PPS Unit-II
int a[5] = {1, 2}; // Remaining elements = 0

Method 3 – Compiler decides size

int a[] = {10, 20, 30, 40};

Accessing Array Elements

You can access elements using the index, starting from 0.

#include <stdio.h>

int main() {

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

printf("Third element = %d", a[2]);

return 0;

Output:

Third element = 30

Input and Output of Arrays

#include <stdio.h>

int main() {

int a[5];

printf("Enter 5 numbers:\n");

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

scanf("%d", &a[i]);

printf("You entered:\n");

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

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

return 0;

Memory Representation of Array

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


11
PPS Unit-II
and assuming 4 bytes per integer:

Index Value Address

0 1 1000

1 2 1004

2 3 1008

3 4 1012

4 5 1016

Types of Arrays

Type Description Example

One-Dimensional Linear list of elements int a[5];

Two-Dimensional Matrix/Tabular data int mat[3][3];

Multi-Dimensional More than 2 dimensions int cube[3][3][3];

One-Dimensional Array Example

#include <stdio.h>

int main() {

int i, sum = 0;

int marks[5] = {90, 85, 88, 92, 76};

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

sum += marks[i];

printf("Total = %d", sum);

return 0;

Output:

Total = 431

Two-Dimensional Array (Matrix)


12
PPS Unit-II
A 2D array is a collection of rows and columns.

int a[2][3] = {

{1, 2, 3},

{4, 5, 6}

};

Row Col Value

a[0][0] 1 First Row

a[1][2] 6 Second Row

Example – Matrix Input and Output

#include <stdio.h>

int main() {

int a[2][3];

printf("Enter elements (2x3):\n");

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

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

scanf("%d", &a[i][j]);

printf("Matrix:\n");

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

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

printf("%d ", a[i][j]);

printf("\n");

return 0;

}
13
PPS Unit-II
Common Array Programs

Problem Description Hint

Find Largest Element Compare elements Use a max variable

Find Sum/Average Add all elements Use loop and count

Reverse Array Swap start–end Use temp variable

Sort Array Arrange ascending Use bubble sort

Matrix Addition Add a[i][j]+b[i][j] Nested loops

Matrix Transpose Flip row/column b[j][i]=a[i][j]

Example – Find Largest Element

#include <stdio.h>

int main() {

int a[5] = {12, 45, 67, 23, 89};

int max = a[0];

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

if(a[i] > max)

max = a[i];

printf("Largest = %d", max);

return 0;

Example – Reverse Array

#include <stdio.h>

int main() {

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

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

temp = a[i];

a[i] = a[j];
14
PPS Unit-II
a[j] = temp;

printf("Reversed Array: ");

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

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

return 0;

Output:

Reversed Array: 5 4 3 2 1

Multidimensional Arrays

Example – 3D Array:

int cube[2][2][2] = {

{{1,2}, {3,4}},

{{5,6}, {7,8}}

};

Accessing: cube[1][0][1] = 6

Strings in C
A string in C is a sequence of characters terminated by a null character '\0'.
It is represented as a character array.

Example:

char name[] = "Eswar";

This actually stores:

'E' 's' 'w' 'a' 'r' '\0'

Declaring and Initializing Strings

Method 1: Direct Initialization

char str[] = "Hello";

Method 2: Character by Character


15
PPS Unit-II
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};

Method 3: Using Pointer

char *str = "Hello";

Input and Output of Strings

Using scanf() and printf()

#include <stdio.h>

int main() {

char name[20];

printf("Enter your name: ");

scanf("%s", name); // stops at space

printf("Hello %s", name);

return 0;

scanf() stops reading when a space or newline is found.

Using gets() and puts()

#include <stdio.h>

int main() {

char name[30];

printf("Enter your name: ");

gets(name); // reads spaces too

puts(name); // prints the whole string

return 0;

gets() is unsafe and removed from modern C standards.


Use fgets(name, sizeof(name), stdin) instead.

Using fgets()

#include <stdio.h>

int main() {

char name[30];
16
PPS Unit-II
printf("Enter your name: ");

fgets(name, sizeof(name), stdin);

printf("You entered: %s", name);

return 0;

String Library Functions (<string.h>)

You must include:

#include <string.h>

strlen() – Find string length

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello";

printf("Length = %lu", strlen(str));

return 0;

Output:

Length = 5

strcpy() – Copy one string to another

#include <stdio.h>

#include <string.h>

int main() {

char src[] = "C Language";

char dest[20];

strcpy(dest, src);

printf("Copied String: %s", dest);

return 0;

}
17
PPS Unit-II
strncpy() – Copy limited characters

strncpy(dest, src, n);

Copies only n characters and doesn’t add '\0' automatically if n < src length.

strcat() – Concatenate two strings

#include <stdio.h>

#include <string.h>

int main() {

char a[20] = "Hello ";

char b[] = "World";

strcat(a, b);

printf("Concatenated: %s", a);

return 0;

Output:

Concatenated: Hello World

strcmp() – Compare two strings

#include <stdio.h>

#include <string.h>

int main() {

char a[] = "abc";

char b[] = "abd";

int result = strcmp(a, b);

if(result == 0)

printf("Strings are equal");

else if(result < 0)

printf("a is smaller");

else

printf("a is greater");

return 0;
18
PPS Unit-II
}

strrev() – Reverse a string (non-standard but supported in some compilers like


Turbo C)

#include <stdio.h>

#include <string.h>

int main() {

char str[20] = "Hello";

printf("Reversed: %s", strrev(str));

return 0;

Not part of standard C library.


strlwr() and strupr() (non-standard)

Convert to lowercase or uppercase.

strlwr(str); // hello

strupr(str); // HELLO

For portable code, use loops with tolower() / toupper() from <ctype.h>.

strchr() and strrchr()

Find the first or last occurrence of a character.

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "banana";

char *pos = strchr(str, 'a');

printf("First 'a' at position: %ld", pos - str);

return 0;

strstr() – Find substring

#include <stdio.h>

#include <string.h>

int main() {
19
PPS Unit-II
char text[] = "C is powerful";

char word[] = "power";

char *pos = strstr(text, word);

if(pos)

printf("Found at index: %ld", pos - text);

else

printf("Not found");

return 0;

Manual Operations on Strings

Find Length (without strlen)

int stringLength(char str[]) {

int i = 0;

while(str[i] != '\0')

i++;

return i;

Reverse a String (manually)

#include <stdio.h>

#include <string.h>

int main() {

char str[100], temp;

int i, j;

printf("Enter a string: ");

gets(str);

i = 0;

j = strlen(str) - 1;

while(i < j) {

temp = str[i];
20
PPS Unit-II
str[i] = str[j];

str[j] = temp;

i++;

j--;

printf("Reversed String: %s", str);

return 0;

Count vowels, consonants, digits, spaces

#include <stdio.h>

int main() {

char str[100];

int vowels = 0, consonants = 0, digits = 0, spaces = 0;

printf("Enter a string: ");

gets(str);

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

if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||

str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')

vowels++;

else if((str[i]>='a' && str[i]<='z')||(str[i]>='A' && str[i]<='Z'))

consonants++;

else if(str[i]>='0' && str[i]<='9')

digits++;

else if(str[i]==' ')

spaces++;

printf("Vowels: %d\nConsonants: %d\nDigits: %d\nSpaces: %d", vowels, consonants,


digits, spaces);

return 0;
21
PPS Unit-II
}

6. Array of Strings (2D Character Array)

Example:

#include <stdio.h>

int main() {

char names[3][10] = {"Ram", "Shyam", "Ravi"};

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

printf("%s\n", names[i]);

return 0;

Common Interview Programs

Problem Hint Function / Logic

Check Palindrome Compare with reversed string

Count Words Count spaces + 1

Remove Spaces Shift characters left

Compare two strings manually Loop and compare each character

Find frequency of characters Use an int array of size 256

Summary Table

Function Purpose

strlen() Get length

strcpy() Copy string

strcat() Concatenate

strcmp() Compare

strchr() Find character

strstr() Find substring


22
PPS Unit-II
Function Purpose

strrev() Reverse string (non-standard)

strupr() / strlwr() Case change (non-standard)

You might also like