PPS Unit 2 Question Bank: One Dimensional Array in C
PPS Unit 2 Question Bank: One Dimensional Array in C
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];
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.
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
}
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
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
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");
}
}
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'}};
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.
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
Computes the length of the string str up to but not including the
size_t strlen(const char *str)
terminating null character
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
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:
code
int main() {
//initializing the strings
char string1[] = "Hello“,str2[15],str3[15];
strcpy(str2,string1);
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
===================
char str1[15]=”Good”,str2[15]=”Morning”;
char str3[15];
strlwr(str1);
strupr(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 emp
{
int empno;
char ename[20];
float sal;
};
struct emp e1 = { 123,”Kumar”,5000.00};
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);
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.
APPLICATIONS OF STRUCTURES:
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.
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;
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.
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 };
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