C Programming Question Bank Solved
C Programming Question Bank Solved
int main() {
int dayNumber;
switch (dayNumber) {
case 1:
printf("Day: Sunday\n");
break;
case 2:
printf("Day: Monday\n");
break;
case 3:
printf("Day: Tuesday\n");
break;
case 4:
printf("Day: Wednesday\n");
break;
case 5:
printf("Day: Thursday\n");
break;
case 6:
printf("Day: Friday\n");
break;
case 7:
printf("Day: Saturday\n");
break;
default:
printf("Invalid input. Please enter a number between 1 and 7.\n");
}
return 0;
}
Explanation:
1. Include Header:
o #include <stdio.h> includes the standard input/output library, which provides
functions like printf and scanf for interacting with the user.
2. Declare Variable:
o int dayNumber; declares an integer variable named dayNumber to store the
input from the user.
3. Get Input:
o printf("Enter a number (1-7) representing the day of the week: "); displays a
message to the user, prompting them to enter a number.
o scanf("%d", &dayNumber); reads the integer entered by the user and stores it
in the dayNumber variable.
4. Use switch Statement:
o The switch statement evaluates the value of dayNumber.
o Each case block corresponds to a specific day number (1-7).
o If dayNumber matches a case value, the corresponding code block is
executed.
o The break statement is used to exit the switch block after executing the code
for the matching case.
o The default block is executed if none of the case values match the
dayNumber.
5. Print Output:
o Inside each case block, printf() is used to print the corresponding day of the
week.
6. Return 0:
o return 0; indicates successful program execution.
This program effectively demonstrates how to use a switch statement to determine and
print the day of the week based on a given numeric input.
10.write an program to create a simple calculator? Along with algorithm and it flowchart
and it's output.
Here's the C program for a simple calculator, along with the algorithm, flowchart, and
sample output:
Algorithm:
1. Start
2. Declare variables:
o num1, num2: To store the input numbers
o operator: To store the operator (+, -, *, /)
o result: To store the calculated result
3. Prompt the user to enter the first number
4. Read the first number from the user
5. Prompt the user to enter the operator
6. Read the operator from the user
7. Prompt the user to enter the second number
8. Read the second number from the user
9. Use a switch statement to perform the calculation based on the operator:
o +: Add num1 and num2
o -: Subtract num2 from num1
o *: Multiply num1 and num2
o /: Divide num1 by num2 (check for division by zero)
10. Print the result
11. End
Flowchart:
+--------------------+
| Start |
+--------------------+
| Declare variables: |
| num1, num2, operator, result |
+--------------------+
| Input: num1 |
+--------------------+
| Input: operator |
+--------------------+
| Input: num2 |
+--------------------+
| Switch (operator) |
| Case '+': |
| result = num1 + num2 |
| Case '-': |
| result = num1 - num2 |
| Case '*': |
| result = num1 * num2 |
| Case '/': |
| if (num2 != 0) |
| result = num1 / num2 |
| else |
| Print "Error: Division by zero" |
| Default: |
| Print "Invalid operator" |
+--------------------+
| Print result |
+--------------------+
| End |
+--------------------+
C Program:
C
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if(num2 != 0) {
result = num1 / num2;
} else {
printf("Error: Division by zero\n");
return 1; // Indicate an error
}
break;
default:
printf("Error: Invalid operator\n");
return 1; // Indicate an error
}
int main() {
int num;
if (num < 0) {
printf("The number is negative: %d\n", num);
}
return 0;
}
Sample Output:
Enter a number: -10
The number is negative: -10
Explanation:
1. The program starts by declaring an integer variable num to store the input number.
2. It prompts the user to enter a number using printf and reads the input using scanf.
3. The if statement checks if the value of num is less than 0.
4. If the condition is true (i.e., num is negative), the program prints the value of num
using printf.
5. The program then terminates.
This program effectively demonstrates how to check if a number is negative and display it
accordingly.
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
// Access and assign values to array elements
• Types of 1D Arrays:
o Integer Array: Stores integers (e.g., int numbers[10];)
o Float Array: Stores floating-point numbers (e.g., float prices[5];)
o Character Array (String): Stores a sequence of characters (e.g., char
name[20];)
2. 2D Array (Two-Dimensional Array)
• Definition: A 2D array is a tabular arrangement of elements of the same data type,
organized in rows and columns. It's essentially an array of arrays.
• Syntax:
C
data_type array_name[rows][columns];
o data_type: Specifies the type of elements the array will hold.
o array_name: The name you give to the array.
o rows: The number of rows in the array.
o columns: The number of columns in the array.
• Example:
C
int matrix[3][3]; // Declares a 3x3 integer matrix
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
// ... and so on
• Types of 2D Arrays:
o Matrix: Represents mathematical matrices for various operations.
o Image Representation: Can be used to store pixel data for images.
o Game Boards: Can represent game boards like chess or tic-tac-toe.
Key Points:
• Array indices start from 0. For example, in a 1D array with size 5, the valid indices are
0, 1, 2, 3, and 4.
• Arrays provide an efficient way to store and access collections of data.
• 2D arrays are more complex to visualize and manipulate compared to 1D arrays.
I hope this explanation is helpful!
5.what is user define functions types in c ? Explain with syntax with its types .
Certainly, let's explore user-defined functions in C.
User-Defined Functions
• Definition: In C, a function is a block of code that performs a specific task. User-
defined functions are created by the programmer to encapsulate a set of instructions
that can be reused multiple times within a program.
• General Syntax:
C
return_type function_name(parameter1, parameter2, ...) {
// Code to be executed within the function
return value; // If the function has a return type
}
• Components:
o return_type: Specifies the data type of the value returned by the function
(e.g., int, float, char, void). If the function does not return any value, void is
used.
o function_name: The name you give to the function, following the same rules
as identifiers.
o parameters: A comma-separated list of variables that receive values from the
caller of the function. Each parameter has its own data type.
o Function Body: The block of code that performs the desired operations.
o return statement: (Optional) Used to return a value from the function. If the
function has a void return type, the return statement is not used.
Types of User-Defined Functions
• Functions with no arguments and no return value (void):
C
void greet() {
printf("Hello, world!\n");
}
• Functions with arguments and no return value (void):
C
void display(int num) {
printf("The number is: %d\n", num);
}
• Functions with arguments and a return value:
C
int add(int a, int b) {
int sum = a + b;
return sum;
}
• Functions with no arguments and a return value:
C
int getRandomNumber() {
// Generate a random number
return rand();
}
Advantages of Using Functions:
• Modularity: Breaks down complex problems into smaller, more manageable units.
• Reusability: Avoids code duplication by allowing you to reuse the same code block
multiple times.
• Readability: Improves code readability and maintainability by making the code more
organized.
• Debugging: Makes debugging easier by isolating specific functionalities within
functions.
By effectively using user-defined functions, you can write more efficient, organized, and
maintainable C programs.
I hope this explanation is helpful!
int main() {
int num1 = 5, num2 = 3, sum;
// Function call
sum = add(num1, num2);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
In this example:1
• The add function takes two integers as input and returns their sum.
• The main function calls the add function with the values 5 and 3.
• The add function calculates the sum and returns it to the main function.
• The main function then prints the result.
Key Advantages of Using Functions:
• Modularity: Breaks down complex problems into smaller, more manageable units.
• Reusability: Avoids code duplication by allowing you to reuse the same code block
multiple times.
• Readability: Improves code readability and maintainability by making the code more
organized.
• Debugging: Makes debugging easier by isolating specific functionalities within
functions.
Functions are essential for writing well-structured, efficient, and maintainable C programs.
7.what is library functions (math string) types in c ? Explain with syntax with its types.
Certainly, let's explore library functions in C, specifically focusing on math and string
functions.
Library Functions in C
Library functions are pre-written and pre-compiled code blocks that provide a wide range of
functionalities. They are included in header files, which you include in your C program using
the #include directive. This allows you to use these functions without having to write their
implementations yourself.
1. Math Library Functions
• Header File: #include <math.h>
• Common Functions:
o sqrt(x): Calculates the square root of x.
o pow(x, y): Calculates x raised to the power of y.
o sin(x): Calculates the sine of x (in radians).
o cos(x): Calculates the cosine of x (in radians).
o tan(x): Calculates the tangent of x (in radians).1
o log(x): Calculates the natural logarithm (base e) of x.
o log10(x): Calculates the common logarithm (base 10) of x.
o ceil(x): Returns the smallest integer greater than or equal to x.
o floor(x): Returns the largest integer less than or equal to2 x.
o abs(x): Returns the absolute value of x.
• Example:
C
#include <stdio.h>
#include <math.h>
int main() {
double num = 25.0;
double sqrt_num = sqrt(num);
printf("Square root of %.2f is: %.2f\n", num, sqrt_num);
return 0;
}
2. String Library Functions
• Header File: #include <string.h>
• Common Functions:
o strlen(str): Returns the length of the string str.
o strcpy(dest, src): Copies the string src to the string dest.
o strcat(dest, src): Concatenates (appends) the string src to the end of the
string dest.
o strcmp(str1, str2): Compares two strings lexicographically. Returns 0 if they
are equal, a negative value if str1 is less than str2, and a positive value if str1
is greater than str2.
o strchr(str, ch): Finds the first occurrence of the character ch in the string str
and returns a pointer to it.
o strstr(str1, str2): Finds the first occurrence of the substring str2 within the
string str1 and returns a pointer to it.
• Example:
C
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = " World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Key Points:
• Library functions provide pre-built solutions for common tasks, saving you time and
effort.
• Always include the appropriate header file to use library functions.
• Refer to the C library documentation for detailed information on available functions
and their usage.
I hope this explanation is helpful!
10.what is array in c ? Explain with syntax with its types that is call by value and call by
reference.
In C, an array is a collection of elements of the same data type stored in contiguous
memory locations. This means that the elements are1 placed one after another in memory,
allowing you to access them efficiently using an index.
Syntax:
C
data_type array_name[size];
• data_type: Specifies the type of elements the array will hold (e.g., int, float, char).
• array_name: The name you give to the array.
• size: The number of elements the array can hold.
Example:
C
int numbers[5]; // Declares an array named 'numbers' to hold 5 integers
Accessing Array Elements:
You can access individual elements of an array using their index. The index starts from 0.
C
numbers[0] = 10; // Assigns 10 to the first element of the array
int value = numbers[2]; // Retrieves the value of the third element
Types of Arrays in C
• One-Dimensional Array (1D Array): A simple linear collection of elements.
o Example: int numbers[5];
• Two-Dimensional Array (2D Array): An array of arrays, often used to represent tables
or matrices.
o Syntax: data_type array_name[rows][columns];
o Example: int matrix[3][3]; // Declares a 3x3 matrix
• Multi-Dimensional Arrays: Arrays with more than two dimensions.
o Example: int cube[3][3][3]; // Declares a 3D array
Call by Value vs. Call by Reference with Arrays
• Call by Value:
o When an array is passed to a function by value, a copy of the entire array is
created and passed to the function.
o Any modifications made to the array within the function do not affect the
original array in the calling function.
• Call by Reference:
o When an array is passed to a function by reference, only the address of the
first element of the array is passed.
o This means that the function can directly access and modify the original array
elements.
Example:
C
#include <stdio.h>
int main() {
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {1, 2, 3, 4, 5};
printf("arr1: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr1[i]); // Output: 1 2 3 4 5 (original array not modified)
}
printf("\n");
printf("arr2: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr2[i]); // Output: 2 4 6 8 10 (original array modified)
}
printf("\n");
return 0;
}
In this example:
• modifyArray1 receives a copy of the arr1 array. Changes made within the function do
not affect the original arr1.
• modifyArray2 receives the address of the first element of arr2. Changes made within
the function directly modify the original arr2.
Key Points:
• Arrays are a fundamental data structure in C for storing and manipulating collections
of data.
• Understanding call by value and call by reference is crucial when working with arrays
and functions.
• Choose the appropriate method (call by value or call by reference) based on your
specific needs and whether you want to modify the original array within the
function.
I hope this comprehensive explanation of arrays in C, including call by value and call by
reference, is helpful!