0% found this document useful (0 votes)
2 views39 pages

ICP Module - 3 Notes

Uploaded by

Santosh Patil
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)
2 views39 pages

ICP Module - 3 Notes

Uploaded by

Santosh Patil
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

INTRODUCTION TO C PROGRAMMING

1BPLC205E
MODULE-03
Arrays and Strings: Introduction, Declaration and Initialization of One-dimensional and
Two-Dimensional Arrays, Declaring and Initializing String Variables, Example programs
using arrays ,Reading Strings from Terminal, Writing Strings to Screen, Arithmetic
Operations on Characters, Comparison of Two Strings, String-handling Functions.
Textbook: Chapter 8.1 to 8.6, Chapter 9.2 to 9.5, 9.7, 9.8

INTORDUCTION
We can use arrays to represent not only simple lists of values but also tables of data in two, three or
more dimensions. In this chapter, we introduce the concept of an array and discuss how to use it to
create and apply the following types of arrays.

One-dimensional arrays
Two-dimensional arrays

Multidimensional arrays

DATA STRUCTURES
C supports a rich set of derived and user-defined data types in addition to a variety of fundamental types
as shown below:
INITIALIZATION OF ONE-DIMENSIONAL ARRAYS

After declaring an array, the elements of the array must be initialized with values.

If array elements are not initialized, they may contain garbage values (random values in memory).

Array initialization can be done in two ways:

1. Compile-time initialization

2. Run-time initialization

Compile-Time Initialization
Compile-time initialization means assigning values to array elements during declaration.

General Syntax
datatype arrayname[size] = {value1, value2, value3, ...};
Example

int number[3] = {0,0,0};

This creates an array of size 3 and initializes all elements to zero.

Memory representation

Index Value

number[0] 0

number[1] 0

number[2] 0

Partial Initialization
If the number of initial values is less than the array size, the remaining elements are automatically
initialized to zero.
Example

float total[5] = {0.0, 15.75, -10};


Array values become

Index Value

total[0] 0.0

total[1] 15.75
total[2] -10

total[3] 0

total[4] 0
Omitting the Size
The array size can be omitted if values are provided.

Example

int counter[] = {1,1,1,1};

Compiler automatically determines the size.

Array size = 4

Character Array Initialization


Character arrays can be initialized using characters.
Example

char name[] = {'J','o','h','n','\0'};

This stores the string "John".

Another simpler method

char name[] = "John";

The compiler automatically adds the null character '\0' at the end.

Example: Partial Character Initialization


char city[5] = {'B'};

Result

Index Value

city[0] B

city[1] NULL

city[2] NULL

city[3] NULL

city[4] NULL
Error in Initialization

If the number of values exceeds the array size, the compiler produces an error.
Example

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

This is illegal in C.

Run-Time Initialization
Run-time initialization means assigning values during program execution.
This method is useful for large arrays.

Example

int x[3]

scanf("%d %d %d", &x[0], &x[1], &x[2]);

Values are entered using keyboard input.

Example Program – Runtime Initialization

#include<stdio.h>
int main()

