0% found this document useful (0 votes)
655 views

PPS Unit 2 Question Bank: One Dimensional Array in C

The document contains information about arrays in C programming language. It discusses one-dimensional arrays, two-dimensional arrays, and three-dimensional arrays. It provides examples of declaring, initializing, and accessing arrays. It also includes examples of C programs to perform operations on arrays such as updating elements, finding the maximum and minimum, calculating the mean, variance and standard deviation, adding and transposing matrices.

Uploaded by

Paradox 1883
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
655 views

PPS Unit 2 Question Bank: One Dimensional Array in C

The document contains information about arrays in C programming language. It discusses one-dimensional arrays, two-dimensional arrays, and three-dimensional arrays. It provides examples of declaring, initializing, and accessing arrays. It also includes examples of C programs to perform operations on arrays such as updating elements, finding the maximum and minimum, calculating the mean, variance and standard deviation, adding and transposing matrices.

Uploaded by

Paradox 1883
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

PPS Unit 2 Question Bank

1. Explain in detail about arrays in C (CO 4, L2)


Ans:
Arrays:
 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 which can store the primitive type of data such as int,
char, double, float, etc.
 Arrays can be randomly accessed by using its index number.
One Dimensional Array in C
Declaration of C Array
data_type array_name[array_size];
Ex:- int marks[5];
Initialization of C Array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Array: Declaration with Initialization


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};
Example: Write a program to create an array of n elements, update the i th element and
print the array.
#include<stdio.h>
int main()
{
int arr[5]={10,20,30,40,50},i,k,ele;
// printing the array before update
printf("Array elements before update:\n");
for(i=0;i<5;i++)
{
printf("%d ",arr[i]);
}
printf("\Enter the index to be updated:\n");
scanf(“%d”,&k);
printf("Enter the new element:\n");
scanf(“%d”,&ele);
arr[k]=ele;
printf("\nArray elements after update:\n");
for(i=0;i<5;i++)
{
printf("%d ",arr[i]);
}
return 0;
}
Sample input & output:
Array elements before update:
10 20 30 40 50
Enter the index to be updated:
2
Enter the new element:
345
Array elements after update:
10 20 345 40 50

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.
Declaration of two dimensional Array in C
data_type array_name[rows][columns];
Ex:- int arr[4][3];
Initialization of 2D Array in C:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Example: Write a program to find the row wise and column wise greatest element.
#include<stdio.h>
int main()
{
int x,y,i,j,l,k;
printf ("Enter no. of rows:");
scanf("%d",&x);
printf ("Enter the columns:");

scanf("%d",&y);
int a[x][1y];
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("row wise greatest element\n");
for(i=0;i<x;i++)
{
l=a[i][0];
for(j=1;j<y;j++)
{
if(l<a[i][j])
{
l=a[i][j];
}
}
printf("%d\n",l);
}
printf("column wise greatest element\n");
for(j=0;j<y;j++)
{
l=a[0][j];
for(i=1;i<x;i++)
{
if(l<a[i][j])
{
l=a[i][j];
}
}
printf("%d\n",l);
}
return 0;
}

Sample output:
Enter no. of rows:3
Enter the columns:3
123456789
row wise greatest element
3
6
9
column wise greatest element
7
8
9
Three-Dimensional Array:
C programming language allows multidimensional arrays.
Here is the general form of a multidimensional array declaration –
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three-dimensional integer array −
int arr[5][10][4];

Declaring and Initializing Three-Dimensional Array: Initialization in a Three-Dimensional


array is the same as that of Two-dimensional arrays. The difference is as the number of
dimensions increases so the number of nested braces will also increase.
Method 1:

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


11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23};
Better Method:

int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional
Arrays is also similar to that of Two-Dimensional Arrays. The difference is we have to use three
loops instead of two loops for one additional dimension in Three-dimensional Arrays.

Example: C program to print elements of Three-Dimensional Array


