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

CP CT 2 Important Questions Answers

Uploaded by

vaibhavbhise221
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)
42 views

CP CT 2 Important Questions Answers

Uploaded by

vaibhavbhise221
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/ 15

Shri Yashwantrao Bhonsale Education Society’s

YASHWANTRAO BHONSALE INSTITUTE OF


TECHNOLOGY (DTE CODE : 3470) (MSBTE CODE : 1742)
Approved by AICTE, DTE & Affiliated to Mumbai University & MSBTE Mumbai
(NBA Accredited ME, CE, EE Diploma Programs)

C Programming (FEC205)
Important questions for Class Test 2

1. Explain compile time and run time initialization of an array with proper
example.

In C, arrays can be initialized either at compile time or at run time.

Compile Time Initialization:


Compile-time initialization refers to initializing the array elements with known
constant values at the time of writing the code. The values are known to the
compiler during compilation, and they are directly specified in the code.

Here's an example of compile-time initialization:

#include <stdio.h>

int main() {
// Compile-time initialization of an array
int numbers[] = {1, 2, 3, 4, 5};

// Printing the array elements


printf("Array elements:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

return 0;
}
In this example:

The array numbers is initialized at compile time with the values {1, 2, 3, 4, 5}.
The compiler knows the size and values of the array at compile time, so it can
allocate memory accordingly.
Run Time Initialization:
Run-time initialization refers to initializing the array elements with values obtained
during program execution. The values are not known to the compiler during
compilation and are determined dynamically during program execution.

Here's an example of run-time initialization:

#include <stdio.h>

int main() {
int n;

// Prompt the user to enter the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Declare an array of size 'n'


int numbers[n];
// Run-time initialization of the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &numbers[i]);
}
// Printing the array elements
printf("Array elements:\n");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

return 0;
}
In this example:

The size of the array numbers is determined at run time based on the user input.
The array elements are initialized with values entered by the user during program
execution.
Since the size and values of the array are determined dynamically at run time, it's
called run-time initialization.
2. Write a C program that uses functions to perform Multiplication of Two
Matrices.
#include <stdio.h>

#define MAX_SIZE 10 // Maximum size for matrices