{
int x[5];

int i;

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

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

{
scanf("%d",&x[i]);
}

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

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

{
printf("%d ",x[i]);

return 0;
}
Frequency Counting Example
Arrays are often used to count occurrences of values.

Example problem:
Count how many marks fall within different ranges.

Array

int group[11] = {0};

Each element represents a range of marks.

Example

Marks Range Array Index

0–9 group[0]

10–19 group[1]

20–29 group[2]

If a student score is 59

index = 59 / 10

Result
index = 5

So

group[5]++
TWO-DIMENSIONAL ARRAYS
A two-dimensional array is used to store tabular data (rows and columns).

Example table

Salesgirl Item1 Item2 Item3

A 150 200 250

B 300 325 350

C 100 150 200

D 250 275 300


This table contains 4 rows and 3 columns.

Total values = 12
Representation of Two-Dimensional Array

In mathematics

[
V_{ij}
]

i = row number
j = column number
In C

v[i][j]

Example

v[4][3]
4 rows and 3 columns.

Declaration of Two-Dimensional Arrays


Syntax

datatype arrayname[row][column];

Example

int marks[4][3];

Indexing Rule

In C:

 Rows start from 0

 Columns start from 0

Example

Element Representation

First row first column marks[0][0]

Second row third column marks[1][2]

Memory Representation of 2D Arrays

C stores arrays row-wise.


Example

int A[2][3]

Memory order
A[0][0]

A[0][1]
A[0][2]
A[1][0]

A[1][1]

A[1][2]

This is called row-major order.

Example Program – Multiplication Table Using 2D Array


#include<stdio.h>

int main()

{
int table[5][5];

int i,j;

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

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

table[i][j] = (i+1)*(j+1);

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

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

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

printf("\n");

return 0;

INITIALIZING TWO-DIMENSIONAL ARRAYS


Like 1D arrays, 2D arrays can be initialized during declaration.

Example
int table[2][3] = {0,0,0,1,1,1};

Result

Row 1 → 0 0 0
Row 2 → 1 1 1

Row-wise Initialization

int table[2][3] =

{
{0,0,0},

{1,1,1}

};

Matrix Style Initialization


int matrix[3][3] =

{1,2,3},

{4,5,6},

{7,8,9}

};

Automatic Size Deduction


If all values are given, the first dimension can be omitted.

Example

int matrix[][3] =

{1,2,3},

{4,5,6}

};

Partial Initialization
If some values are missing, they are initialized to zero.

Example

int m[2][3] =

{1,1},

{2}

};
Result

110

200

Initialize Entire Matrix with Zero


Shortcut method
int m[3][5] = {0};

All elements become 0.

Multidimensional Array Storage

Example

int A[2][3][3]

Storage order

A[0][0][0]
A[0][0][1]
A[0][0][2]

A[0][1][0]

...

The rightmost index changes first.

Program – Transpose of a Matrix


Transpose means interchanging rows and columns.

Example

Matrix

123
456

Transpose

14
25
36

Program

#include<stdio.h>

int main()
{

int A[3][3],B[3][3];

int i,j;

printf("Enter matrix:\n");

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

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

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

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

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

B[j][i] = A[i][j];

}
}

printf("Transpose matrix:\n");

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

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

printf("%d ",B[i][j]);
}
printf("\n");

return 0;

Program – Matrix Multiplication


Matrix multiplication rule

C[i][j] = A[i][k] * B[k][j]

Program

#include<stdio.h>
int main()

{
int A[3][3],B[3][3],C[3][3];

int i,j,k;
for(i=0;i<3;i++)

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

C[i][j] = 0;

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

C[i][j] += A[i][k]*B[k][j];

return 0;

}
Advantages of Two-Dimensional Arrays
1. Used to represent matrices

2. Useful for tabular data

3. Efficient storage of rows and columns

4. Simplifies matrix operations

Arrays provide a powerful mechanism for storing and manipulating large collections of data in C. One-
dimensional arrays are used for storing linear lists of elements, while two-dimensional arrays are used
for representing tabular data such as matrices and tables. Proper initialization and indexing are essential
for correct array operations.

MATRIX MULTIPLICATION USING ARRAYS

Matrix multiplication is an important application of two-dimensional arrays.

Matrices are often used in:

 scientific calculations
 engineering problems

 graphics processing

 data analysis

A matrix is a rectangular arrangement of numbers in rows and columns.

Example:
Matrix A