#include <stdio.h>
int main()
{
int test[2][3][2],i,j,k;

printf("Enter 12 values: \n");

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


{
for(j = 0; j < 3; ++j)
{
for(k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with proper index.


printf("\nDisplaying values:\n");
for(i = 0; i < 2; ++i)
{
for(j = 0; j < 3; ++j)
{
for(k = 0; k < 2; ++k)
{
printf("%d ", test[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
2. a) Write a C program to compute mean, variance, Standard Deviation. (CO 4, L3)
Ans:
#include<stdio.h>
#include<math.h>
void main()
{
float x[10], mean, variance,dev;
float sum1=0, sum2=0;
int n,i;
printf("Enter the number of integers:");
scanf("%d", &n);
printf("\nEnter the integers:");
for(i=0;i<=n-1;i++)
{
scanf("%f", &x[i]);
}
//to find mean
for(i=0;i<=n-1;i++)
{
sum1 = sum1 + x[i];
}
mean = sum1 /n;
printf("\nmean = %f", mean);

//to find variance


for(i=0;i<=n-1;i++)
{
sum2 = sum2 + (x[i] - mean) * (x[i] - mean);
}
variance = sum2/n;
printf("\nvariance = %f", variance);
//to find deviation
dev = sqrt(variance);
printf("\ndeviation = %f", dev);
}
Sample output:
Enter the number of integers:7
Enter the integers: 2 4 3 5 6 1 7
mean = 4.000000
variance = 4.000000
deviation = 2.000000

2. b) Write a program to find maximum and minimum of array elements. (CO 4, L3)
Ans:
#include<stdio.h>
int main()
{
int max=0,min=0;i,n;
printf ("Enter no. of elements:");
scanf("%d",&n);
int a[n];
printf ("Enter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<max)
min=a[i];
}
printf("Maximum element is = %d\n",max);
printf("Minimum element is = %d\n",min);
return 0;
}
Sample output:
Enter no. of elements:5
Enter the elements:
23 45 12 67 78
Maximum element is = 78
Minimum element is = 12

3. a) Write a program to find trace of two matrices. (CO 4, L3)


Ans:
#include<stdio.h>
int main()
{
int i,j,r,c,trace;
printf ("Enter no. of rows:");
scanf("%d",&r);
printf ("Enter the columns:");
scanf("%d",&c);
int a[r][c];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}

}
for(i=0;i<r;i++)
{
trace=trace+a[i][i];
}
printf("Trace of a matrix is: %d",trace);
}
Sample Output:
Enter no. of rows:3
Enter the columns:3
123456789
Trace of a matrix is: 15

3. b) Write a program to perform transpose of two matrices. (CO4, LEVEL-3)


Ans:
#include<stdio.h>
int main()
{
int a[20][20],b[20][20];
int i,j,r,c;
printf ("Enter no. of rows:");
scanf("%d",&r);
printf ("Enter the columns:");
scanf("%d",&c);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
b[i][j]=a[j][i];
}
}
printf("Transpose of a matrix is:\n");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf("%d ",b[i][j]);
}
printf("\n");
}
return 0;
}
Sample Output:
Enter no. of rows:3
Enter the columns:2
123456
Transpose of a matrix is:
135
246

4. a) Write a C program to perform addition of 2 matrices. (CO 4, L3)