void matrix_multiply(int mat1[][MAX_SIZE], int mat2[][MAX_SIZE], int


result[][MAX_SIZE], int rows1, int cols1, int rows2, int cols2) {
int i, j, k;

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


for (j = 0; j < cols2; j++) {
result[i][j] = 0;
for (k = 0; k < cols1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

void input_matrix(int rows, int cols, int mat[][MAX_SIZE]) {


int i, j;

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


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

void print_matrix(int rows, int cols, int mat[][MAX_SIZE]) {


int i, j;

printf("The matrix is:\n");


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat1[MAX_SIZE][MAX_SIZE], mat2[MAX_SIZE][MAX_SIZE],
result[MAX_SIZE][MAX_SIZE];
int rows1, cols1, rows2, cols2;

// Input number of rows and columns for matrix 1


printf("Enter the number of rows for matrix 1: ");
scanf("%d", &rows1);
printf("Enter the number of columns for matrix 1: ");
scanf("%d", &cols1);

// Input number of rows and columns for matrix 2


printf("Enter the number of rows for matrix 2: ");
scanf("%d", &rows2);
printf("Enter the number of columns for matrix 2: ");
scanf("%d", &cols2);

// Check if multiplication is possible


if (cols1 != rows2) {
printf("Matrix multiplication is not possible!\n");
return 1;
}

// Input elements for matrix 1


input_matrix(rows1, cols1, mat1);

// Input elements for matrix 2


input_matrix(rows2, cols2, mat2);

// Multiply matrices
matrix_multiply(mat1, mat2, result, rows1, cols1, rows2, cols2);

// Display result matrix


printf("Result of matrix multiplication:\n");
print_matrix(rows1, cols2, result);

return 0;
}
3. Explain following functions with proper example.
a. strcmp
b. strrev
c. strstr
d. strcat
e. strcpy
a. strcmp (String Compare):
The strcmp function compares two strings lexicographically (i.e., based on their alphabetical order). It
returns an integer value based on the comparison result:

Returns 0 if the strings are equal.


Returns a negative value if the first string is lexicographically less than the second string.
Returns a positive value if the first string is lexicographically greater than the second string.
Here's an example:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "apple";
char str2[] = "banana";

int result = strcmp(str1, str2);

if (result == 0) {
printf("Both strings are equal.\n");
} else if (result < 0) {
printf("%s comes before %s in lexicographical order.\n", str1, str2);
} else {
printf("%s comes after %s in lexicographical order.\n", str1, str2);
}

return 0;
}
Output:
apple comes before banana in lexicographical order.

b. strrev (String Reverse):


The strrev function reverses the given string in place. It modifies the original string.
// C program to demonstrate
// example of strrev() function

#include <stdio.h>
#include <string.h>

int main()
{
char str[50] = "geeksforgeeks";

printf("The given string is =%s\n", str);


printf("After reversing string is =%s", strrev(str));

return 0;
}
Output:

The given string is = geeksforgeeks


After reversing string is = skeegrofskeeg

c. strstr()
The strstr function in C is used to find the first occurrence of a substring within a larger string. It stands for
"string find". The function takes two arguments: the string in which to search and the substring to search
for. It returns a pointer to the first occurrence of the substring within the string, or NULL if the substring is
not found.

Syntax
char *strstr (const char *s1, const char *s2);
Parameters
s1: This is the main string to be examined.
s2: This is the sub-string to be searched in string.

// C program to illustrate strstr()

#include <stdio.h>
#include <string.h>

int main()
{
// Take any two strings
char s1[] = "GeeksforGeeks";
char s2[] = "for";
char* p;

// Find first occurrence of s2 in s1


p = strstr(s1, s2);

// Prints the result


if (p) {
printf("String found\n");
printf("First occurrence of string '%s' in '%s' is %s'", s2, s1, p);
}
else
printf("String not found\n");

return 0;
}

Output
String found
First occurrence of string 'for' in 'GeeksforGeeks' is 'forGeeks'

d. strcat
The strcat function in C is used to concatenate (i.e., append) one string to the end of another string. It stands
for "string concatenation". The function takes two arguments: the destination string (the string to which the
other string will be appended) and the source string (the string that will be appended to the destination
string). The destination string must have enough space to accommodate the concatenated string.

Here's the syntax of strcat:

char *strcat(char *dest, const char *src);


• dest: A pointer to the destination string, which should be large enough to hold the concatenated
result.
• src: A pointer to the source string, which will be appended to the destination string.
And here's an example demonstrating the usage of strcat:

#include <stdio.h>
#include <string.h>

int main() {
char dest[20] = "Hello, ";
const char src[] = "world!";

// Concatenate the source string to the destination string


strcat(dest, src);

// Print the concatenated string


printf("Concatenated string: %s\n", dest);

return 0;
}
Output:

Concatenated string: Hello, world!

e. strcpy (Copy string):


The strcpy function in C is used to copy a string from one location to another. It stands for "string copy". It
takes two arguments: the destination string and the source string. It copies each character from the source
string to the destination string until it encounters the null terminator ('\0') in the source string.

Here's the syntax of strcpy:

char *strcpy(char *destination, const char *source);


destination: Pointer to the destination array where the content is to be copied.
source: Pointer to the source string to be copied.

here's an example demonstrating the usage of strcpy:

#include <stdio.h>
#include <string.h>

int main() {
char source[] = "Hello, world!";
char destination[20]; // Make sure destination has enough space to hold the source string

// Copy the source string to the destination string


strcpy(destination, source);

// Print the destination string


printf("Copied string: %s\n", destination);

return 0;
}
Output:
Copied string: Hello, world!

4. Define what are arrays? Explain how we declare and initialize 1D and 2D arrays
with simple example.
Arrays in C are a collection of elements of the same data type that are stored in
contiguous memory locations. They provide a convenient way to store and
manipulate multiple values of the same type under a single name.

1D arrays
In C, you can declare and initialize a 1D array using the following syntax:
data_type array_name[array_size] = {value1, value2, ..., valueN};
Here's a breakdown of each part:
• data_type: Specifies the data type of the elements in the array.
• array_name: Specifies the name of the array.
• array_size: Specifies the number of elements in the array.
• {value1, value2, ..., valueN}: Represents the initial values of the elements in the
array.
Here's a simple example demonstrating how to declare and initialize a 1D array of
integers:

#include <stdio.h>

int main() {
// Declare and initialize a 1D array of integers
int numbers[5] = {1, 2, 3, 4, 5};

// Print the elements of the array


printf("Elements of the array:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

return 0;
}
Output:
Elements of the array: 1 2 3 4 5

2D arrays
Here's how you declare and initialize a 2D array in C:

data_type array_name[row_size][column_size] = {
{val_11, val_12, ..., val_1N},
{val_21, val_22, ..., val_2N},
...
{val_M1, val_M2, ..., val_MN}
};
• data_type: Specifies the data type of the elements in the array.
• array_name: Specifies the name of the array.
• row_size and column_size: Specify the number of rows and columns in the
array, respectively.
• val_ij: Represents the value of the element at the ith row and jth column.

Here's a simple example of declaring and initializing a 2D array representing a 3x3


matrix:

#include <stdio.h>

int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Printing the elements of the 2D array


printf("Matrix elements:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

return 0;
}
5. Why we need structures. Define Structure and explain the syntax of declaration of
Structure with example.

Structures in C programming are used to group together different types of variables


under a single name. They provide a way to organize related data into a meaningful
unit. Here are several reasons why structures are useful in C programming:

1. Organizing Data: Structures allow you to organize related data items into a
single unit, making it easier to manage and manipulate complex data.

2. Abstraction: Structures provide a level of abstraction by encapsulating data


and operations into a single entity. This helps in simplifying the code and
making it easier to understand.

3. Modularity: Structures promote modularity by allowing you to create


reusable components that can be easily integrated into different parts of the
program.

4. Passing Complex Data: Structures enable you to pass complex data structures
as arguments to functions, making it easier to work with large datasets.

5. Memory Allocation: Structures facilitate memory allocation by grouping


related variables together, which helps in efficient memory management.

6. Code Readability: Structures improve code readability by providing a clear


and concise way to represent complex data relationships.

7. Data Hiding: Structures can be used to hide implementation details and


expose only the necessary information, promoting encapsulation and
information hiding principles.

8. Enhanced Maintainability: Structures make it easier to maintain and update


the codebase, as related data items are grouped together, allowing for easier
identification and modification.

A structure in C is a user-defined data type that allows you to group together


different types of variables under a single name. Each variable within a structure is
called a member or field. Structures are commonly used to represent a collection of
related data fields that together describe a single entity or concept.
The syntax for declaring a structure in C is as follows:
struct structure_name {
member_type1 member_name1;
member_type2 member_name2;
// Additional members...
};
Here's what each part of the syntax represents:

• struct: This keyword is used to define a structure.


• structure_name: This is the name you choose for the structure. It's like a
blueprint that describes the layout of the data structure.
• member_type1, member_type2, etc.: These are the data types of the
members (fields) of the structure.
• member_name1, member_name2, etc.: These are the names of the members
(fields) of the structure.
Here's an example of defining a structure representing a point in 2D space:

#include <stdio.h>

// Define a structure called Point


struct Point {
int x;
int y;
};

int main() {
// Declare a variable of type Point
struct Point p1;

// Access and initialize members of the structure


p1.x = 10;
p1.y = 20;

// Print the values of the members


printf("Coordinates of point p1: (%d, %d)\n", p1.x, p1.y);

return 0;
}

6. Write a program to store information of 10 students using structure.


Information include Roll_number, Name, Marks of student.
#include <stdio.h>

// Define a structure to store student information


struct Student {
int roll_number;
char name[50];
float marks;
};

int main() {
// Declare an array of structures to store information of 10 students
struct Student students[10];

// Input information for each student


printf("Enter information for 10 students:\n");
for (int i = 0; i < 10; i++) {
printf("Student %d:\n", i + 1);
printf("Enter roll number: ");
scanf("%d", &students[i].roll_number);
printf("Enter name: ");
scanf("%s", students[i].name); // Note: Using %s for string input
printf("Enter marks: ");
scanf("%f", &students[i].marks);
}

// Display information for each student


printf("\nInformation of 10 students:\n");
for (int i = 0; i < 10; i++) {
printf("Student %d:\n", i + 1);
printf("Roll number: %d\n", students[i].roll_number);
printf("Name: %s\n", students[i].name);
printf("Marks: %.2f\n", students[i].marks);
}

return 0;
}

7. Write a C program to find both the largest and smallest number in a list of integers.
#include <stdio.h>

int main() {
int num;
int largest, smallest;

// Ask the user to enter the number of integers in the list


printf("Enter the number of integers: ");
scanf("%d", &num);

// Initialize variables to store the largest and smallest numbers


int arr[num];

// Ask the user to enter the integers


printf("Enter %d integers:\n", num);
for (int i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}

// Initialize largest and smallest with the first element of the array
largest = smallest = arr[0];

// Find the largest and smallest numbers in the array


for (int i = 1; i < num; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}

// Print the largest and smallest numbers


printf("The largest number is: %d\n", largest);
printf("The smallest number is: %d\n", smallest);

return 0;
}
Output
Enter 7 integers:
10 23 54 67 54 23 32
The largest number is: 67
The smallest number is: 10

8. Write a program in C to find average of N elements entered by the user using an


array.

#include <stdio.h>

int main() {
int num;
float sum = 0.0, average;

// Ask the user to enter the number of elements


printf("Enter the number of elements: ");
scanf("%d", &num);

// Declare an array of size 'num'


int arr[num];

// Ask the user to enter the elements


printf("Enter %d elements:\n", num);
for (int i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}

// Calculate the sum of all elements


for (int i = 0; i < num; i++) {
sum += arr[i];
}

// Calculate the average


average = sum / num;

// Print the average


printf("The average of the elements is: %.2f\n", average);

return 0;
}
Output
Enter the number of elements: 5
Enter 5 elements:
10
12
32
43
13
The average of the elements is: 22.00
9. Write a program to check whether the entered string is palindrome or not.

#include <stdio.h>
#include <string.h>

int main() {
char str[100];
int i, j;
int isPalindrome = 1; // Assume initially that the string is a palindrome

printf("Enter a string (in lowercase): ");


scanf("%s", str);

// Calculate the length of the string


int len = strlen(str);

// Check for palindrome


for (i = 0, j = len - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
isPalindrome = 0; // If characters don't match, it's not a palindrome
break;
}
}

// Print the result


if (isPalindrome) {
printf("The entered string is a palindrome.\n");
} else {
printf("The entered string is not a palindrome.\n");
}

return 0;
}

Output :
Enter a string (in lowercase): nitin
The entered string is a palindrome.

You might also like