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

PPSC MID-II Unit-3 ASSIGNMENT QUESTIONS

The document provides a comprehensive overview of programming concepts in C, focusing on arrays, including their declaration, initialization, and manipulation. It includes examples of single and two-dimensional arrays, string functions, and various programs to perform tasks such as finding unique elements, calculating sums and averages, and counting vowels and consonants. Additionally, it covers string manipulation functions and the multiplication of matrices.

Uploaded by

buradabalaji66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views25 pages

PPSC MID-II Unit-3 ASSIGNMENT QUESTIONS

The document provides a comprehensive overview of programming concepts in C, focusing on arrays, including their declaration, initialization, and manipulation. It includes examples of single and two-dimensional arrays, string functions, and various programs to perform tasks such as finding unique elements, calculating sums and averages, and counting vowels and consonants. Additionally, it covers string manipulation functions and the multiplication of matrices.

Uploaded by

buradabalaji66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Programming for Problem Solving Using C

Mid-II
Unit-3 Assignment Questions

1. What is an Array? How to declare and initialize a single dimensional


array? With example

Ans:
Definition: An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection
of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each
data element can be randomly accessed by using its index number.

We can declare a Single Dimensinal array as follow:

data_type array_name[array_size];

Example: int marks[5];

The simplest way to initialize a Single Dimensional array is by using the index of each
element. We can initialize each element of the array by using the index. Consider the following
example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Program:

#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}

Output:

80
60
70
85
75

2. Write a program in c to print all unique elements in an array?

Program:

#include <stdio.h>
int main()
{
int arr[100], n,ctr=0;
int i, j, k;
printf("Print all unique elements of an array:\n");
printf("------------------------------------------\n");
printf("Input the number of elements to be stored in the array: ");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr[i]);
}
printf("\nThe unique elements found in the array are: \n");
for(i=0; i<n; i++)
{
ctr=0;
for(j=0,k=n; j<k+1; j++)
{
/*Increment the counter when the seaarch value is duplicate.*/
if (i!=j)
{
if(arr[i]==arr[j])
{
ctr++;
}
}
}
if(ctr==0)
{
printf("%d ",arr[i]);
}
}
printf("\n\n");
return 0;
}

Expected Output:

Print all unique elements of an array:


------------------------------------------
Input the number of elements to be stored in the array: 5
Input 5 elements in the array :
element - 0 : 2
element - 1 : 8
element - 2 : 1
element - 3 : 4
element - 4 : 6
The unique elements found in the array are:
28146

Actual Output:
Print all unique elements of an array:
------------------------------------------
Input the number of elements to be stored in the array: 5
Input 5 elements in the array :
element - 0 : 2
element - 1 : 8
element - 2 : 1
element - 3 : 4
element - 4 : 6
The unique elements found in the array are:
28146

3. Explain how to declare and initialize a two dimensional array with


suitable examples.

Ans: 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. However, 2D arrays are
created to implement a relational database lookalike data structure. It provides ease of holding the
bulk of data at once which can be passed to any number of functions wherever required.

The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];

Consider the following example.

int twodimen[4][3];

In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The two-dimensional array can be declared and
defined in the following way.

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

Program:

#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}

Output:

arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 2
arr[1] [1] = 3
arr[1] [2] = 4
arr[2] [0] = 3
arr[2] [1] = 4
arr[2] [2] = 5
arr[3] [0] = 4
arr[3] [1] = 5
arr[3] [2] = 6

4. Build a C program to find the sum & average of n numbers using array

Program:
#include<stdio.h>
int main()
{
int i,n,sum=0,num;
float avg;
printf("\nEnter How many Number you want?\n");
scanf("%d",&n);
printf("\nEnter elements one by one\n");
for(i=0;i<n;++i)
{
scanf("%d",&num);
sum = sum +num;
}

avg = sum/(float)n;

printf("\nSum of %d Numbers = %d",n, sum);


printf("\nAverage of %d Numbers = %.2f",n, avg);

return 0;
}

Output:

Enter How many Number you want?


5
Enter elements one by one
10
2
38
23
38

Sum of 5 Numbers = 111


Average of 5 Numbers = 22.20000

5. Explain about string input & output functions with suitable examples.