Ans:
#include<stdio.h>
int main()
{
int r,c,x,y,i,j;
printf("Enter rows and columns of matrix1:\n");
scanf("%d %d",&r,&c);
int a[r][c];
printf("Enter rows and columns of matrix2:\n");
scanf("%d %d",&x,&y);
int b[x][y],k[x][y];
if(r==x && c==y)
{
printf("Enter %d values of matrix1:\n",r*c);
for (i=0;i<r;i++)
{
for (j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter %d values of matrix2: \n",x*y);
for (i=0;i<x;i++)
{
for (j=0;j<y;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("Resultant Matrix:\n");
for (i=0;i<x;i++)
{
for (j=0;j<y;j++)
{
k[i][j]=a[i][j]+b[i][j];
printf("%d ",k[i][j]);
}
printf("\n");
}
}
else
{
printf("Matrix addition is not possible");
}

return 0;
}
Sample input & output 1:
Enter rows and columns of matrix1:
23
Enter rows and columns of matrix2:
23
Enter 6 values of matrix1:
493176
Enter 6 values of matrix2:
597361
Resultant Matrix:
9 18 10
4 13 7

Sample Input & Output 2:


Enter rows and columns of matrix1:
34
Enter rows and columns of matrix2:
33
Matrix addition is not possible

4. b) Write a C program to perform Matrix multiplication. (CO 4, L3)


#include<stdio.h>
void main()
{
int i,j,k,r1,c1,r2,c2;
printf("Enter rows and columns of matrix1:\n");
scanf("%d %d",&r1,&c1);
printf("Enter rows and columns of matrix2:\n");
scanf("%d %d",&r2,&c2);
if(c1==r2)
{
int a[r1][c1], b[r2][c2], c[r1][c2];
printf("Enter %d values of matrix1:\n",r1*c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);

printf("Enter %d values of matrix2:\n",r2*c2);


for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);

for(i=0;i<r1;i++)//rows
{
for(j=0;j<c2;j++)//cols
{
c[i][j]=0;
for(k=0;k<c1;k++)
c[i][j]=c[i][j] + a[i][k]*b[k][j];
}
}

printf("Resultant Matrix:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
}
else
{
printf("Matrix multiplication is not possible");
}
}

Sample input &output 1:


Enter rows and columns of matrix1:
23
Enter rows and columns of matrix2:
32
Enter 6 values of matrix1:
123456
Enter 6 values of matrix2:
456789
Resultant Matrix:
40 46
94 109

Sample input &output 2:


Enter rows and columns of matrix1:
22
Enter rows and columns of matrix2:
32
Matrix multiplication is not possible

5. a) Explain Strings in C with an example (CO 4, L2)


Ans:
A string is an array of characters that is terminated by a NULL character ‘\0’.
It can be read as a single entity, unlike other types of arrays.
Declaration:
char String_name[size_of_the_string];
Example:
char name[15];
Initialization:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";

char ch[ ] = { 'a', 'e', 'i', 'o', 'u', '\0'};


Here the characters a, e, i, o, u are stored character by character in the character array ch.
In this, the NULL ('\0') character can be added by the user at the end of the initialization as the
array is initialized with values character by character
The one-dimensional character array can also be written as char ch[ ] = "aeiou";
Here double quotes are used to mention the string constant.
In this type of initialization the NULL ('\0') character is automatically appended.
Let us consider another example: char text[4] = "COLLEGE";.
In this example only the first 4 characters of the string COLLEGE are assigned to the array and
NULL is not included.
The output may contain unexpected characters after the first four characters
COLL.
Hence, care must be taken to mention the size of the array and that is large enough to store
all the characters including NULL.
So we can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Example: Write a program in C to find the length of a string without using library function
#include<stdio.h>
void main(){
char str[100];
int i,len;
printf("Enter a string");
gets(str);
for(i=0;str[i]!='\0';i++)
{
len++;
}
printf("String length:%d",len);
}
Output:
Enter a stringKMIT Autonomous
String length:15

5. b) Explain array of Strings and sort the 10 strings entered by the user in lexicographical order
(dictionary order) (CO 4, L2)
Ans:
Array of Strings:
An array of strings is a two-dimensional character array.
The size of the first index (rows) determines the number of strings and the size of the second
index (columns) determines maximum length of each string.
The syntax of declaring an array of strings is:
char array_name[row_size][column_size];
Let us consider some examples:
char str[4][7] = {"First", "Second", "Third", "Four" };
char ch_arr[3][10] = {{'s', 'p', 'i', 'k', 'e', '\0'}, {'t', 'o', 'm','\0'}, {'j', 'e', 'r', 'r', 'y','\0'}};

Program to sort the 10 strings entered by the user in lexicographical order


#include <string.h>
int main()
{
int i, j, num;
char name[20][20], temp[20];
printf("Enter number of names to be sorted in alphabetical order: ");
scanf("%d", &num);
printf("Enter %d names: \n", num);
for(i=0; i<num; i++)
{
scanf("%s",name[i]);
}
for(i=0; i < num-1 ; i++)
{
for(j=i+1; j< num; j++)
{
if(strcmp(name[i],name[j]) > 0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
printf("Names after sorting in alphabetical order: \n");
for(i=0; i< num ; i++)
{
printf("%s\n",name[i]);
}
}
Output:
Enter number of names to be sorted in alphabetical order: 4
Enter 4 names:
Hyderabad
Adilabad
Banglore
Delhi
Names after sorting in alphabetical order:
Adilabad
Banglore
Delhi
Hyderabad

6. Explain string input & output functions in C with a program. (CO 4, L2)
Ans: String I/O
The syntax of gets() function is
char * gets(char *str);
Read using scanf() and gets() a NULL ('\0') is automatically inserted at the end of the string.
Reads a string using gets() until it encounters a newline or EOF. ‘\n’ is replaced by the ’\0’ at the
end of the string.
code:
char str[50];
printf(“\nEnter a string use gets”);
gets(str);
printf(“\nString is:%s”,str);

output
Enter a string use gets:KMIT is autonomous college
String is:KMIT is autonomous college
---------------------------------------------------------
Syntax of puts
int puts(char *str)
puts() is used to display the string on the console. The delimiter character ‘\0’ of the string is
automatically converted into a newline character ‘\n’ when the string is displayed.

code:
char str[50];
puts(“Give your college name”);
gets(str);
puts(“COLLEGE NAME”);
puts(str);

output
Give your college name
KMIT Autonomous
COLLEGE NAME
KMIT Autonomous
---------------------------------------------
Reading and displaying a string using scanf() and printf():
scanf() function can be used to read a string by using %s.
Reads a string until it encounters a whitespace character and a NULL ('\0') is added to the string.
syntax of reading a string
char char[25];
scanf("%s", chArr);
Here & is not used with variable as chArr itself represents the base address of the array.
The function printf() is used with format specifier %s to display the string.
The syntax of displaying a string with printf() is
printf("%s", chArr);
Here the string value that is stored in chArr is displayed.

Reading a string using getchar():


Alternative to read a string is read character by character.
Characters are read one at a time using getchar() (or) scanf() with %c.
The NULL ('\0') character is not appended, if it is read character by character.
It is necessary to add it in a separate statement.
int getchar(void);

To read a string character by character using getchar() function.


void main() {
char ch[100]; int i = 0;
printf("Enter a string (Read up to # is given) : ");
while ((ch[i] = getchar()) != '#') { i++; }
ch[i] = '\0';
printf("\nThe given string is : ");
puts(ch);
}
Output
Enter a string (Read up to # is given) :KMIT College#
The given string is: KMIT College
----------------------------------------------------------------------
Above code, getchar() reads character from the keyboard and stored in ith location of array ch.
Next, it checks whether the given character is '#' or not, if it is not, and repeat the loop again.
While loop is repeated until user enters character '#'.
If '#' is given it is stored at the end of that string.
The statement ch[i]='\0'; stores the NULL character at where '#' is stored.

putchar():
C library function int putchar(int char) writes a character specified by the argument char to
stdout.
int putchar(int char)

#include <stdio.h>
int main () {
char ch;
for(ch = 'A' ; ch <= 'Z' ; ch++)
{
putchar(ch);
}
return(0);
}
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
7. Explain String manipulation functions with examples. (CO 4, L2)
Ans:
 In C, we have different types of string manipulation functions which are used for the
different string operations.
 C supports a string handling library which provides useful functions that can be used for
string manipulations.
 All these string handling functions are defined in the header file string.h.
 string.h header file must be included to use the string functions

Major string handling functions used are tabulated below.


String functions Description

Computes the length of the string str up to but not including the
size_t strlen(const char *str)
terminating null character

char *strcpy(char *dest, const


Copies the string pointed to, by src to dest.
char *src)

char *strcat(char *dest, const char Appends the string pointed to, by src to the end of the string pointed to
*src) by dest.

Compares the string pointed to, by str1 to the string pointed to by str2.
int strcmp(const char *str1, const
Returns 0 if str1 is same as str2. Returns <0 if strl < str2.
char *str2)
Returns >0 if str1 > str2

Returns the modified string obtained after converting the characters


char *strlwr(char *str)
of the given string str to lowercase

Returns the modified string obtained after converting the characters


char *strupr(char *str)
of the given string str to uppercase

strlen():
• The function strlen() is used to find the length of a
given string. This function returns only integer data (or) numeric data.
• The format of strlen() is integer_variable = strlen(string);.

int main() {
int len1, len2;
//initializing the strings
char string1[] = "Hello";
char string2[] = {'c','o','m','p','u','t','e','r','\0'};
//calculating the length of the two strings
len1 = strlen(string1);
len2 = strlen(string2);
//displaying the values
printf("Length of string1 is: %d \n", len1);
printf("Length of string2 is: %d \n", len2);
}
Output:

Length of string1 is: 5


Length of string2 is: 8
========================
strcpy():
The function strcpy() is used to copyone string into another string including the NULL
character (terminator char ‘\0’).
The format of strcpy( ) is strcpy(string1, string2);.

code
int main() {
//initializing the strings
char string1[] = "Hello“,str2[15],str3[15];
strcpy(str2,string1);

//displaying the values


printf("string2 is: %s \n",str2);
}
Output
string2 is: Hello
================
strcmp():
The function strcmp() is used for comparison of two strings and it always returns
numeric data.
The syntax of strcmp() is variable = strcmp (string1, string2);,
where string1, string2 are two strings and variable is of the type integer.
The comparison of two strings is dependent on the alphabets and not on the size of
the strings.
• If the function strcmp() returns zero, both strings are equal.
• If the function returns less than zero, string2 is higher than string1.
• If the function returns greater than zero, string1 is higher than string2.

int i;
char str1[15]=”Good”,str2[15]=”good”;
printf(“String1:%s\nString2:%s”,str1,str2);
i=strcmp(str1,str2);
puts(“Comparing strcmp function”);
if(i==0)
printf("The strings are equal");
else
printf("The strings are not equal");

Output
String1:Good
String2:good
Comparing strcmp function
The strings are not equal

===================================
strcat():
• The function strcat() is used to concatenate two strings into one string
• The syntax of strcat() is strcat(string1, string2); where string1, string2 are two different
strings. Here string2 is concatenated with string1, and finally the resultant concatenated string is
stored in string1.
char str1[15]=”Good”,str2[15]=”Morning”;
char str3[15];
strcpy(str3,str1);
strcat(str1,str2);
printf("The string after strcat 4 chars is %s",str1);

Output
The string after strcat is GoodMorning
===================

strlwr( ): converts string to lowercase


strupr( ): converts string to uppercase

char str1[15]=”Good”,str2[15]=”Morning”;
char str3[15];
strlwr(str1);
strupr(str2);

printf(“Lower case: %s",str1);


printf(“Upper case: %s",str2);

Output:
Lower case: good
Upper case: MORNING
================================
strrev( ): reverse of give string
printf("Enter string ");
gets(str1);
strrev(str1);
printf("Reverse string is");
printf("%s",str1);
Output
Enter string Good Morning
Reverse string is gninroM dog
================================
8 a) Write a C program to count the number of vowels, consonants, digits and white-spaces in a
string which is entered by the user. (CO 4, L3)
Ans:
#include <stdio.h>
void main() {
char line[150];
int vwl, cons, dgt, spc,i;
vwl = cons = dgt = spc = 0;
printf("Enter a line of string: ");
gets(line);
for (i = 0; line[i] != '\0'; ++i) {
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u') {
vwl++;
}
else if ((line[i] >= 'a' && line[i] <= 'z')||(line[i] >= 'A' && line[i] <= 'Z')) {
cons++;
}
else if (line[i] >= '0' && line[i] <= '9') {
dgt++;
}
else if (line[i] == ' ') {
spc++;
}
}
printf("Vowels: %d", vwl);
printf("\nConsonants: %d", cons);
printf("\nDigits: %d", dgt);
printf("\nWhite spaces: %d", spc);
}
Output
Enter a line of string: This 1234
Vowels: 1
Consonants: 3
Digits: 4
White spaces: 1

8 b) Write a C program to find the given string is palindrome or not without using any string
functions. (CO 4, L3)
Ans:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[10];
int res,len=0;
puts("Enter a string to check palindrome");
gets(s1);
len=strlen(s1);
for(int i=0;i<len/2;i++)
{
if(s1[i]==s1[len-i-1])
res=0;
else{
res=1;
break;
}
}
if(res!=0)
printf("\n%s is not palindrome",s1);
else
printf("\n%s is palindrome",s1);
return 0;
}
Sample Output 1:
Enter a string to check palindrome
CIVIC
CIVIC is palindrome
Sample Output 2:
Enter a string to check palindrome
hello
hello is not palindrome

9. Define Structure? How to declare and initialize a Structure? Explain with an example (CO 4,
L1)
Ans:
A Structure is a collection of elements of dissimilar data types. Structures provide the ability to
create user defined data types and also to represent real world data.

Suppose if we want to store the information about a book, we need to store its name (String), its
price (float) and number of pages in it (int). We have to store the above three items as a group
then we can use a structure variable which collectively store the information as a book.
Structures can be used to store the real world data like employee, student, person etc.

Declaration:
The declaration of the Structure starts with a Key Word called struct and ends with semicolon.
The Structure elements can be any built in types.

struct <Structure name>


{
Structure element 1;
Structure element 2;
-
-
-
Structure element n;
};

Then the Structure Variables are declared as


struct < Structure name > <Var1,Var2>;
Eg:-
struct emp
{
int empno.
char ename[20];
float sal;
};
struct emp e1,e2,e3;

The above Structure can also be declared as:


struct emp
{
int empno;
char ename[20];
float sal;
}e1,e2,e3;
Initialization:
Structure Variables can also be initialised where they are declared.

struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e1 = { 123,”Kumar”,5000.00};

To access the Structure elements we use the dot (.) operator.


To refer empno we should use e1.empno
To refer sal we would use e1.sal
Structure elements are stored in contiguous memory locations as shown below. The above
Structure occupies totally 26 bytes.
e1.empno E1.ename E1.sal
123 Kumar 5000.00
2000 2002 2022

Example: Program to illustrate the usage of a Structure and Dynamic Initialization.


main()
{
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e;

printf (“ Enter Employee number: \n”);


scanf(“%d”,&e.empno);
printf (“ Enter Employee Name: \n”);
scanf(“%s”,&e.empname);
printf (“ Enter the Salary: \n”);
scanf(“%f”,&e.sal);
printf (“ Employee No = %d”, e.empno);
printf (“\n Emp Name = %s”, e.empname);
printf (“\n Salary = %f”, e.sal);
}

10. What is Nesting of Structures? Illustrate with an example? (CO 4, L1)


Ans:
One Structure can be enclosed in another Structure. The Structure which is to be nested must be
declared before it is used. We can nest a Structure within a Structure, which is in still another
Structure and so on. Nesting of Structure can be done to any number of levels. The elements of
the nested Structure are accessed by using one more dot (.) operator.

Eg:-
struct date
{
int dd, mm, yy;
};
struct student
{
int rno;
char sname[15];
struct date dob;
};
struct student s;

Here, dob is the Nested Structure. To access this we use s.dob.dd or s.dob.mm or s.dob.yy.

Example: Program to store employee details and calculate total salary using nested
structure
#include<stdio.h>
#include<string.h>
struct Employee
{
int eid;
char ename[50];
char dept[10];
int age;
struct salary
{
int basic;
int da;
int hra;
}allowance;
};
void main()
{
struct Employee emp;
emp.eid=121;
strcpy(emp.ename, "Shiva Rama");
strcpy(emp.dept, "Accounts");
emp.age=48;
emp.allowance.basic=55000;
emp.allowance.da=8000;
emp.allowance.hra=15000;
int total = emp.allowance.basic + emp.allowance.da + emp.allowance.hra;
printf(" ID:%d\n Name:%s\n Dept:%s\n Age:%d\n", emp.eid, emp.ename, emp.dept,
emp.age);
printf("Total Salary: %d\n", total);
}
Output:
ID: 121
Name: Shiva Rama
Dept: Accounts
Age: 48
Total Salary: 78000

11. a) Write a C Program to read student details and calculate total and average marks obtained
by a student using structures? (CO 4, L3)
Ans:
#include<stdio.h>
main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s;
int tot;

float avg;
printf(“Enter the student roll number: \n”);
scanf(“%d”,&s.rno);

printf(“Enter the student name: \n”);


scanf(“%s”,&s.sname);
printf(“Enter the three subjects marks: \n”);
scanf(“%d%d%d”,&s.m1,&s.m2,&s.m3);
tot = s.m1 + s.m2 +s.m3; avg = tot/3.0;
printf(“Roll Number : %d\n”,s.rno); printf(“Student Name: %s\n”,s.sname);
printf(“Total Marks : %d\n”,tot); printf(“Average : %f\n”,avg);
}

11. b) Explain about Arrays Of Structures with Example? (CO 4, L2)


