0% found this document useful (0 votes)
6 views15 pages

Ip U-Iii

This document provides an introduction to arrays in C programming, detailing their definition, properties, advantages, and disadvantages. It covers single-dimensional and multi-dimensional arrays, including declaration, initialization, and example programs for various operations like sorting and searching. Additionally, it introduces strings in C, explaining their declaration, initialization, and methods for reading and writing strings.
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)
6 views15 pages

Ip U-Iii

This document provides an introduction to arrays in C programming, detailing their definition, properties, advantages, and disadvantages. It covers single-dimensional and multi-dimensional arrays, including declaration, initialization, and example programs for various operations like sorting and searching. Additionally, it introduces strings in C, explaining their declaration, initialization, and methods for reading and writing strings.
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
You are on page 1/ 15

INTRODUCTION TO PROGRAMMING I B.

TECH I SEM (R23)

MODULE – III
Arrays
Definition:
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
Properties of Array:
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 2
bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantage of Array:
1. Code Optimization: Less code to the access the data.
2. Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3. Easy to sort data: To sort the elements of array, we need a few lines of code only.
4. Random Access: We can access any element randomly using the array.
Disadvantage of Array:
Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList.
Array Types:
 Single-Dimensional Arrays (One-Dimensional Arrays)
 Multi-Dimensional Arrays (Two-Dimensional Arrays)
One-Dimensional Arrays
Declaration of an Array:
We can declare an array in the c language in the following way.
data_type array_name[array_size];
For example:
int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of array. It
means array arr can only contain 10 elements of int type. Index of an array starts from 0 to
size-1 i.e first element of arr array will be stored at arr[0] address and last element will occupy
arr[9].

1
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

Initialization of Array:
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Array Example Program:


#include <stdio.h>
int main()
{
int marks[5]; // declaration of array
marks[0] = 80; // initialization of array
marks[1] = 60;
marks[2] = 70;
marks[3] = 85;
marks[4] = 75;
// traversal of array
for (int i = 0; i < 5; i++)
{
printf("%d \n", marks[i]);
} // end of for loop
return 0;
}
Output:
80
60
70
85
75

Declaration with Initialization:


We can initialize the array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as
the following code.
int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.


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

2
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

int marks[5] = {20, 30, 40, 50, 60}; // declaration and initialization
of array traversal of array
for (i = 0; i < 5; i++)
{
printf("%d \n", marks[i]);
}
return 0;
}
Output:
20
30
40
50
60

Write a C program to read and display 5 values


#include <stdio.h>
void main()
{

int i;
int arr[5];
for(i=0; i<5; i++)
{
printf("Index -> %d : ",i);
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<5; i++)
{
printf("%d \t", arr[i]);
}
}
Output:
Index -> 0 : 20
Index -> 1 : 30
Index -> 2 : 40
Index -> 3 : 50
Index -> 4 : 60

Elements in array are: 20 30 40 50 60

Array Example: Sorting an array


In the following program, we are using bubble sort method to sort the array in
ascending order.
#include <stdio.h>
void main()
{

3
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

int i, j, temp;
int a[10] = {12, 9, 6, 104, 32, 44, 14, 78, 34, 23};
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < 10; j++)
{
if (a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for (i = 0; i < 10; i++)
{
printf("%d\n", a[i]);
}
}
Output:
Printing Sorted Element List ...
6
9
12
14
23
32
34
44
78
104

Program to Search an Element in Array.


#include <stdio.h>
void main() {
int search, flag = 0;
int arr[5] = {34, 54, 12, 65, 92};
// Getting the element to search
printf("Enter the element to search: ");
scanf("%d", &search);
// Searching the element
for (int i = 0; i < 5; i++) {
if (arr[i] == search) {
printf("Element found at position: %d\n", i);
flag = 1;
break;
}
}

4
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

if (flag == 0) {
printf("Element not found in the array.\n");
}
}
Output:
Enter the element to search: 54
Element found at position: 1

Two-Dimensional Arrays
The two dimensional array in C language is represented in the form of rows and
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
Declaration of two dimensional Array:
The syntax to declare the 2D array is given below.
Syntax:
data_type array_name[rows][columns];
or
data_type array_name[size1][size2];
Example 1:
int twodimen[4][3];
Example 2:
int a[3][4];

Initialization of 2D Array:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Accessing Two-Dimensional Array Elements:


An element in a two-dimensional array is accessed by using the subscripts, i.e., row
index and column index of the array.

Two-Dimensional Array or 2D Array Example:


#include <stdio.h>
int main()
{
int i, j;
int arr[4][3] = {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}};
// traversing 2D array
for (i = 0; i < 4; i++)

5
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

{
for (j = 0; j < 3; j++)
{
printf("arr[%d] [%d] = %d \n", i, j, arr[i][j]);
} // end of j
} // end of i
return 0;
}
Output:
arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 2
arr[1] [1] = 3
arr[1] [2] = 4
arr[2] [0] = 3
arr[2] [1] = 4
arr[2] [2] = 5
arr[3] [0] = 4
arr[3] [1] = 5
arr[3] [2] = 6

