Array Pgms
Array Pgms
Arrays
Program to read and print marks of n students
void main()
{
int i,n;
printf("enter the number of students");
scanf("%d",&n);
int mark[n];
for(i=0;i<n;i++)
{
printf("enter %d marks",i+1);
scanf("%d",&mark[i]);
}
for(i=0;i<n;i++)
{
printf("\n marks of %d student is : %d",i+1,mark[i]);
}
}
Write a program to print smallest number and its position in an
array of size n
#include<stdio.h> small=a[0];
void main() for(i=1;i<n;i++)
{ {
int i,n,small,pos; if(a[i]<small)
printf("enter the size of array"); {
scanf("%d",&n); small=a[i];
int a[n]; pos=i;
printf("enter the elements"); }
for(i=0;i<n;i++) }
{ printf("the smallest element is %d \n
scanf("%d",&a[i]); its position is %d",small,pos);
} }
Program to add all the elements of 1D array
void main()
{
int n,sum=0;
printf("enter size of array");
scanf("%d",&n);
int a[n];
printf("enter array elements");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("\n sum is %d",sum);
}
Program to find if there are duplicates in the array
#include<stdio.h> for(i=0;i<n;i++)
void main() {
{ for(int j=i+1;j<n;j++)
int i,n,small,pos; {
printf("enter the size of array"); if(a[i]==a[j] && i!=j)
scanf("%d",&n); {
int a[n],flag=0; flag=1;
printf("enter the elements"); printf("\n Duplicate number
for(i=0;i<n;i++) found at location %d and %d",i,j);
{ }
scanf("%d",&a[i]); }
} }
}
Inserting an element at a specific position in an array
Expected Output
First Dimension
A two dimensional array is declared as:
data_type array_name[row_size][column_size];
There are two ways of storing a 2-D array can be stored in memory. The first way is row major order and the second is
column major order.
In the row major order the elements of the first row are stored before the elements of the second and third row. That is,
the elements of the array are stored row by row where n elements of the first row will occupy the first nth locations.
(0,0) (0, 1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3) (2,0) (2,1) (2,2) (2,3)
However, when we store the elements in a column major order, the elements of the first column are stored before the
elements of the second and third column. That is, the elements of the array are stored column by column where n
elements of the first column will occupy the first nth locations.
(0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2,1 (3,1) (0,2) (1,2) (2,2) (3,2)
Address(A[I][J] = Base_Address + w{M ( J - 1) + (I - 1)}, if the array elements are stored in column major order.
And, Address(A[I][J] = Base_Address + w{N ( I - 1) + (J - 1)}, if the array elements are stored in row major order.
Where, w is the number of words stored per memory location
m, is the number of columns
n, is the number of rows
I and J are the subscripts of the array element
Initializing Two-dimensional Arrays
Arrays are initialized by writing,
type array_name[size]={list of values};
Example: int marks[2][3] = {90, 87, 78, 68, 62, 71};
The initialization of two-dimensional array is done row by row.
int marks[2][3] = {{90, 87, 78}, {68, 62, 71}};
int marks[ ][3] = {{90, 87, 78}, {68, 62, 71}}; //Only size of 1st dimension can be omitted.
int marks[2][3] = {0}; //Entire 2D array is initialized to zero.
int marks[ ][3] = {{90, 87, 78}}; //Elements of 2nd row will be initialized to zero.
int i, j, marks[2][3];
for(i=0; i<2; i++)
for(j=0; j<3; j++)
Scanf(“%d”, &marks[i][j])
Code to input the values from the keyboard into 2D array
TWO DIMENSIONAL ARRAYS CONTD..
● A two dimensional array is initialized in the same was as a single dimensional array is initialized.
For example,
int marks[2][3]={90, 87, 78, 68, 62, 71};
int marks[2][3]={{90,87,78},{68, 62, 71}};
Write a program to print the elements of a 2D array
#include<stdio.h>
main()
Output
12 34
{
56 32
int arr[2][2] = {12, 34, 56,32};
int i, j;
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t", arr[i][j]);
}
return 0; }
#include <stdio.h>
int main()
{
int arr[7][7]={0};
int row=2, col, i, j ;
arr[0][0] = arr[1] [0] = arr [1][1] = 1;
while(row < 7 )
{
arr [row] [0] = 1;
for (col= 1; col <= row; col++)
arr[row][col] = arr[row-1][col-1]+ arr[row-1][col];
row++;
}
for ( i = 0; i< 7; i++)
{
printf(“\n”);
for ( j = 0; j <= i; j++)
printf(“\t %d ", arr [i] [j] );
}
return 0;
}
Operations on Two-dimensional Arrays
Using two-dimensional arrays, we can perform the following operations on an m X n matrix.
Transpose: Transpose of a m X n matrix A is given as n X m matrix B where,
Bi,j = Aj,i
Sum: Two matrices that are compatible with each other can be added together storing the result in the third
matrix. Two matrices are said to be compatible when they have the same number of rows and columns.
Elements of the matrices can be added by writing:
Ci,j = Ai,j + Bi,j
Difference: Two matrices that are compatible with each other can be subtracted together storing the result in
the third matrix. Elements of the matrices can be subtracted by writing:
Ci,j = Ai,j – Bi,j
Product: Two matrices can be multiplied with each other if the number of columns in the first matrix is equal to
the number of rows in the second matrix. Therefore, m X n matrix A can be multipied with a p X q matrix if n =
p. Elements of the matrices can be multiplied by writing:
Ci,j = ∑ Ai,k Bk,j for k=1 to k < n
Write a program to transpose a 3 × 3 matrix.
#include <stdio.h>
int main()
{
int i, j, mat[3][3], transposed_mat[3][3];
printf("\nEnter the elements of the matrix");
printf("\n*************************");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &mat[i][j]);
}
}
printf("\nThe elements of the matrix are ");
printf("\n*************************");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t", mat[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
transposed_mat[i][j] = mat[j][i];
}
printf("\n The elements of the transposed matrix are ");
printf("\n*************************");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t", transposed_mat[i][j]);
}
return 0;
}
Addition of two matrices
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
printf("Enter the size of first matrix\n");
scanf("%d %d",&m,&n);
printf("Enter the size ofsecond matrix\n");
scanf("%d %d",&p,&q);
if(n==p)
{
printf("Enter the elements of first matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of the second matrix\n");
for(i=0;i<p;i++)
printf("The product of two matrix is\n");
for(i=0;i<m; i++)
{
for(j=0;j<q; j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}
}
else
printf("Multiplication is not possible\n");
return 0;
}
Passing 1D arrays to functions
#include <stdio.h>
void func(int arr[]);
int main() {
int arr[5]={1,2,3,4,5};
func(arr);
}
void func(int arr[5]){
int i;
for (i=0;i<5;i++)
printf("%d\t", arr[i]);
}
str[0] 1000 H
str[1] 1001 E
str[2] 1002 L
str[3] 1003 L
str[4] 1004 O
str[5] 1005 \0
If we declare a string by writing READING STRINGS
char str[100];
Then str can be read from the user by using three ways
use scanf function
using gets() function
using getchar() function repeatedly
● The string can be read using scanf() by writing
scanf(“%s”, str);
● The string can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input. The string inputted using gets() is automatically
terminated with a null character.
● The string can also be read by calling the getchar() repeatedly to read a sequence of single characters (unless a
terminating character is entered) and simultaneously storing it in a character array.
i=0;
ch=getchar(); // get a character
while(ch != ‘ * ’)
{ str[i] = ch; //store the read character in str
i++;
ch=getchar(); //get another character
} str[i] = '\0'; // terminate str with null character
The gets() function can also be to take input from the user.
However, it is removed from the C standard.
Scanf(“%s”, name);
WRITING STRINGS
The string can be displayed on screen using three ways
● use printf() function
● using puts() function
● using putchar()function repeatedly
The string can also be written by calling the putchar() repeatedly to print a sequence of single characters
i=0;
while(str[i] != '\0’)
{ putchar(str[i]); //print the character on the screen
i++;
}
You can initialize strings in a number of ways.
int c = 0;
while (s1[c] == s2[c])
{
if (s1[c] == '\0' || s2[c] == '\0’)
break;
c++;
}
if (s1[c] == '\0' && s2[c] == '\0’)
return 0;
else
return 1;
}
void concatenate(char s1[], char s2[])
{
int c, d; c = 0;
while (s1[c] != '\0’)
{
c++;
}
d=0;
while(s2[d]!='\0’)
{
s1[c] = s2[d];
d++;
c++;
}
s1[c] = '\0';
}
STRING COMPARISION
#include <stdio.h>
#include <string.h>
int main(){
char Str1[100], Str2[100];
int result, i;
printf("\n Please Enter the First String : ");
gets(Str1);
printf("\n Please Enter the Second String : ");
gets(Str2);
for(i = 0; Str1[i] == Str2[i] && Str1[i] == '\0'; i++);
if(Str1[i] < Str2[i])
{
printf("\n str1 is Less than str2");
}
else if(Str1[i] > Str2[i])
{
printf("\n str2 is Less than str1");
}
else
{
printf("\n str1 is Equal to str2");
}
return 0;
}
BINARY SEARCH ON STRINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main(){
int i,n,low,high,mid;
char a[15][15],key[15];
printf("enter the number of names to be added\n"); scanf("%d",&n);
printf("enter the name in alphabetical order\n"); for(i=0;i<n;i++)
{
scanf("%s",&a[i]);
}
printf("\nEnter the name to be searched\n"); scanf("%s",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if (strcmp(key,a[mid])==0)
{
printf("key found at the position %d\n",mid+1);
exit(0);
}
STRUCTURES
INTRODUCTION
● A structure is same as that of records. It stores related information about an entity.
● Structure is basically a user defined data type that can store related information (even of different data types)
together.
● A structure is declared using the keyword struct followed by a structure name. All the variables of the
structures are declared within the structure. A structure type is defined by using the given syntax.
● struct struct-name
struct student
{ data_type var-name;
{ int r_no;
data_type var-name;
... char name[20];
}; char course[20];
float fees;
};
The structure definition does not allocates any memory. It just gives a template that conveys to the C
compiler how the structure is laid out in memory and gives details of the member names. Memory is allocated
for the structure when we declare a variable of the structure. For ex, we can define a variable of student by
writing
struct student stud1;
TYPEDEF DECLARATIONS
● When we precede a struct name with typedef keyword, then the struct becomes a new type. It is
used to make the construct shorter with more meaningful names for types already defined by C or
for types that you have declared. With a typedef declaration, becomes a synonym for the type.
For example, writing
typedef struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
● Now that you have preceded the structure’s name with the keyword typedef, the student becomes
a new data type. Therefore, now you can straight away declare variables of this new data type as
you declare variables of type int, float, char, double, etc. to declare a variable of structure student
you will just write,
student stud1;
INITIALIZATION OF STRUCTURES
● Initializing a structure means assigning some constants to the members of the structure.
● When the user does not explicitly initializes the structure then C automatically does that. For int and
float members, the values are initialized to zero and char and string members are initialized to the ‘\0’
by default.
● The initializers are enclosed in braces and are separated by commas. Note that initializers match their
corresponding types in the structure definition.
● The general syntax to initialize a structure variable is given as follows.
struct struct_name
{ data_type member_name1; struct struct_name
data_type member_name2; { data_type member_name1;
data_type member_name3;
data_type member_name2;
.......................................
}struct_var = {constant1, constant2, constant 3,...}; data_type member_name3;
OR .......................................
};
struct struct_name struct_var = {constant1, constant2, ….};
struct student stud1 = {01, “Rahul”, “BCA”, 45000};
ACCESSING THE MEMBERS OF A STRUCTURE
● Each member of a structure can be used just like a normal variable, but its name will be a bit longer. A
structure member variable is generally accessed using a ‘.’ (dot operator).
● The syntax of accessing a structure a member of a structure is:
struct_var.member_name
● For ex, to assign value to the individual data members of the structure variable Rahul, we may write,
Copying and Comparing structures
stud1.r_no = 01;
strcpy(stud1.name, “Rahul”);
stud1.course = “BCA”;
stud1.fees = 45000;
● We can assign a structure to another structure of the same type. For ex, if we have two structure variables stu1 and stud2
of type struct student given as
struct student stud1 = {01, "Rahul", "BCA", 45000};
struct student stud2;
Then to assign one structure variable to another we will write,
stud2 = stud1;
A program to illustrate copying and comparing structure variables
If((strcmp(s3.name,s2.name)==0)&&(s3.number == s2.number) &&
(s3.marks == s2.marks)) )
struct stud x=1;
{ else
int number; x=0;
char name[20];
if(x ==1)
float marks; {
}; printf(”\nstudent2 and student3 are same\n\n”);
main() printf(”%d %s %f\n”, student3.number,student3 .name,student3
{ .marks);
}
int x;
else
struct stud s1 = {111,"Rao",72.50}; printf(”\nstudent2 and student3 are different\n\n");
struct stud s2 = {222,"Reddy", 67.00}; }
struct stud s3; Output
student2 and student3 are same
s3 = s2;
structure as its member. Such a structure that contains another structure as its member is
called a nested structure.
typedef struct
{ char first_name[20];
char mid_name[20];
char last_name[20];
}NAME;
typedef struct
{ int dd;
int mm;
int yy;
}DATE;
struct student stud1;
stud1.name.first_name = “Janak”;
stud1.name.mid_name = “Raj”;
stud1.name.last_name = “Thareja”;
stud1.course = “BCA”;
stud1.DOB.dd = 15;
stud1.DOB.mm = 09;
stud1.DOB.yy = 1990;
stud1.fees = 45000;
Write a program to read and display information of a student using structure
#include<stdio.h> within a structure
int main( )
{ struct DOB
{
int day;
int month;
int year;
};
struct student
{ int roll_no;
char name[100];
float fees;
struct DOB date;
};
struct student stud1;
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.roll_no);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%d %d %d”, &stud1.date.day, &stud1.date.month, &stud1.date.year);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.roll_no);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n FEES. = %f”, stud1.fees);
printf(“\n DOB = %d - %d - %d”, stud1.date.day, stud1.date.month, stud1.date.year);
}
ARRAYS OF STRUCTURES
The general syntax for declaring an array of structure can be given as,
struct struct_name struct_var[index];
struct student stud[30];
● Now, to assign values to the ith student of the class, we will write,
● stud[i].r_no = 09;
● stud[i].name = “RASHI”;
● stud[i].course = “MCA”;
● stud[i].fees = 60000;
Arrays of Structures
• Example 2: Student[0].subject1 45
Student[0].subject2 68
struct marks
Student[0].subject3 81
{
Student[1].subject1 75
int subject1, subject2, subject3; Student[1].subject2 53
}; Student[1].subject3 69
Student[2].subject1 57
Student[2].subject2 36
Student[2].subject3 71
main()
{
struct marks student [3] ={{45,68,81},{75,53,69},{57,36,71}};
Write a program to read and display information of all the students in the class.
#include<stdio.h>
int main()
{ struct student
{
int roll_no;
char name[80];
float fees;
char DOB[80];
};
struct student stud[50];
int n, i;
printf(“\n Enter the number of students : “);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud[i].roll_no);
printf(“\n Enter the name : “);
scanf(“%s”, stud[i].name);
printf(“\n Enter the fees : “);
scanf(“%f”, stud[i].fees);
Finding the size of a structure
Simple addition
we will make a list of all data and add the types memory required by each. For example, let's consider a
simple structure of an employee.
Using size of operator
sizeof operator is used to calculate the size of a data type, variable, or an expression. To use this operator simply write,
sizeof (struct_name);
For example, the code given below prints the size of structure employee
Subtracting the Addresses
In this technique, we use an array of structure variables. Then we subtract the address of first element of next
consecutive variable from the address of the first element of preceding structure variable. For example, the code
below finds the size of structure Employee.
Write a program to declare a structure to read the name and salary
of a person and print it.
#include <stdio.h>
struct personal Output
{
char name[20]; Enter the name and salary:
Goel 4500
float salary;
Goel 4500.00
};
void main()
{
struct personal p1;
printf(“Enter the name and salary:\n");
scanf(”%s%f ",p1.name, &p1.salary);
printf(”%s %f \n", p1.name,p1.salary);
}
Implement structures to read the student details, write and compute average marks
and students scoring above and below the average marks for a class of N students.
#include<stdio.h>
void main()
printf("enter the name usn and marks of %d
{
students", n);
struct stud
for(i=0;i<n; i++)
{
char name[25];
{
char usn[25]; scanf("%s%s%d",s[i].name, &s[i].usn,&s[i].marks);
int marks; sum=sum+s[i].marks;
}; }
struct stud s[25]; average=sum/(float)n;
int n,i,sum; printf("average marks=%f", average);
float average;
sum=0;
printf("enter number of students\n");
scanf("%d",&n);
printf(" Details of students scoring above average marks\n"); Input:
for(i=0;i<n;i++) enter number of students :3
if (s[i].marks >= average) enter the name usn and marks of 3
students
printf("name=%s \t usn=%s \t marks=%d \n", s[i].name,
s[i].usn, s[i].marks); abc 1 25
xyz 2 28
pqr 3 30
printf(" Details of students scoring below average marks\n");
for(i=0;i<n;i++) Output:
if (s[i].marks < average) average marks=27.666666
printf("name=%s \t usn=%s \t marks= %d \n", s[i].name, Details of students scoring above
s[i].usn, s[i].marks); average marks
name=xyz usn=2 marks= 28
}
name=pqr usn=3 marks= 30
Write a Program to read the detail of one student and compute the total marks
obtained by the student and print the total marks