Ans:
Array od structures:
To store more number of Structures, we can use array of Structures. In array of Structures all
elements of the array are stored in adjacent memory location.

Example: Program to illustrate the usage of array of Structures.


main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];

int i;

for (i=0;i<10;i++)
{
print(“\n Enter Name, Price and Pages”); scanf(“%s%f%d”,
b[i].name,&b[i].price,&b[i].pages);
}

for ( i=0;i<10;i++)
printf(“ \n%s%f%d”, b[i].name,b[i].price,b[i].pages);
}

12. Explain about Self-referential structures and applications of structures? (CO 4, L2)
SELF REFERENTIAL STRUCTURES:
A Self referential Structure is one that includes within its structure at least one member which is
a pointer to the same structure type. With self referential structures we can create very useful
data structures such as linked lists, trees etc.
Ex:
Struct tag
{
char name[40];
struct emp*next;
};
A structure contains two members a 40 element character array called name,and a pointer to
another structure of the same called next.

Example: Program to create single linked list


#include<stdio.h>
struct node
{
int data;
struct node *link;
};
void main()
{
struct node obj1;
//object 1 creation
obj1.data=20;
obj1.link=NULL;
printf("Object 1: %d %d\n",obj1.data,obj1.link);//20 0
//Object 2 creation
struct node obj2;
obj2.data=30;
obj2.link=NULL;
obj1.link=&obj2; //linking object 1 and object 2
printf("Object 1 (after creating object 2): %d %d\n",obj1.data,obj1.link);//20 address
printf("Object 2: %d %d\n",obj1.link->data,obj1.link->link);//30 0
}
Output:
Object 1 (after creating object 2): 20 1238116
Object 2: 30 0