Write a C program Addition of Two Matrices?


#include <stdio.h>
void main()
{
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
int c[3][3];
int i, j, m = 3, n = 3;
printf("\nThe additon of two matrics");
for (i = 0; i < m; i++)
{
printf("\n");
for (j = 0; j < n; j++)
{
c[i][j] = a[i][j] + b[i][j];
printf("\t%d", c[i][j]);
}
}
}
Output:
The additon of two matrics
2 2 3
4 6 6
7 8 10

Write a C program Multiplication of Two Matrices?


#include <stdio.h>

6
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

void main()
{
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
int c[3][3];
int i, j, k, m = 3, n = 3;
printf("\nThe multiplication of two matrics");
for (i = 0; i < m; i++)
{
printf("\n");
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (k = 0; k < n; k++)
{
c[i][j]+=a[i][k]*b[k][j];

}
printf("\t%d", c[i][j]);
}
}
}

Output:
The multiplication of two matrics
1 2 3
4 5 6
7 8 9

STRINGS
In „C‟ language the group of characters, digits, and symbols enclosed within double
quotation (" ") marks are called as string otherwise a string is an array of characters and
terminated by NULL character which is denoted by the escape sequence „\0‟.
Declaration of String:
C does not support string as a data type. However, it allows us to represent strings as
character arrays. In C, a string variable is any valid C variable name and it is always declared
as an array of characters.
The general form of declaration of a string variable is,
Syntax:
char string_name[size];
The size determines the number of characters in the string name.
Note: In declaration of string size must be required to mention otherwise it gives an error.
Ex:
char str[]; // Invalid
char str[0]; // Invalid

7
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

char str[-1]; // Invalid


char str[10]; // Valid
char a[9]; //Valid
Using this declaration the compiler allocates 9 memory locations for the variable a ranging
from 0 to 8.

Here, the string variable a can hold maximum of 9 characters including NULL(\0)
character.
Initializing Array String:
Syntax:
char string_name[size]={“string” };
Note: In Initialization of the string if the specific number of character is not initialized it then
rest of all character will be initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL
Note: In initialization of the string we cannot initialized more than size of string elements.
Ex: char str[2]={'5','+','A','B'}; // Invalid
Different ways of initialization can be done in various ways:
1. Initializing locations character by character.
2. Partial array initialization.
3. Initialization without size.
4. Array initialization with a string.
Initializing locations character by character
Consider the following declaration with initialization,
char b[9]={„C‟,„O‟,„M‟,„P‟,„U‟,„T‟,„E‟,„R‟};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations
are initialized with the characters in the order specified. The remaining locations are
automatically initialized to null characters.

Partial Array Initialization:


If the character to be initialized is less than the size of the array, then the characters
are stored sequentially from left to right. The remaining locations will be initialized to NULL
characters automatically.
Ex: char a[10]={„R‟, „A‟, „M‟, „A‟ };

8
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

The compiler allocates 10 bytes for the variable a ranging from 0 to 9 and initializes
first four locations with the ASCII characters of „R‟, „A‟, „M‟, „A‟. The remaining locations
are automatically filled with NULL characters (i.e.,\0).

