KEMBAR78
Array Pgms | PDF | String (Computer Science) | Computer Programming
0% found this document useful (0 votes)
8 views70 pages

Array Pgms

They are c programming notes

Uploaded by

hx4ww8pjrv
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)
8 views70 pages

Array Pgms

They are c programming notes

Uploaded by

hx4ww8pjrv
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/ 70

C Programs

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

• pos, as this is now empty.


Algorithm
Step 1: Start
Step 2: Declare and initialize an array a[n] , Where n is number of elements in the
array
Step 3: Read the number to be inserted and position to be inserted into
Step 4: Set i=n-1
Step 5: While i >= pos
Set a[i+1]=a[i]
i=i-1;
Step 6 : Set a[pos] = num;
Step 7: Set n=n+1;
Step 8: Display the array
Step 9 :Stop
void main()
{
int pos,n,num,i;
printf("enter the size of array :");
scanf("%d",&n);
int a[n];
printf("enter the elements : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter number to be inserted : ");
scanf("%d",&num);
printf("enter position to insert : ");
scanf("%d",&pos);
for(i=n-1;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=num;
n++;
printf("\n The array after insertion is : ");
for(i=0;i<=n-1;i++)
printf(" %d \t",a[i]);
}
Program to delete an element in a specific position in an array
Algorithm
Step 1: Start
Step 2: Declare and initialize an array a[n] , Where n is number of elements in
the array
Step 3: Read position at which number should be deleted
Step 4: Set i=pos
Step 5: While i < n-1
Set a[i]=a[i+1]
i=i+1;
Step 6: Set n=n-1;
Step 7: Display the array
Step 8 :Stop
void main()
{
int pos,n,num,i;
printf("enter the size of array :");
scanf("%d",&n);
int a[n];
printf("enter the elements : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter position from which element should be deleted : ");
scanf("%d",&pos);
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
n--;
printf("\n The array after deletion is : ");
for(i=0;i<=n-1;i++)
printf(" %d \t",a[i]);
}
Searching
• It is the process of finding the location of the specified
element in a list.
• The specified element is often called the search key.
• If it is found search is successful, otherwise it is
unsuccessful.

• Ex: Binary Search, Linear Search, Sequential


Search.
Program to demonstrate Binary search
Expected Output
Algorithm
Step 1: Start
Step 2: Declare and Initialise the array a[n] where n is the size of array. The array elements need to be in
ascending order
Step 3: Read the number that has to be searched – key
Step 4: Set low= 0 and high = n-1
Step 5: Compute mid = (low+high)/2
Step 6: while low <= high
if(array[mid] < key)
set low = mid + 1;
else if (array[mid] == key)
Print key found at location mid+1
Exit loop -go to step 9
else
Set high = mid - 1;
Step 7 : compute mid = (low + high)/2 and repeat step 6
Step 8: if(low > high)
Print element Not found
Step 9: Stop
void main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements in the array");
scanf("%d",&n);
printf("Enter the array elements");
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to be searched ");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high) {
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("\n %d found at location %d", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list", key);
}
Program to demonstrate Linear search
Expected Output
Algorithm
Step 1: Start
Step 2: Declare and Initialise an array a[n] where n is the size of array
Step 3: Read the number that has to be searched - key
Step 4: Set i=0
Step 5: while i < n
if a[i]= key
print that the element is found in position i
exit from loop – go to step 7
i=i+1;
Step 6: if end of array is reached
then print that the element is not found in the array
Step 7: Stop
void main()
{
int a[100], key, i, n;
printf("Enter number of elements in array: ");
scanf("%d", &n);
printf("\n Enter elements of the array: ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\n Enter a number to search: \n");
scanf("%d", &key);
for (i = 0; i < n; i++)
{
if (a[i] == key)
{
printf("%d is present at location %d \n", key, i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array\n",key);
}
TWO DIMENSIONAL ARRAYS
● A two dimensional array is specified using two subscripts where one subscript denotes row
and the other denotes column.
● C looks a two dimensional array as an array of a one dimensional array.

First Dimension
A two dimensional array is declared as:
data_type array_name[row_size][column_size];

Therefore, a two dimensional mXn array is an


array that contains m*n data elements and each
element is accessed using two subscripts, i and j
where i<=m and j<=n
Second Dimension
int marks[3][5]

Col 0 Col 1 Col2 Col 3 Col 4


Rows/Columns
Row 0 Marks[0][0] Marks[0][1] Marks[0][2] Marks[0][3] Marks[0][4]
Row 1 Marks[1][0] Marks[1][1] Marks[1][2] Marks[1][3] Marks[1][4]
Row 2 Marks[2][0] Marks[2][1] Marks[2][2] Marks[2][3] Marks[2][4]
Two Dimensional Array
MEMORY REPRESENTATION OF A TWO DIMENSIONAL ARRAY

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);

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


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

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


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
{
printf("\n");
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
}
}
return 0;
}
Multiplication of two matrices

#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]);
}