APPLICATIONS OF STRUCTURES:

Structures can be used for a Variety of Applications like:


a) Database Management.
(To maintain data about employees in an organisation, book in a library,
items in a Store etc)
b) Changing the size of the Cursor.
c) Clearing the contents of the Screen.
d) Placing the Cursor at appropriate position on Screen.

e) Drawing any graphics Shape on the Screen.


f) Receiving a Key from the Keyboard.
g) Checking the memory size of the Computer.
h) Finding the list of equipment attached to the Computer.
i) Formatting a Floppy.
j) Hiding a file from the Directory.
k) Displaying the Directory of a Disk.
l) Sending the Output to Printer.
m) Interacting with the Mouse.

13. a) What is the syntax and purpose of typedef? Explain with an example? (CO 4, L1)
Ans:
typedef is used to create new datatype. The statement typedef is used while defining the new data
type.
Syntax:
typedef type dataname;
Here, type is the data type and dataname is the user defined name for that type.
typedef int hours;
Here, hours is another name for int and now we can use hours instead of int in the program as
follows:
Example to demonstrate typedefinition
#include <stdio.h>
#define H 60
main()
{
typedef int hours;
hours hrs;
printf(“Enter hours\n”);
scanf(“%d”,&hrs);
printf(“minutes=%d”,hrs*H);
printf(“\nseconds=%d”,hrs*H*H);
}
Output:
Enter hours: 2
Minutes=120
Seconds=7200