Initialization without size:


Consider the declaration along with the initialization
char b[]={„C‟,„O‟,„M‟,„P‟,„U‟,„T‟,„E‟,„R‟};
In this declaration, the compiler will set the array size to the total number of initial
values i.e., 8. The character will be stored in these memory locations in the order specified.

Array Initialization with a String:


Consider the declaration with string initialization.
char b[ ] = “COMPUTER”;
Here, the string length is 8 bytes. But, string size is 9 bytes. So the compiler reserves
8+1 memory locations and these locations are initialized with the characters in the order
specified. The string is terminated by \0 by the compiler.

The string “COMPUTER” contain 8 characters, because it is a string. It always ends


with null character. So, the array is 9 bytes (i.e string length+1 byte for null character).

Reading and Writing Strings:


The “%s” control string can be used in scanf() statement to read a string from the
terminal and the same may be used to write string to the terminal in printf() statement.
Example:
char name[10];
scanf(“%s”, name);
printf(“%s”, name);
Example Program 1:
#include <stdio.h>
void main()
{
char str1[14] = { 'C', ' ', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm',
'i', 'n', 'g', '\0'};
char str2[14] = "c programming";
printf("Char Array Value is: %s\n", str1);

9
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

printf("String Literal Value is: %s\n", str2);


}
Output:
Char Array Value is: C Programming
String Literal Value is: c programming
Example Program 2:
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Srihari
Your name is Srihari.

String Input / Output Functions


The strings can be read from the keyboard and can be displayed onto the monitor
using various functions. The various input and output functions that are associated with can
be classified as,

Input Functions:
1. scanf(): Reads input from the standard input (usually the keyboard) and stores it in
variables.
Syntax: int scanf(const char *format, ...);
Example: scanf("%d %f %s", &age, &height, name);
2. getchar(): Reads a single character from the standard input.
Syntax: int getchar(void);
Example: char c = getchar();

10
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

3. getch(): Reads a single character from the standard input without echoing it to the
console.
Syntax: int getch(void); (Note: getch() is not part of the C standard library, but is
available in some implementations like conio.h)
Example: char c = getch();
4. getche(): Reads a single character from the standard input and echoes it to the console.
Syntax: int getche(void); (Note: getche() is not part of the C standard library, but is
available in some implementations like conio.h)
Example: char c = getche();
5. gets(): Reads a string from the standard input until a newline character is encountered.
Syntax: char *gets(char *str);
Example: gets(name); (Note: gets() is deprecated due to security concerns)

Output Functions:
1. printf(): Prints output to the standard output (usually the console).
Syntax: int printf(const char *format, ...);
Example: printf("Hello, %s!", name);

2. putchar(): Prints a single character to the standard output.


