0% found this document useful (0 votes)
21 views26 pages

Cmodule 3

Uploaded by

krupamariam008
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)
21 views26 pages

Cmodule 3

Uploaded by

krupamariam008
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/ 26

MODULE 3

C Array

 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.
 It also has the capability to store the collection of derived data types, such as
pointers, structure, etc.
 The array is the simplest data structure where each data element can be
randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store
the marks of a student in 6 subjects, then we don't need to define different variables for
the marks in the different subject. Instead of that, we can define an array which can store
the marks in each subject at the contiguous memory locations.

Properties of Array

The array contains the following properties.

 Each element of an array is of same data type and carries the same size.
 Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
 Elements of the array can be randomly accessed .

Advantage of C Array

1) Code Optimization: Less code to the access the data.


2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.

1
Disadvantage of C Array

1) In an array, it is essential to identify the number of elements to be stored.


2) It is a static structure. It means that in an array, the memory size is fixed.
3) When it comes to insertion and deletion, it is a bit difficult because the
elements are stored sequentially and the shifting operation is expensive

Declaration of C Array

We can declare an array in the c language in the following way.

data_typearray_name[array_size];

example

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C 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;

2
C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

Array Initialization with Declaration without Size

If we initialize an array using an initializer list, we can skip declaring the size of the
array as the compiler can automatically deduce the size of the array in these cases.

int marks[]={20,30,40,50,60}; The size of the arrays is 5 which is automatically


deduced by the compiler.

C program to declare and initialize the array in C.

#include<stdio.h>

voidmain(){

int i=0;

int marks[5]={20,30,40,50,60};//declaration and initialization of array

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

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

getch();

Output

20

30

40

3
50

60

Program to take values from the user and store them in an array

#include <stdio.h>

int main() {

int marks[10], i, n;

printf("Enter number of elements: ");

scanf("%d", &n);

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

printf("Enter number%d: ",i+1);

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

printf("Displaying integers: ");

// printing elements of an array

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

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

getch(); }

Two Dimensional Array in C

 The two-dimensional array can be defined as an array of arrays.


 The 2D array is organized as matrices which can be represented as the
collection of rows and columns.

4
Declaration of Two-Dimensional Array in C

The basic form of declaring a 2D array with x rows and y columns in C is shown
below.

Syntax:

data_typearray_name[x][y];

where,

data_type: Type of data to be stored in each element.

array_name: name of the array

x: Number of rows. y: Number of columns.

Example:int x[10][20];

Initialization of Two-Dimensional Arrays in C

The various ways in which a 2D array can be initialized are as follows:

1. Initialization of 2D array using Initializer List

First Method:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

The above array has 3 rows and 4 columns. The elements in the braces from left
to right are stored in the table also from left to right. The elements will be filled in
the array in order: the first 4 elements from the left will be filled in the first row,
the next 4 elements in the second row, and so on.

Second Method (better):

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

5
This type of initialization makes use of nested braces. Each set of inner braces
represents one row. In the above example, there is a total of three rows so there
are three sets of inner braces. The advantage of this method is that it is easier to
understand.

2. Initialization of 2D array using Loops

We can use any C loop to initialize each member of a 2D array one by one as
shown in the below example.

Example:

int x[3][4];

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

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

x[i][j] = i + j;

This method is useful when the values of each element have some sequential
relation.

Accessing Elements of Two-Dimensional Arrays in C

Elements in 2D arrays are accessed using row indexes and column indexes. Each
element in a 2D array can be referred to by:

Syntax:

array_name[i][j]

where,

i: The row index.

j: The column index.

Example:

6
int x[2][1];

The above example represents the element present in the third row and second
column.

Two-dimensional array example in C

The two-dimensional array can be declared and defined in the following way.

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

program:

#include<stdio.h>

voidmain(){

int i=0,j=0;

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

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

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

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

} }getch(); }

Character Array String :Strings in C

 String is a sequence of characters that are treated as a single data item and
terminated by a null character '\0'.
 A string is actually a one-dimensional array of characters in C language.
 These are often used to create meaningful and readable programs.
 The C String is stored as an array of characters.

7
C String Declaration Syntax

char string_name[size];

In the above syntax string_name is any name given to the string variable and size is
used to define the length of the string, i.e the number of characters strings will
store.

C String Initialization

A string in C can be initialized in different ways. We can initialize a C string in 4


different ways which are as follows:

1. Assigning a String Literal without Size

String literals can be assigned without size. Here, the name of the string str acts as
a pointer because it is an array.

char str[] = "Rekha";

2. Assigning a String Literal with a Predefined Size

String literals can be assigned with a predefined size. But we should always account
for one extra space which will be assigned to the null character.