[
A=

1&2&3
4&5&6

Matrix B

[
B=

7&8\
9 & 10 \
11 & 12
]

Rule for Matrix Multiplication

Matrix multiplication is possible only when:

[
\text{Number of columns in matrix A} = \text{Number of rows in matrix B}
]

Example

Matrix A → 2 × 3
Matrix B → 3 × 2

Result matrix C → 2 × 2

Mathematical Formula
Each element of the result matrix is calculated as:

[
C[i][j] = \sum (A[i][k] * B[k][j])
]

Where

 i → row index

 j → column index

 k → intermediate index

Algorithm for Matrix Multiplication

Step 1: Start

Step 2: Read matrices A and B

Step 3: Check multiplication condition

Step 4: For each element

C[i][j] = 0
for k = 0 to n

C[i][j] = C[i][j] + A[i][k] * B[k][j]


Step 5: Display result matrix

Step 6: Stop

C Program for Matrix Multiplication


#include<stdio.h>

int main()
{
int A[3][3], B[3][3], C[3][3];

int i, j, k;

printf("Enter elements of matrix A:\n");

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

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

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

printf("Enter elements of matrix B:\n");

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

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

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

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

for(j=0;j<3;j++)
{
C[i][j] = 0;

for(k=0;k<3;k++)

C[i][j] += A[i][k] * B[k][j];

printf("Resultant matrix:\n");

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

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

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

}
printf("\n");

return 0;

Multidimensional arrays extend the concept of arrays to multiple dimensions and are useful for
representing complex data structures such as matrices, tables, and multidimensional datasets. Matrix
multiplication is one of the most important applications of two-dimensional arrays. Dynamic arrays
further enhance the flexibility of arrays by allowing memory allocation during program execution,
making C a powerful language for handling large and varying datasets.

MATRIX MULTIPLICATION USING ARRAYS

Matrix multiplication is an important application of two-dimensional arrays in C.


A matrix is a rectangular arrangement of numbers organized in rows and columns.

Example matrix:

Matrix A (2 × 3)
1 2 3

4 5 6
Matrix B (3 × 2)

7 8

9 10

11 12

Condition for Matrix Multiplication


Two matrices can be multiplied only when:

Number of columns in the first matrix = Number of rows in the second matrix

Example

A= 2 × 3

B=3×2

Result = 2 × 2

Formula for Matrix Multiplication


The element of the resulting matrix is calculated as

[
C[i][j] = \sum (A[i][k] × B[k][j])
]

Where:

 i → row index of matrix A


 j → column index of matrix B

 k → intermediate index

Example

C[1][1] = A[1][1]*B[1][1] + A[1][2]*B[2][1] + A[1][3]*B[3][1]

Algorithm for Matrix Multiplication


Step 1: Start
Step 2: Input matrices A and B
Step 3: Check multiplication condition
Step 4: Initialize result matrix C to zero
Step 5: Multiply matrices using nested loops
for i
for j

C[i][j] = 0

for k

C[i][j] += A[i][k] * B[k][j]

Step 6: Display matrix C


Step 7: Stop

C Program for Matrix Multiplication


#include<stdio.h>

int main()
{

int A[3][3], B[3][3], C[3][3];

int i, j, k;

printf("Enter elements of matrix A:\n");


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

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

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

printf("Enter elements of matrix B:\n");

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

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

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

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

C[i][j] = 0;

for(k=0;k<3;k++)
{
C[i][j] += A[i][k] * B[k][j];

printf("Result matrix:\n");

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

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

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

printf("\n");

return 0;

STRINGS IN C
A string is a sequence of characters treated as a single data item.

Examples of strings:

"Hello"

"Programming"

"Man is obviously made to think."


In C, a string is written inside double quotation marks (" ").

Example:

printf("Hello World");
This prints the string Hello World.
String Constant
A string constant is any sequence of characters enclosed within double quotes.
Example:

"Hello"

"C Programming"

"Welcome to Programming"

If we want to print double quotes inside a string, we must use **escape character **.

Example:

printf("\"Well Done!\"");
Output

"Well Done!"

Common String Operations

Strings are widely used in programming because they help create readable and meaningful programs.

Common operations on strings include:

1. Reading strings from input


2. Writing strings to output
3. Copying strings

4. Comparing strings

5. Combining strings

6. Extracting substrings

These operations are performed using library functions.

Declaring String Variables


C does not provide a separate string data type.

Instead, strings are represented using character arrays.

General form:

char string_name[size];

Example declarations:
char city[10];
char name[30];

char message[50];

Here:

 char → data type

 city, name, message → array names

 number inside brackets → maximum size of string

Important Rule
When storing a string in C, the compiler automatically adds a null character (\0) at the end.

Example:

"HELLO"
Stored in memory as

| H | E | L | L | O | \0 |

Therefore, the array size must be string length + 1.

Initializing String Variables


Strings can be initialized in two ways.

Method 1: Using String Literal


char city[9] = "NEW YORK";
The string contains:

N E W (space) Y O R K

Total characters = 8

One extra space is required for null character


Total size = 9

Method 2: Using Character List

char city[9] = {'N','E','W',' ','Y','O','R','K','\0'};


In this case we must explicitly include the null character.
Automatic Size Determination
The size of array may be omitted.

Example

char string[] = {'G','O','O','D','\0'};

The compiler automatically determines the size.

Large Array Initialization


Example:

char str[10] = "GOOD";

Memory representation
| G | O | O | D | \0 | | | | | |

Remaining elements are filled with NULL values.

Illegal String Declaration

The following declaration is incorrect.

char str2[3] = "GOOD";

Reason:
Array size is smaller than the string.

This produces a compile-time error.

Invalid String Assignment


In C, we cannot assign strings directly.

Example:

char str1[10];
str1 = "HELLO"; // Error

Also
char s1[4] = "abc";

char s2[4];
s2 = s1; // Error

Arrays cannot be used as left operand of assignment operator.

Terminating Null Character


The null character (\0) indicates the end of the string.

Why is it needed?

Because strings are stored inside arrays whose size may be larger than the actual string.
Example

char name[20] = "RAM";

Memory representation
| R | A | M | \0 | garbage | garbage |

The null character tells the compiler where the string ends.

READING STRINGS FROM TERMINAL


Strings can be read using:

1. scanf

2. getchar

3. gets

Using scanf Function


The format specifier %s is used to read strings.
Example

char address[20];

scanf("%s", address);

Important rule:
When reading strings, ampersand (&) is not required.

Limitation of scanf
The scanf("%s") function stops reading input when it encounters whitespace.
Whitespace includes:

 space

 tab

 newline

Example input

NEW YORK

Result
address = NEW

Only the first word is stored.

Reading Multiple Words

Example

char adr1[10], adr2[10];


scanf("%s %s", adr1, adr2);
Input

NEW YORK

Output

adr1 = NEW

adr2 = YORK

Field Width in scanf


We can limit the number of characters read.

Example

char name[10];

scanf("%5s", name);

If input is

KRISHNA
Stored value

KRISH
INTRODUCTION TO C PROGRAMMING MODULE-03 AZ Documents

Remaining characters remain unread.

Reading a Full Line


To read a complete line including spaces, we can use:

%[^\n]
Example

char line[80];

scanf("%[^\n]", line);

This reads characters until newline is encountered.

Using getchar

The getchar() function reads one character at a time.

Example
char line[80];
int i = 0;

char ch;

while((ch = getchar()) != '\n')

line[i] = ch;

i++;

}
line[i] = '\0';

This reads an entire line of text.

Using gets Function


A simpler method for reading strings is gets().

Syntax
gets(str);
Example
char line[80];

gets(line);
This reads a full line including spaces.

Example program

char line[80];

gets(line);
printf("%s", line);

WRITING STRINGS TO SCREEN


Strings can be displayed using:

1. printf

2. putchar
3. puts

Using printf Function

The %s format specifier is used to print strings.

Example

printf("%s", name);
This prints the entire string.

Field Width in printf


Example

%10.4s

Meaning:

 Print first 4 characters

 In a field width of 10

Example

printf("%10.4s", name);
Left Justified Output
Using minus sign

%-10.4s

This prints the string left aligned.

Using putchar Function


putchar() prints a single character.

Example

putchar('A');

Equivalent to

printf("%c", 'A');

Example for printing string

char name[6] = "PARIS";

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

{
putchar(name[i]);

Using puts Function

puts() prints an entire string and automatically moves to the next line.

Syntax

puts(str);

Example

char line[80];

gets(line);

puts(line);
This reads a line and prints it.
Difference Between printf and puts

Function Output

printf("%s",str) Prints string

Prints string and moves to next


puts(str)
line

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

char name[50];

printf("Enter your name: ");

gets(name);

printf("Hello ");

puts(name);

return 0;

Advantages of Strings
1. Makes programs more readable
2. Allows text processing

3. Useful in user interfaces

4. Supports text manipulation


Strings in C are implemented using character arrays and are terminated with a null character (\0).
Various functions such as scanf, gets, printf, puts, and putchar are used for string input and output.
Strings are widely used in programming for handling textual data and performing operations such as
copying, comparing, and concatenating.
STRING HANDLING FUNCTIONS IN C
In C programming, strings are stored as arrays of characters.

Example:
char name[20] = "oma";

C does not provide built-in operators for string operations such as:

 copying
 comparing

 joining

 finding length

Therefore C provides string handling functions in the header file:


#include <string.h>

These functions make string operations easy.

Common String Handling Functions


The most frequently used string functions are:

Function Purpose

strlen() Find length of string

strcpy() Copy one string to another

strcat() Concatenate (join) strings

strcmp() Compare two strings

strncpy() Copy first n characters

strncmp() Compare first n characters

strncat() Concatenate n characters

strstr() Find substring

strchr() Find first occurrence of character

strrchr() Find last occurrence of character


1. strlen() Function

Purpose
strlen() finds the length of a string.

It counts the number of characters excluding the null character \0.

Syntax
strlen(string_name);

Example

#include <stdio.h>
#include <string.h>
int main()
{
char name[] = "Iqra";
printf("Length = %d", strlen(name));
return 0;
}
Output

Length = 4

Explanatio
umaa → 4 characters

2. strcpy() Function
Purpose
strcpy() copies one string into another string.

Syntax
strcpy(destination, source);

Example
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20];
char s2[] = "Hello";

strcpy(s1, s2);

printf("%s", s1);

return 0;
}

Output

Hello

Explanation
s2 → copied into s1

3. strcat() Function

Purpose
strcat() joins two strings.
This process is called concatenation.

Syntax

strcat(string1, string2);
string2 is added to the end of string1.

Example
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "Hello ";
char s2[] = "World";
strcat(s1, s2)
printf("%s", s1);
return 0;
}

Output

Hello World

Explanation

s1 = "Hello "
s2 = "World"

After strcat

s1 = "Hello World"

4. strcmp() Function

Purpose
strcmp() compares two strings.

Syntax

strcmp(string1, string2);

Return Values

Return value Meaning

strings are
0
equal

string1 <
negative
string2

string1 >
positive
string2
Example
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = "Apple";
char s2[] = "Apple";

if(strcmp(s1, s2) == 0)
printf("Strings are equal");

return 0;
}