Syntax: int putchar(int c);
Example: putchar('A');
3. putch(): Prints a single character to the standard output.
Syntax: int putch(int c); (Note: putch() is not part of the C standard library, but is available in
some implementations like conio.h)
Example: putch('A');
4. puts(): Prints a string to the standard output followed by a newline character.
Syntax: int puts(const char *str);
Example: puts("Hello, World!");
Example program for String Input and Output Functions
#include <stdio.h>
#include <conio.h>
int main()
{
int age;
float height;
char name[20];
char ch;

// Using scanf()
printf("Enter your age, height, and name: ");
scanf("%d %f %s", &age, &height, name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Name: %s\n", name);

// Using getchar()

11
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

printf("Enter a character: ");


ch = getchar();
printf("You entered: %c\n", ch);

// Using getch()
printf("Enter a character (without echo): ");
ch = getch();
printf("You entered: %c\n", ch);

// Using getche()
printf("Enter a character (with echo): ");
ch = getche();
printf("\nYou entered: %c\n", ch);

// Using gets()
printf("Enter your full name: ");
gets(name);
printf("Your full name is: %s\n", name);

// Using putchar()
putchar('\n');
putchar('A');
printf("\n");

// Using putch()
putch('\n');
putch('B');
printf("\n");

// Using puts()
puts("Hello, World!");

return 0;
}
Output:
Enter your age, height, and name: 31 5.6 Srihari
Age: 31
Height: 5.60
Name: Srihari

Enter a character: X
You entered: X
Enter a character (without echo): Y
You entered: Y
Enter a character (with echo): Z
You entered: Z

12
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

Enter your full name: P Srihari


Your full name is: P Srihari

B
Hello, World!

Character Manipulations / Character Functions


Here are some common character manipulation functions in C
1. isalpha(): Checks if a character is an alphabet.
2. isdigit(): Checks if a character is a digit.
3. isalnum(): Checks if a character is an alphabet or digit.
4. islower(): Checks if a character is in lowercase.
5. isupper(): Checks if a character is in uppercase.
6. tolower(): Converts a character to lowercase.
7. toupper(): Converts a character to uppercase.
Example Program:
#include <stdio.h>
#include <ctype.h>

int main() {
char ch = 'A';
// Character functions
printf("Is 'A' an alphabet? %d\n", isalpha(ch));
printf("Is 'A' a digit? %d\n", isdigit(ch));
printf("Is 'A' an alphabet or digit? %d\n", isalnum(ch));
printf("Is 'A' in lowercase? %d\n", islower(ch));
printf("Is 'A' in uppercase? %d\n", isupper(ch));
printf("Convert 'A' to lowercase: %c\n", tolower(ch));
printf("Convert 'A' to uppercase: %c\n", toupper(ch));

return 0;
}

Output:
Is 'A' an alphabet? 1
Is 'A' a digit? 0
Is 'A' an alphabet or digit? 1
Is 'A' in lowercase? 0
Is 'A' in uppercase? 1
Convert 'A' to lowercase: a
Convert 'A' to uppercase: A

13
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

String Functions or String Manipulations or String Operations


There are many important string functions defined in "string.h" library.
No Function Description

1 strlen(string_name) returns the length of string name.


2 strcpy(destination, source) copies the contents of source string to destination string.
strcat(first_string, concats or joins first string with second string. The result
3
second_string) of the string is stored in first string.
strcmp(first_string, compares the first string with second string. If both
4
second_string) strings are same, it returns 0.
5 strrev(string) returns reverse string.
6 strlwr(string) returns string characters in lowercase.
7 strupr(string) returns string characters in uppercase.

Example Program:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
// strlen()
printf("Length of str1: %d\n", strlen(str1));
// strcpy()
strcpy(str3, str1);
printf("Copied string: %s\n", str3);
// strcat()
strcat(str3, str2);
printf("Concatenated string: %s\n", str3);
// strcmp()
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
// strrev()
strrev(str1);
printf("Reversed str1: %s\n", str1);
// strlwr()
strlwr(str2);
printf("Lowercase str2: %s\n", str2);
// strupr()
strupr(str3);
printf("Uppercase str3: %s\n", str3);

14
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur
INTRODUCTION TO PROGRAMMING I B.TECH I SEM (R23)

return 0;
}

Output:
Length of str1: 5
Copied string: Hello
Concatenated string: HelloWorld
Strings are not equal
Reversed str1: olleH
Lowercase str2: world
Uppercase str3: HELLOWORLD
Arrays of Strings
An array of strings in C is a two-dimensional array of character types. Each String is
terminated with a null character (\0). It is an application of a 2d array.
Using Two-dimensional Arrays:
Creating a String Array is one of the applications of two-dimensional Arrays. To get a
picture of the arrangement, observe the below representation:
For suppose we want to create an Array of 3 Strings of size 5:

Every String in a String Array must terminate with a null Character. It is the property of a
String in C.
Syntax to create a String Array:
char Array[rows][columns] = {"String1", "String2"...};
Example String Array:
Observe that when we assign the number of rows and columns, we need to consider
the Null Character to the length.
#include <stdio.h>
void main()
{
int i;
char Array[3][6] = {"Black", "Blame", "Block"};
printf("String Array: \n");
for (i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
}
Output:
String Array:
Black
Blame
Block
~ ~ END OF THE UNIT ~ ~

15
P. Srihari, Assistant Professor, Narayana Engineering College, Gudur

You might also like