Explanation of program: In the above example with typedef we had declared hours as an integer
data type. Immediately after the typedef statement hrs is a variable of hours datatype which is
similar to int. further the program calculates minutes and seconds using hrs variable.

13. b) Differentiate between Structure and Union? (CO 4, L4)


Ans:
The memory occupied by structure variable is the sum of sizes of all the members but memory
occupied by union variable is equal to space hold by the largest data member of a union.
In the structure all the members can be accessed at any point of time but in union only one
of union member can be accessed at any given time.
Example program:
#include<stdio.h>
union job
{
char name[32];
float salary;
int worker_no;
} u;
struct job1
{
char name[32];
float salary;
int worker_no;
} s;
void main( )
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d",sizeof(s));
}
Output:
Size of union = 32
Size of structure = 40

Difference between Structure and Union

Structure Union
1. It can be defined using struct keyword. It can be defined using a union keyword.

2. Every member within structure is assigned In union, a memory location is shared by all
a unique memory location. the data members.
3. Changing the value of one data member Changing the value of one data member
will not affect other data members in willchange the value of other data
structure. members in union.
4. It allows initializing several members at It allows initializing only the first member of
once. union.
5. The total size of the structure is the sum The total size of the union is the size of
ofthe size of every data member. the largest data member.

6. It is used for storing various data types. It is used for storing one of the many data
types that are available.
7. It reserves space for each and every It reserves space for a member having
member separately. the highest size.