Output

Strings are equal

5. strncpy() Function

Purpose
Copies only first n characters of a string.

Syntax

strncpy(destination, source, n);

Example

char s1[20];
char s2[] = "Programming";

strncpy(s1, s2, 5);


Result

s1 = Progr

6. strncmp() Function

Purpose
Compares first n characters of two strings.
Syntax
strncmp(s1, s2, n);

Example
strncmp("apple", "apricot", 2);

Result

0
because first two characters are same.

7. strncat() Function

Purpose

Concatenates first n characters of a string.

Syntax
strncat(s1, s2, n);

Example

char s1[20] = "Hello ";


char s2[] = "World";

strncat(s1, s2, 3);


Result

Hello Wor

8. strstr() Function

Purpose
Searches a substring inside another string.

Syntax

strstr(main_string, sub_string);
Example
strstr("Programming", "gram");

Result

pointer to "gram"

If substring not found → returns NULL.

9. strchr() Function

Purpose

Finds the first occurrence of a character in a string.

Syntax

strchr(string, character);

Example
strchr("banana", 'a');

Result

pointer to first 'a'

10. strrchr() Function

Purpose
Finds the last occurrence of a character.

Syntax

strrchr(string, character);

Example

strrchr("banana", 'a');

Result
pointer to last 'a'
Example Program Using String Functions
#include<stdio.h>
#include<string.h>

int main()
{

char s1[20] = "Hello";


char s2[] = "World";

printf("Length = %d\n", strlen(s1));

strcat(s1,s2);
printf("After concat: %s\n", s1);

strcpy(s1,s2);
printf("After copy: %s\n", s1);

printf("Compare result: %d\n", strcmp(s1,s2));

return 0;
}

Advantages of String Functions


1. Simplifies string manipulation

2. Reduces programming effort


3. Improves code readability

4. Saves development time

String handling functions in C are provided by the <string.h> library to perform


operations on strings such as copying, concatenation, comparison, and length
calculation. Important functions include strlen(), strcpy(), strcat(), and strcmp().
These functions allow efficient manipulation of character strings stored in arrays.

You might also like