Ans: The gets() and puts() are declared in the header file stdio.h, are functions are involved
in the input/output operations of the strings.
C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All
the characters entered by the user get stored in a character array. The null character is added
to the array to make it a string. The gets() allows the user to enter the space-separated strings.
It returns the string entered by the user.

Declaration

char[] gets(char[]);

Example:

#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

Output:

Enter the string?


Hai! Welcome to C Programming
You entered Hai! Welcome to C Programming

The gets() function is risky to use since it doesn't perform any array bound checking
and keep reading the characters until the new line (enter) is encountered. It suffers from
buffer overflow, which can be avoided by using fgets().

C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to
print the string on the console which is previously read by using gets() or scanf() function.
The puts() function returns an integer value representing the number of characters being
printed on the console. Since, it prints an additional newline character with the string, which
moves the cursor to the new line on the console, the integer value returned by puts() will
always be equal to the number of characters present in the string plus 1.

Declaration

int puts(char[])

Example:

#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}

Output:
Enter your name: Hari
Your name is: Hari

6. Write a C program to find the smallest and largest elements of a given


array.

Program:

#include<stdio.h>

int main()
{
int a[50],i,n,large,small;
printf(“\nEnter the number of elements : “);
scanf(“%d”,&n);
printf(“\nInput the array elements : “);
for(i=0;i<n;++i)
scanf(“%d”,&a[i]);

large=small=a[0];

for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];

if(a[i]<small)
small=a[i];
}

printf(“\nThe smallest element is %d\n”,small);


printf(“\nThe largest element is %d\n”,large);

return 0;
}

Output:

Enter the number of elements : 5

Input the array elements : 1 2 3 4 5

The smallest element is 1

7. Explain about any five string manipulation functions?


Ans: The following are the list of string manipulation functions in C:

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination


string.

3) strcat(first_string, concats or joins first string with second string. The


second_string) result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both


second_string) strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function

The strlen() function returns the length of the given string. It doesn't count null
character '\0'.

#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}

Output:

Length of string is: 10

C Copy String: strcpy()

The strcpy(destination, source) function copies the source string in destination.

#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}

Output:

Value of second string is: javatpoint

C String Concatenation: strcat()

The strcat(first_string, second_string) function concatenates two strings and result


is returned to first_string.

#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
Output:

Value of first string is: helloc

C Compare String: strcmp()

The strcmp(first_string, second_string) function compares two string and returns 0


if both strings are equal.

Here, we are using gets() function which reads string from the console.

#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

C Reverse String: strrev()

The strrev(string) function returns reverse of the given string. Let's see a simple
example of strrev() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}

Output:

Enter string: javatpoint


String is: javatpoint
Reverse String is: tnioptavaj

8. Write a c program to find number of vowels , consonants and digits in


the given string

Program:

#include <stdio.h>
int main() {

char line[150];
int vowels, consonant, digit, space;

// initialize all variables to 0


vowels = consonant = digit = space = 0;

// get full line of string input


printf("Enter a line of string: ");
fgets(line, sizeof(line), stdin);

// loop through each character of the string


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

// convert character to lowercase


line[i] = tolower(line[i]);
// check if the character is a vowel
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u') {

// increment value of vowels by 1


++vowels;
}

// if it is not a vowel and if it is an alphabet, it is a consonant


else if ((line[i] >= 'a' && line[i] <= 'z')) {
++consonant;
}

// check if the character is a digit


else if (line[i] >= '0' && line[i] <= '9') {
++digit;
}

// check if the character is an empty space


else if (line[i] == ' ') {
++space;
}
}

printf("Vowels: %d", vowels);


printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);

return 0;
}

Output:

Enter a line of string: C++ 20 is the latest version of C++ yet.


Vowels: 9
Consonants: 16
Digits: 2
White spaces: 8
9. Explain about array of strings with examples

Ans: In C programming String is a 1-D array of characters and is defined as an


array of characters. But an array of strings in C is a two-dimensional array of
character types. Each String is terminated with a null character (\0). It is an
application of a 2d array.

Syntax:
char variable_name[r] = {list of string};
Here,
 var_name is the name of the variable in C.
 r is the maximum number of string values that can be stored in a string array.
 c is a maximum number of character values that can be stored in each string