8. Any member can be retrieve at a time. Only one member can be retrieve at a time.
9. It allows dynamic array as member. It does not allows dynamic array as member.

14. Explain about pointers and write a program to explain pointer to an array. (CO 4, L2)
Ans:
Pointer is a special type of variable used to store the memory location address of a variable.
Every pointer stores the address of variable with same datatype only.
For declaring a pointer variable
datatype *pointer_name;
Example:
int *ptr;
Reference (address of) operator ‘&’ is used to access address of a variable.
Initialising a pointer
pointer_name = &varaible_name;
Example:
int a, *ptr;
a = 10;
ptr = &a;
• Pointer can be used to access value at the address with the use of ‘*’ (dereferencing
operator) in front of pointer variable name.
• Memory allocation of pointer variable:
– In computer, memory address of any memory location is an unsigned integer value,
which requires 2 bytes of memory in C.
– So, irrespective of pointer datatype every pointer variable is allocated with 2 bytes of
memory.
Example: program to illustrate pointer to an array
#include<conio.h>
void main()
{
int arr[]={5,10,15,20,25,30};
int i, *ptr;
ptr = &arr[0];
for(i=0;i<6;i++)
{
printf("arr[%d] = %d ",i,*ptr);
printf("address = %u\n",ptr);
ptr++;
}
}
Output:
15. a) What is the difference between array and a pointer? (CO4, L1)
Ans:
Array: Arrays are generally used for storing the same types of data items or values that are same
in the nature. Although arrays cannot be used to store the data items or values that are not same
in the nature, it is also considered a significant disadvantage of the arrays.
Syntax: datatype arrayname[size];
Eg: int mark[5] = {19, 10, 8, 17, 9};

Pointers: Pointers are generally used for storing the memory address of the other variable
instead of storing the actual value of the variable. However, we can also use the pointer to access
the whole array by using the pointer arithmetic. In addition, it also even makes the accessing
array process much faster.
Syntax: type * name;
Eg: int *p;

Basis for Pointer Array


Comparison

Declaration type * var_name; type var_name[size]

Working It generally stores the address of another Array usually stores the value of the
variable of the same data type as the variable of the same datatype.
pointer variable's datatype.

Generation A pointer to an array can be generated. An array of pointers can be generated.

Storage Pointers are specially designed to store the A normal array stores values of variables,
address of variables. and pointer array stores the address of
variables.