char str[50] = "cprogramming";

3. Assigning Character by Character with Size

We can also assign a string character by character. But we should remember to set
the end character as ‘\0’ which is a null character.

char str[10] = { 'G','o','o','d','m','o','r','n','i','g',''\0'};

4. Assigning Character by Character without Size

We can assign character by character without size with the NULL character at the
end. The size of the string is determined by the compiler automatically.

char str[] = { 'G','o','o','d','m','o','r','n','i','g',''\0'};

8
C String Example:

Read a String Input From the User(C Input Output (I/O)-printf and scanf
example:)

#include<conio.h>

#include<string.h>

void main()

{ char name[20];

printf("Enter a name: ");

scanf("%s", name);

printf("Your name is :::::%s.", name);

getch();}

C gets() and puts() functions(Reading line of Text)

 C gets() function:The gets() function enables the user to enter some


characters followed by the enter key. The gets() allows the user to enter the
space-separated strings. It returns the string entered by the user.
 C puts() function:The puts() function is very much similar to printf() function.
The puts() function returns an integer value representing the number of
characters being printed on the console.

Example:

#include<stdio.h>

#include <string.h>

void main(){

char name[50];

printf("Enter your name: ");

gets(name); //reads string from user


9
printf("Your name is: ");

puts(name); //displays string

getch();}

String Handling Functions:

C language supports a large number of string handling functions that can be used to
carry out many of the string manipulations. These functions are packaged in the
string.h library. Hence, you must include string.h header file in your programs to
use these functions.

The following are the most commonly used string handling functions.

Method Description

1. strlen() It is used to show the length of a string


2. strcpy() Copies one string into another
3. strcat() It is used to concatenate(combine) two strings
4. strcmp() It is used to compare two string
5. strrev() It is used to show the reverse of a string
6. strupr(): It is used to converts all the letters in the string to uppercase.
7. strlwr() It is used to convert a given string into lowercase.

1. strlen(): This function can be used to find a string’s length.

Syntax of srtlen():

Length=strlen(Stringname);

Example of strlen():

#include <stdio.h>

#include <string.h>

void main() {

int len;

10
char string[] = "Rekha";

len = strlen(string);

printf("Length of string is: %d ", len);

getch();

Output:The length of the string is: 5

2. strcpy (): This function is used to copy one string to another.

Syntax of srtcpy():

strcpy(DestinationString,Sourcetring);

Example :

#include <stdio.h>

#include <string.h>

void main() {

char str1[20] = "C programming";

char str2[20];

strcpy(str2, str1);

puts(str2);

getch();}

Output:C programming

11
strcat(): This function is used to concatenate two strings.

Syntax of strcat():

strcat(String1,String2);

Example Code:

#include<stdio.h>

#include <string.h>

int main() {

char str1[] = "Good";

char str2[] = "Morning";

strcat(str1, str2);

printf("The concatenated string is: %s\n", str1); return 0;}

Output:The concatenated string is: GoodMorning

3. strcmp(): This function is used to compare two strings.

Syntax of strcmp():

int strcmp(str1, str2);

Example Code:

#include <stdio.h>

#include <string.h>

void main() {

char string1[] = "hello";

char string2[] = "helloo";

int result = strcmp(string1, string2);

if (result == 0){
12
printf("Strings are equal");}

else if(result < 0) {

printf("The first string is less than the second string.\n");

} else {

printf("The first string is greater than the second string.\n");

} getch();}

Output:The first string is smaller than the second string.

4. Strrev(): It is used to reverse a given string. It takes a string as an argument


and returns a pointer to the reversed string.

Syntax of strrev():

char strrev(str);

Example Code:

#include <stdio.h>

#include<string.h>

void main()

{ char s1[50];

printf("Enter your string: ");

gets(s1);

printf("Reversed string is: %s",strrev(s1));

getch();

Output:llew

13
5. strupr(): It takes a string as input and converts all the letters in the string to
uppercase.

Syntax of strupr():

strupr(str);

Example Code:

#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello”;

printf("Original string: %s\n", str);

strupr(str);

printf("Uppercase string: %s\n", str);

return 0;}

Output:Uppercase string: HELLO

6. strlwr(): It takes a string as input and converts all the letters in the string to
lowercase.

Syntax of strlwr():

strlwr(str);

Example Code:

#include <stdio.h>

#include <string.h>

voidmain() {

14
char str[] = "Hello”;

printf("Original string: %s\n", str);

strlwr(str);

printf("Lowercase string: %s\n", str);

getch();} Output:Lowercase string: hello

C Arrays Lab Programs

1. Program to print array elements


include <stdio.h>

void main(){

int i=0;

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

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

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

getch();

2. Program to take N values from the user and store them in an array
#include <stdio.h>

int main() {

int marks[10], i, n;

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

scanf("%d", &n);

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

printf("Enter number%d: ",i+1);

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

printf("Displaying integers: ");

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

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

getch();

3. Program to find the sum of numbers in an array


#include <stdio.h>

void main() {

int marks[10], i, n, sum = 0;

printf("Enter number of elements: ");

scanf("%d", &n);

printf("enter elements");

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

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

16
printf("Displaying integers: ");

// printing elements of an array

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

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

sum += marks[i];

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

getch();

4. Program to find the sum and average of n numbers using arrays


#include <stdio.h>

void main() {

int marks[10], i, n, sum = 0;

double average;

printf("Enter number of elements: ");

scanf("%d", &n);

printf("enter elements");

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

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

printf("Displaying integers: ");

// printing elements of an array

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

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

sum += marks[i];

average = (double) sum / n;

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

printf("Average = %.2lf", average);

getch();

5. Sorting an array
#include<stdio.h>

void main ()

int i, j,temp;

int a[10] = { 10, 9, 7, 101, 23, 44, 12, 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;

18
}

printf("Printing Sorted Element List ...\n");

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

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

6. C Program to Reverse an Array by Printing it from The Last


Element to the First Element
#include <stdio.h>

#define N 1000

void main() {

int arr[N];

int ni,j;

printf("Enter the size of the array: ");

scanf("%d", &n);

printf("Enter an array: ");

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

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

19
// Printing the reverse of the array

printf("Reversed array: ");

for (int i = n-1; i>=0; i--){

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

getch();

7. C program to find largest and smallest number in an array


#include <stdio.h>

void main()

int arr[100], n, i, small, large;

printf("Enter the number of elements you want to insert : ");

scanf("%d", &n);

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

printf("Enter element %d : ", i + 1);

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

small = arr[0];

large = arr[0];

for (i = 1; i< n; i++)

20
if (arr[i] > large)

large = arr[i];

else

small = arr[i];

printf("\nLargest element is : %d", large);

printf("\nSmallest element is : %d", small);

getch();

8. Storing elements in a matrix and printing it.


#include <stdio.h>

void main ()

int arr[3][3],i,j;

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

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

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

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

printf("\n printing the elements ....\n");

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

printf("\n");

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

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

} getch();

9. Example of adding two matrices of size 3x3:


#include <stdio.h>

int main() {

int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int b[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

int c[3][3];

int i, j;

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

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

22
c[i][j] = a[i][j] + b[i][j];

printf("Result of addition: \n");

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

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

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

printf("\n"); }

getch();

10. Addition of two matrix in C


C program for matrix addition:

#include <stdio.h>

int main()

int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf("Enter the number of rows and columns of matrix\n");

scanf("%d%d", &m, &n);

printf("Enter the elements of first matrix\n");

for (c = 0; c < m; c++)

23
for (d = 0; d < n; d++)

scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

for (c = 0; c < m; c++)

for (d = 0 ; d < n; d++)

scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");

for (c = 0; c < m; c++) {

for (d = 0 ; d < n; d++) {

sum[c][d] = first[c][d] + second[c][d];

printf("%d\t", sum[c][d]);

printf("\n");

return 0;

11. Program to multiply two square matrices:


Algorithm

1. Start.

2. Enter the value of m and n (or) order of the first matrix.

24
3. Enter the value of p and q (or) order of the second matrix.

4. Create a matrix of size a[m][n] and b[p][q].

5. Enter the element of matrices row-wise using loops.

6. If the number of columns of the first matrix is not equal to the number of
rows of the second matrix, print matrix multiplication is not possible and exit. If
not, proceed to the next step.

7. Create a third matrix, c of size m x q, to store the product.

8. Set a loop from i=0 to i=m.

9. Set an inner loop for the above loop from j=0 to j=q.

10. Initialise the value of the element (i, j) of the new matrix to 0.

11. Set an inner loop inside the above loop from k=0 to k=p.

12. Using the add and assign operator (+=) store the value of a[i][k] * b[k][j] in
the third matrix, c[i][j].

13. Print the third matrix.

14. Stop.

#include<stdio.h>

void main() {

int a[10][10], b[10][10], c[10][10], n, i, j, k;

printf("Enter the value of N (N <= 10): ");

scanf("%d", & n);

printf("Enter the elements of Matrix-A: \n");

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

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

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


25
}

printf("Enter the elements of Matrix-B: \n");

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

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

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

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

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("The product of the two matrices is: \n");

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

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

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

printf("\n"); }getch();}
26

You might also like