array.

Example:

#include <stdio.h>

// Driver code
int main()
{
char arr[3][10] = {"Geek",
"Geeks", "Geekfor"};
printf("String array Elements are:\n");

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


{
printf("%s\n", arr[i]);
}
return 0;
}

Output:

String array Elements are:


Geek
Geeks
Geekfor

10. Write a C Program to perform multiplication of two matrices?


Ans:

Program:

#include<stdio.h>
int main()
{
int r1,r2,c1,c2;
printf("Enter number of rows for First Matrix:\n");
scanf("%d",&r1);
printf("Enter number of columns for First Matrix:\n");
scanf("%d",&c1);
printf("Enter number of rows for Second Matrix:\n");
scanf("%d",&r2);
printf("Enter number of columns for Second Matrix:\n");
scanf("%d",&c2);
if(c1!=r2)
{
printf("Matrices Can't be multiplied together");
}
else
{
int m1[r1][c1],m2[r2][c2];
printf("Enter first matrix elements \n");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
scanf("%d",&m1[i][j]);
}
}
printf("Enter Second matrix elements\n");
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
{
scanf("%d",&m2[i][j]);
}
}
int mul[r1][c2];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
mul[i][j]=0;

// Multiplying i’th row with j’th column


for(int k=0;k<c1;k++)
{
mul[i][j]+=m1[i][k]*m2[k][j];
}
}
}
printf("Multiplied matrix\n");
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
}
return 0;
}

Output:

Enter number of rows for First Matrix:


2
Enter number of columns for First Matrix:
2
Enter number of rows for Second Matrix:
2
Enter number of columns for Second Matrix:
2
Enter first matrix elements
13
56
Enter Second matrix elements
21
44
Multiplied matrix
14 13
34 29

11. Explain how to declare and initialize a three dimensional array with
suitable examples.

Ans: In C programming, you can create an array of arrays. These arrays are known
as multidimensional arrays. A 3D Array is an array which contains 3 dimensions.
The following is the syntax:

datatype arrayname[size1][size2][size3];

You can initialize a three-dimensional array in a similar way to a two-dimensional


array. Here's an example,

int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

Example:

// C Program to store and print 12 values entered by the user

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

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


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

// Printing values with the proper index.

printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

return 0;
}

Output:

Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12

Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

12. Write a c program to sort elements of an array in ascending order.


Ans:

#include <stdio.h>

int main()
{
//Initialize array
int arr[] = {5, 2, 8, 7, 1};
int temp = 0;

//Calculate length of array arr


int length = sizeof(arr)/sizeof(arr[0]);

//Displaying elements of original array


printf("Elements of original array: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
//Sort the array in ascending order
for (int i = 0; i < length; i++) {
for (int j = i+1; j < length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

printf("\n");

//Displaying elements of array after sorting


printf("Elements of array sorted in ascending order: \n");
for (int i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output:
Elements of original array:
52871
Elements of array sorted in ascending order:
12578

13. Write a C program to transpose a given matrix without using a second


matrix.

Ans:

#include<stdio.h>
void main()

int mat[12][12];

int i,j,row,col,temp;

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

scanf("%d%d",&row,&col);

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

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

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

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

printf("The matrix\n");

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

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

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

printf("\n");

//transpose logic using same matrix

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

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

temp=mat[i][j];

mat[i][j]=mat[j][i];

mat[j][i]=temp;

printf("The transpose of the matrix is\n");

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

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

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

printf("\n");

Output:

14. Write a c program to print individual characters of string in reverse


order without using string functions

Ans:
#include<stdio.h>
#include<string.h>
int rev() //Open rev function
{
char st[100];
int len,i;
gets(st); //Input the string
len=strlen(st); //Calculate length of the string using strlen() function
printf("\nThe reverse string is:");
for(i=len;i>=0;i--) //Loop to print reverse string
{
printf("%c",st[i]); //Print the reverse string's character one by one
}
};
int main() //Code given by Susobhan Akhuli
{
printf("Enter the string: ");
rev(); //Call rev function
return 0;
}

Output:

Enter the string: Susobhan

The reverse string is: nahbosuS

You might also like