Passing 2D arrays to functions


INTRODUCTION
● A string is a collection of characters enclosed within the double quotes.
● A string is a null-terminated character array. This means that after the last character, a null character (‘\0’) is stored to
signify the end of the character array.
● The general form of declaring a string is
char str [size];
● For example if we write,
char str[ ] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L and O. Besides, a null character (‘\0’) is
stored at the end of the string. So, the internal representation of the string becomes- HELLO’\0’. Note that to store a
string of length 5, we need 5 + 1 locations (1 extra for the null character).
The name of the character array (or the string) is a pointer to the beginning of the string.

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.

It's because gets() allows you to input any length of characters.


Hence, there might be a buffer overflow.

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 be displayed using printf() by writing


printf(“%s”, str);

The string can be displayed by writing


puts(str);

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.

char c[] = "abcd";


scanf() to read a string
char c[50] = "abcd"; #include <stdio.h>
int main()
char c[] = {'a', 'b', 'c', 'd', '\0'}; {
char name[20];
char c[5] = {'a', 'b', 'c', 'd', '\0’}; printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
Assigning Values to Strings return 0;
char c[100]; }
c = "C programming"; // Error! array type is not assignable.
Operations on strings
int i;
char ch= ‘A’;
i= ch;
printf (“%d”, i); // prints 65, ASCII value of ch is ’A’
Finding the length of a string
#include <stdio.h>
int main() {
int str[100], i=0, length ;
printf(“Enter the string :”);
gets(str);
While(str[i]! = ‘\0’)
i++;
length= i ;
printf(“ the length of the string is: %d” , length);
return 0;
}
Write a program to display a string using printf()
int main()
{ #include <stdio.h>
char str[]=“introduction to c” ; #include <string.h>
printf(“\n %s”, str);
printf(“\n %20s”, str); int main() {
printf(“\n %-20s”, str); char s[100];
return 0; int i;
} printf("\nEnter a string : ");
gets(s);

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


if(s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] - 32;
}
}
printf("\nString in Upper Case = %s", s);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int compare_strings(char [], char []);
void concatenate(char [], char []);
int string_length(char s1[]);
int main()
{
char s1[1000],s2[1000];
printf("Input a string1\n");
gets(s1);
printf("Input a string2\n");
gets(s2);
int length1 = string_length(s1);
int length2 = string_length(s2);
printf("Length of %s = %d\n", s1,length1);
printf("Length of %s =%d\n", s2,length2);
if (compare_strings(s1, s2) == 0)
printf("Equal strings.\n");
else
printf("Unequal strings.\n");
concatenate(s1,s2);
printf("String obtained on concatenation: \"%s\"\n", s1);
return 0;
/* string length function*/
int string_length(char s1[])
{
int c = 0;
while (s1[c] != '\0') c++;
return c;
}

int compare_strings(char s1[], char s2[])


{

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;

222 Reddy 67.000000


Write a program using structures to read and display the information about a student
#include<stdio.h>
int main()
{ struct student
{ int roll_no;
char name[80];
float fees;
char DOB[80];
};
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(“%s”, stud1.DOB);
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 = %s”, stud1.DOB); }
NESTED STRUCTURES
A structure can be placed within another structure. That is, a structure may contain another

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

struct student printf("Enter 3 subject marks\n");


{ for(i=0;i<3;i++)
int stud_id; {
float subject[3]; scanf("%f",&s.subject[i]);
}; total= total+s.subject[i];
}
void main() printf("Studen with id :%d scored a total mark of
{ %f", s.stud_id, total);
struct student s;
int i; Input:
float total; Enter student id: 1
Enter 3 subject marks: 20 25 30
printf("enter the student id");
Output:
scanf("%d", &s.stud_id); Student with id:1 scored a total mark of 75
total=0.0;

You might also like