Capacity Usually, arrays can store the number of A pointer variable can store the address of
elements the same size as the size of the only one variable at a time.
array variable.
15. b) Write short notes on pointer Arithmetic Operations with an example. (CO 4, L1)
Ans:
In c programming language, we can perform the following arithmetic operations on pointers:
• Addition of a constant
• Subtraction of a constant
• Increment
• Decrement
Example: Program to illustrate pointer operations
#include<stdio.h>
#include<conio.h>
void main()
{
int i=5, *ptr;
clrscr();
printf("value of i = %d\n", i);
ptr=&i;
printf("address of i = %u\n", ptr);
ptr=ptr+2;
printf("After addition of 2 = %u\n", ptr);
ptr=ptr-4;
printf("After substraction of 4 = %u\n", ptr);
ptr++;
printf("After incrementation = %u\n", ptr);
ptr--;
printf("After decrementation = %u\n", ptr);
getch();
getch();
}
16. a) Explain pointer to a pointer with an example. (CO 4, L2)
Ans: Pointer to a pointer
C programming language also provides pointer variable to store the address of another pointer
variable.
This type of pointer variable is called as pointer to pointer variable. Sometimes we also call it as
double pointer.
datatype **pointer_name;
Example: Program to illustrate pointer to a pointer
#include<conio.h>
void main()
{
int a=10;
int *ptr1, **ptr2;
printf("a=%d\n",a);
ptr1=&a;
printf("accessing ptr1\n");
printf("address of a = %u\n",ptr1);
printf("value of a =%d\n",*ptr1);
printf("address of pointer ptr1=%u\n",&ptr1);
ptr2 = &ptr1;
printf("Accessing ptr 2\n");
printf("address of ptr1 = %u\n",ptr2);
printf("address of a = %u\n",*ptr2);
printf("value of a = %d \n", **ptr2);
}
Output:
16. b) Discuss about array of pointers in detail. (CO 4, L2)
Ans:
Array of pointers:
“Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.
Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make
one integer array of pointers that can point to all the values.
Example: C program to demonstrate example of array of pointers.

#include <stdio.h>
const int SIZE = 3;
void main()
{
// creating an array
int arr[] = { 1, 2, 3 };

// we can make an integer pointer array to


// storing the address of array elements
int i, *ptr[SIZE];

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

// assigning the address of integer.


ptr[i] = &arr[i];
}
// printing values using pointer
for (i = 0; i < SIZE; i++) {

printf("Value of arr[%d] = %d\n", i, *ptr[i]);


}
}

Output:
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3

Example: We can likewise make an array of pointers to the character to store a list of strings.

#include <stdio.h>
const int size = 4;
void main()
{
// array of pointers to a character
// to store a list of strings
char* names[] = {
"amit",
"amar",
"ankit",
"akhil"
};
int i = 0;
for (i = 0; i < size; i++) {
printf("%s\n", names[i]);
}
}

Output:
amit
amar
ankit
akhil
17. a) Explain about void pointer. (CO 4, L2)
Ans: void pointer
Pointer to void is the concept of defining a pointer variable that is independent of datatype.
void pointer is a pointer variable used to store the address of variable of any datatype.
“void” keyword is used to create void pointer.
Syntax:
void *pointer_name ;
Example: Program to illustrate void pointer
#include<stdio.h>
void main()
{
int a=10 ;
float b=9.8;
char c='y' ;
void *ptr ;
ptr = &a ;//int
printf("a = %d, address of integer variable a = %u\n",*(int*)ptr, ptr) ;
ptr = &b ;//float
printf("b = %.2f, address of float variable b = %u\n",*(float*)ptr, ptr) ;
ptr = &c ;//char
printf("c = %c, address of character variable c = %u\n",*(char*)ptr, ptr) ;
}
Output:
a = 10, address of integer variable a = 6487572
b = 9.80, address of float variable b = 6487568
c = y, address of character variable c = 6487567

17. b) Illustrate about pointers to structure. (CO 4, L2)


Ans:
Pointer to structure holds the address of the entire structure. It is used to create complex data
structures such as linked lists, trees, graphs and so on.
The members of the structure can be accessed using a special operator called as an arrow
operator ( -> ).
Declaration
Syntax:
struct tagname *ptr;
Eg: struct student *s −
Accessing
It is explained below how to access the pointers to structures.
Ptr-> membername;
Eg: s->sno, s->sname, s->marks;
Example: Program to illustrate structure with pointers
#include<stdio.h>
#include<string.h>
struct Student
{
char name[10];
int rno;
int age;
};
void main()
{
struct Student S;
struct Student *sptr;
sptr = &S;
sptr->rno=125;
strcpy(sptr->name,"Mounica");
sptr->age=20;
printf("student 1 details using pointer:\n");
printf("Name= %s \nRoll no.= %d\nage= %d\n", sptr->name, sptr->rno, sptr->age);
}
Output:
student 1 details using pointer:
Name= Mounica
Roll no.= 125
age= 20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy