C Programming Answers PDF
C Programming Answers PDF
BSC –I Sem - I
C Programming
1. What is an algorithm?
A. Flowchart
B. Flowchart or Pseudocode
C. A Decision
D. Step by step instructions used to solve problem
A. End
B. Decision Making
C. Input and Output
D. Processing
A. int
B. float
C. char
D. void
A. array
B. int
C. pointer
D. structure
A. 30
B. 20
C. 32
D. 31
A. breaker
B. default
C. shorter
D. go
# include<stdio.h>
int main()
{
int i;
for(i=0;i<5;i++)
{
int a = i;
}
printf(“%d”,a);
return 0;
}
A. if statement
B. if…else statement
C. switch statement
D. All the above
A. True
B. False
C. None of above
A. True
B. False
C. None of above
A. ?:
B. :?
C. :<
D. <:
A. if
B. if--else
C. if—else--if
D. all the above
A. for
B. while
C. if—else--if
D. both (i) & (ii)
A. yes
B. no
C. compile time error
D. run time error
A. continue
B. break
C. goto
D. return
21. This Loop tests the condition after having executed the
Statements within the Loop.
A. while
B. do--while
C. for
D. if—else--if
A. 1
B. 2
C. 10
D. Depends upon compiler
A. for
B. while
C. do--while
D. switch
24. switch statement accepts
A. int
B. char
C. long
D. all the above
A. for
B. while
C. do--while
D. both (A) & (B)
A. if
B. break
C. continue
D. exit
A. exit
B. break
C. default
D. continue
A. do--while
B. if--else
C. goto
D. for
A. int num[5]={1,2,3,4,5];
B. int num{} ={2,3,4,5};
C. int num{4}={1,2,3,4};
D. int num(5)={1,2,3,4,5};
A. Single dimensional
B. Two dimensional
C. Multi dimensional
D. All the above
A. memcpy()
B. strcopy()
C. memcopy()
D. strxcpy()
A. strcpy()
B. strcat()
C. strncon()
D. memcon()
39. Which string method helps to find the length of the string?
A. StringLength
B. strlen
C. strdup
D. Both (A) & (B)
A. %d
B. %f
C. %c
D. %s
A. ‘\0’
B. ‘\\0’
C. ‘’
D. “”
Char arr[]=”Hello”;
A. Decrements by 1
B. Adds 1
C. Doubles the value
D. Leaves it unchanged.
48. Which operator is used for logical OR in C?
A. &&
B. OR
C. |
D. ||
A. <stdio.h>
B. <conio.h>
C. <string.h>
D. None of the above
Ans: Flowcharts are a great tool for planning and visualizing the structure of a program,
including C programs. In the context of C programming, flowcharts can help you map out the
logic and flow of your code before you start writing it. This can be especially useful for complex
algorithms or for visualizing how different functions interact.
5. Flow Line (Arrow): Illustrates the direction of the process flow, showing the order in
which steps are executed.
6. Connector (Circle): Used to connect different parts of the flowchart, helpful in complex
flowcharts or those that span multiple pages.
Let's consider a simple C program that checks if a number is even or odd and print the result:
Ans:
1. Start
2. Input: Read the value of nn
3. Initialize: Set sum = 0
4. Loop: For i = 1 to n
o Add: sum = sum + i
5. Output: Display the value of sum
6. End
Ans:
1. if Statement
The if statement is used to test a condition. If the condition is true, the code
block inside the if statement is executed.
if (condition) {
}
2. if-else Statement
if (condition) {
} else {
This is used to test multiple conditions sequentially. The first condition that is
true will have its corresponding code block executed.
if (condition1) {
} else if (condition2) {
} else {
4. nested if Statement
if (condition1) {
if (condition2) {
// code to be executed if both condition1 and condition2 are true
5. switch Statement
The switch statement allows a variable to be tested for equality against a list of
values, each associated with a specific block of code.
switch (variable) {
case value1:
break;
case value2:
break;
default:
Key Points:
Ans:
1. for Loop
The for loop is used when the number of iterations is known beforehand. It
consists of three parts: initialization, condition, and increment/decrement.
// code to be executed
Example:
The while loop is used when the number of iterations is not known beforehand.
It continues to execute the block of code as long as the condition is true.
while (condition) {
// code to be executed
Example:
int i = 0;
i++;
3. do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the block
of code will be executed at least once. The condition is evaluated after the
execution of the code block.
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
i++;
This loop prints numbers from 0 to 9, ensuring that the code inside the loop is
executed at least once, even if the condition is false initially.
Key Points:
Ans:
Declaring an Array
To declare an array in C, you specify the data type of its elements, the name of
the array, and the number of elements it will hold:
int myArray[10];
This line declares an array named myArray that can hold 10 integers.
Initializing an Array
You can initialize an array at the time of declaration or later in the code. Here
are a few ways to initialize an array:
1. Initialization at Declaration
You can initialize an array when you declare it by providing a list of values
enclosed in curly braces:
If the number of values provided is less than the size of the array, the
remaining elements are automatically initialized to zero:
You can omit the size of the array if you are initializing it at the time of
declaration:
The compiler automatically determines the size based on the number of values
provided.
3. Individual Initialization
You can initialize individual elements of an array at a later point in the code:
int myArray[5];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
Multidimensional Arrays
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
#include <stdio.h>
int main() {
return 0;
In this example, the myArray is initialized with values {1, 2, 3, 4, 5} and the
program prints each element of the array.
6. Write a program to accept marks of subjects and calculate total and
percentage and display grade
Ans:
#include <stdio.h>
int main() {
int subjects;
scanf("%d", &subjects);
int marks[subjects];
int total = 0;
float percentage;
char grade;
// Input marks
scanf("%d", &marks[i]);
total += marks[i];
// Calculate percentage
// Determine grade
grade = 'A';
} else if (percentage >= 80) {
grade = 'B';
grade = 'C';
grade = 'D';
} else {
grade = 'F';
// Output results
return 0;
Explanation:
1. Input: The program first asks the user to enter the number of subjects.
2. Marks Input: It then prompts the user to enter the marks for each
subject, storing them in an array and calculating the total marks.
3. Percentage Calculation: It calculates the percentage by dividing the total
marks by the number of subjects.
4. Grade Determination: Based on the percentage, the program determines
the grade using a series of if-else statements:
o A: 90% and above
o B: 80% to 89%
o C: 70% to 79%
o D: 60% to 69%
o F: Below 60%
5. Output: Finally, the program prints the total marks, percentage, and
grade.
7. Write a program to accept 10 numbers and display them using array.
Ans:
#include <stdio.h>
int main() {
int numbers[10];
printf("Enter 10 numbers:\n");
scanf("%d", &numbers[i]);
printf("\n");
return 0;
Explanation:
Ans:
#include <stdio.h>
int main() {
scanf("%d", &num);
if (num <= 1) {
} else {
if (num % i == 0) {
break;
}
// Output: Display the result
if (isPrime) {
} else {
return 0;
Explanation:
Ans:
#include <stdio.h>
int main() {
if (i <= 1) {
next = i;
} else {
first = second;
second = next;
printf("\n");
return 0;
}
Explanation:
1. Initialize Variables:
o n is set to 10 to display the first 10 terms of the Fibonacci series.
o first and second are initialized to 0 and 1, the first two terms of the
series.
o next will store the next term in the series.
2. Print Series:
o The for loop runs 10 times.
o If i is 0 or 1, next is set to i (i.e., 0 for the first term and 1 for the
second term).
o For subsequent terms, next is calculated as the sum of the first
and second terms.
o first and second are then updated for the next iteration.
3. Output:
o The program prints the first 10 numbers in the Fibonacci series: 0,
1, 1, 2, 3, 5, 8, 13, 21, 34.
10. Write a C program to calculate factorial of given number using
recursion function.
Ans:
#include <stdio.h>
if (n == 0) {
return 1;
} else {
int main() {
int num;
scanf("%d", &num);
if (num < 0) {
} else {
return 0;
}
Explanation:
Ans:
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 92, 88}; // Initializing the array with marks
} return 0;
Explanation:
This simple program demonstrates how arrays can be used to store and
manipulate a collection of related data efficiently.
13. Explain different types of Operators with an example.
Ans:
1. Arithmetic Operators
These operators perform basic arithmetic operations such as addition, subtraction, multiplication,
division, and modulus.
• Example:
int a = 10, b = 3;
2. Relational Operators
These operators compare two values and return true or false based on the comparison.
• Example:
int a = 10, b = 3;
3. Logical Operators
These operators perform logical operations such as AND, OR, and NOT.
• Example:
int a = 1, b = 0;
4. Bitwise Operators
These operators perform bit-level operations such as AND, OR, XOR, NOT, and bit shifts.
• Example:
These operators are used to assign values to variables. They include =, +=, -=, *=, /=, and %=.
• Example:
int a = 10;
a += 5; // Equivalent to a = a + 5
a -= 3; // Equivalent to a = a - 3
a *= 2; // Equivalent to a = a * 2
a /= 2; // Equivalent to a = a / 2
a %= 3; // Equivalent to a = a % 3
These operators increment or decrement a variable by one. They include ++ and --.
• Example:
int a = 10;
This operator is a shorthand for an if-else statement. It takes three operands and is used to
evaluate a condition.
• Example:
8. Comma Operator
The comma operator allows two expressions to be evaluated in a single statement. The value of
the entire expression is the value of the last expression.
• Example:
9. Sizeof Operator
• Example:
int a = 10;
These operators include the address-of operator (&) and the dereference operator (*).
• Example:
int a = 10;
int value = *ptr; // value is now 10, the value at the address stored in ptr
14. Explain Problem Solving Process.
Ans:
Before you start writing any code, it's crucial to thoroughly understand the
problem you're trying to solve. Read the problem statement carefully, identify
the inputs, expected outputs, and the constraints.
Once you understand the problem, the next step is to plan the solution. This
involves breaking down the problem into smaller, manageable tasks and
deciding on the algorithms and data structures you will use. Creating a
flowchart or writing pseudocode can be very helpful in this phase.
Algorithm:
1. Start
2. Initialize max to the first element of the array
3. For each element i in the array:
o If i is greater than max, set max to i
4. Output max
5. End
Translate the algorithm into a C program. This involves writing the actual code
in the C programming language, following the syntax and semantics of C.
5. Testing and Debugging
After coding the solution, it's crucial to test your program with various inputs
to ensure it works correctly. Look for edge cases and test your program against
them. If the program doesn't produce the expected results, debug it to find and
fix errors. Common debugging techniques include:
Finally, document your code by adding comments that explain what each part
of the program does. This makes it easier to understand and maintain the code
in the future. Proper documentation is essential, especially for large and
complex programs.
Planning:
Optimization:
Documentation:
Ans:
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list,
compares adjacent elements, and swaps them if they are in the wrong order.
The pass through the list is repeated until the list is sorted.
#include <stdio.h>
int i, j, temp;
temp = arr[j];
arr[j + 1] = temp;
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
bubbleSort(arr, n);
printf("\n");
return 0;
Explanation:
1. Function bubbleSort:
o Parameters: Takes an array arr and its size n as parameters.
o Process: Uses nested loops to iterate through the array. In each
iteration, adjacent elements are compared and swapped if they are
in the wrong order.
2. Main Function:
o Input: The program prompts the user to enter the number of
elements and then the elements themselves.
o Sorting: Calls the bubbleSort function to sort the array.
o Output: Prints the sorted array.
Q.3 Answer the following questions (5 Marks each)
Ans:
Data Types in C
Data types in C programming define the type of data that a variable can hold.
They are fundamental in defining the nature of operations that can be
performed on the data, as well as the memory allocation for storing these
values. Here's a detailed overview of the various data types in C:
1. int (Integer):
o Description: Used to store integer values.
o Size: Typically 4 bytes (may vary based on the system).
o Example: int a = 10;
2. float (Floating Point):
o Description: Used to store single-precision floating-point numbers.
o Size: Typically 4 bytes.
o Example: float b = 3.14;
3. double (Double Precision Floating Point):
o Description: Used to store double-precision floating-point
numbers.
o Size: Typically 8 bytes.
o Example: double c = 3.1415926535;
4. char (Character):
o Description: Used to store single characters.
o Size: 1 byte.
o Example: char d = 'A';
1. Array:
o Description: A collection of elements of the same data type stored
in contiguous memory locations.
o Example: int arr[5] = {1, 2, 3, 4, 5};
2. Pointer:
o Description: A variable that stores the memory address of another
variable.
o Example: int *ptr = &a;
3. Structure:
o Description: A user-defined data type that allows to combine
different data types.
o Example:
struct Person {
char name[50];
int age;
float salary;
};
4. Union:
o Description: Similar to structures but shares memory among its
members.
o Example:
union Data {
int i;
float f;
char str[20];
};
• enum (Enumeration):
o Description: A user-defined data type that consists of integral
constants.
o Example:
• void:
o Description: Represents the absence of type. Commonly used in
functions to indicate no return value or no parameters.
o Example: void functionName(void);
2. Explain following Concepts
Ans:
i. Variables
Types of Variables:
ii. Keywords
Definition: Keywords are reserved words in C that have special meanings and
cannot be used as variable names or identifiers. They are part of the C
language syntax and are predefined by the compiler.
Common Keywords:
iii. Constants
Definition: Constants are fixed values that do not change during the execution
of a program. They are used to define values that remain constant throughout
the program.
Types of Constants:
Ans:
Jumping statements , such as break and continue, are used to alter the flow of
control in loops and switch statements. These statements help manage the
execution of loops by either terminating the loop prematurely or skipping the
rest of the loop iteration.
1. break Statement
Usage in Loops: In loops, break is used to exit the loop when a certain
condition is met, even if the loop has not iterated through all its elements.
2. continue Statement
Purpose: The continue statement is used to skip the remaining code in the
current iteration of a loop and proceed to the next iteration. Unlike break,
continue does not terminate the loop but skips to the next iteration.
Usage: The continue statement is useful when you want to skip certain
conditions within a loop without terminating the entire loop.
Summary
Both break and continue are powerful control flow statements that help
manage the execution of loops and make the code more efficient and readable.
Ans:
The while and do-while loops are both used to execute a block of code
repeatedly based on a condition. However, they differ in the way they check the
condition and execute the code block. Let's explore the differences between the
two:
• while Loop
Syntax:
while (condition) {
Characteristics:
Example:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
return 0;
Output:
01234
• do-while Loop
Syntax:
do {
} while (condition);
Characteristics:
Example:
#include <stdio.h>
int main() {
int i = 0;
do {
i++;
Output:
01234
Key Differences
Summary
• while Loop: Checks the condition before executing the code block. The
code block may not execute at all if the condition is false initially.
• do-while Loop: Checks the condition after executing the code block. The
code block is guaranteed to execute at least once.
5. Explain array
• Declaring an Array
To declare an array, you specify the type of its elements, the name of the array,
and the number of elements it can hold:
• Initializing an Array
If the number of values provided is less than the size of the array, the
remaining elements are initialized to zero.
#include <stdio.h>
int main() {
int myArray[5] = {10, 20, 30, 40, 50}; // Declares and initializes the array
printf("\n");
return 0;
• Multidimensional Arrays
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
int value = matrix[1][2]; // Accesses the element in the second row and third
column
• Advantages of Arrays
Ans:
Program:
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number % 2 == 0) {
} else {
} return 0;
Explanation:
1. Input:
The program prompts the user to enter an integer using scanf.
o
The entered number is stored in the variable number.
o
2. Condition Check:
o The program uses the modulus operator (%) to check the
remainder when number is divided by 2.
o If number % 2 == 0, the number is even.
o Otherwise, the number is odd.
3. Output:
o The program prints whether the entered number is even or odd.
7. Write a C program to accept 5 names using string.
Program:
#include <stdio.h>
int main() {
printf("Enter 5 names:\n");
scanf("%s", names[i]);
printf("%s\n", names[i]);
} return 0;
Explanation:
1. Array Declaration:
o char names[5][50] declares an array of 5 strings, each capable of
holding up to 49 characters (plus the null terminator).
2. Input Loop:
o The for loop iterates 5 times, prompting the user to enter a name
in each iteration.
o scanf("%s", names[i]) reads a name from the user and stores it in
the i-th position of the names array.
3. Output Loop:
o Another for loop iterates 5 times, printing each name stored in the
names array.
8. Explain Loop Control statements.
Ans:
Loop control statements in are used to control the flow of loops (like for, while,
and do-while). These statements help manage the execution of loops by
modifying their behavior based on certain conditions. The primary loop control
statements in C are break, continue, and goto.
1. break Statement
Usage in Loops: In loops, break is often used to exit the loop when a specific
condition is met, even if the loop has not iterated through all elements.
2. continue Statement
Purpose: The continue statement is used to skip the remaining code in the
current iteration of a loop and proceed to the next iteration. It does not
terminate the loop, but skips to the next iteration based on the loop's
condition.
3. goto Statement
Summary
Ans:
Program:
#include <stdio.h>
#include <math.h>
int main() {
scanf("%d", &num);
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
if ((int)result == num) {
} else {
return 0;
Explanation:
1. Input:
The program prompts the user to enter an integer using scanf.
o
The entered number is stored in the variable num.
o
2. Calculate the Number of Digits:
o A while loop is used to determine the number of digits in the
entered number. The original number is divided by 10 repeatedly
until it becomes 0, and the count of iterations (n) gives the number
of digits.
3. Calculate the Sum of the Power of Each Digit:
o The program iterates over each digit of the original number. For
each digit, it calculates the power of the digit raised to n (the
number of digits) using the pow function from the math.h library
and adds the result to the result variable.
4. Check Armstrong Condition:
o The program checks if the sum (result) is equal to the original
number (num). If they are equal, the number is an Armstrong
number; otherwise, it is not.
10. Write a C program to calculate area of circle.
#include<stdio.h>
int main()
float r,a,;
scanf("%f",&r);
a = 3.1415 * r * r;
Ans:
The for loop in C is a control flow statement that allows code to be executed
repeatedly based on a condition. It is particularly useful when the number of
iterations is known beforehand. The for loop provides a concise way of writing
the loop structure. Here’s a detailed explanation:
Syntax
• Components
1. Initialization:
o This part is executed only once at the beginning of the loop.
o It is typically used to initialize a counter variable.
o Example: int i = 0;
2. Condition:
o The condition is evaluated before each iteration.
If the condition is true, the code block inside the loop is executed.
o
If the condition is false, the loop terminates.
o
Example: i < 10;
o
3. Increment/Decrement:
o This part is executed at the end of each iteration.
o It is typically used to update the counter variable.
o Example: i++ (increments i by 1).
Example
#include <stdio.h>
int main() {
printf("%d\n", i);
return 0;
• Initialization: int i = 0;
o The loop starts with i set to 0.
• Condition: i < 10;
o The loop continues as long as i is less than 10.
• Increment: i++
o After each iteration, i is incremented by 1.
• Code Block:
o printf("%d\n", i);
o Prints the current value of i.
• Working of the Loop
• Variations
You can initialize more than one variable and increment multiple variables in a
for loop:
#include <stdio.h>
int main() {
return 0;
• Omitting Parts
Any of the three parts of the for loop can be omitted if not needed, but
the semicolons must remain:
• Without Initialization:
int i = 0;
printf("%d\n", i);
• Without Condition:
printf("%d\n", i);
}
• Without Increment:
printf("%d\n", i);
i++;
Infinite Loop
A for loop can also create an infinite loop if the condition always
evaluates to true (or if the condition is omitted):
for (;;) {
Summary
Ans:
Two-Dimensional Arrays
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements: You access the elements using two indices—one for the
row and one for the column.
int value = matrix[1][2]; // Accesses the element in the second row and third
column (value is 6)
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("\n");
return 0;
Higher-Dimensional Arrays
You can extend this concept to three-dimensional arrays (or even higher
dimensions). Here’s an example of declaring and initializing a three-
dimensional array:
int cube[2][3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
},
};
int value = cube[1][2][3]; // Accesses the element in the second block, third
row, and fourth column (value is 24)
#include <stdio.h>
int main() {
int cube[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
},
};
printf("\n");
printf("\n");
return 0;
}
13. Explain features of array.
1. Homogeneous Elements
3. Fixed Size
4. Indexed Access
6. Multidimensional Arrays
• Description: Arrays can have more than one dimension, such as two-
dimensional or three-dimensional arrays, to represent more complex
data structures like matrices and tables.
• Example: int matrix[3][3]; declares a 3x3 matrix.
printf("%d\n", arr[i]);
• Description: Arrays are often used as the basis for various sorting and
searching algorithms due to their simple structure and efficient element
access.
• Example: Algorithms like bubble sort, quick sort, and binary search are
commonly applied to arrays.
Summary
GCC Compiler
The GNU Compiler Collection (GCC) is a powerful and versatile compiler system
produced by the GNU Project. It supports various programming languages,
including C, C++, Objective-C, Fortran, Ada, and more. GCC is widely used for
its robustness, performance, and the extensive range of features it offers to
developers. Here's an overview of GCC and its key features:
1. Multi-Language Support:
o Languages: GCC supports multiple programming languages,
making it a versatile tool for developers. It includes front ends for
C, C++, Objective-C, Fortran, Ada, Go, and others.
o Example: You can compile a C program with gcc and a C++
program with g++.
2. Cross-Platform:
o Compatibility: GCC is cross-platform, meaning it runs on various
operating systems, including Linux, Windows, and macOS.
o Benefit: This cross-platform capability allows developers to compile
and run their code on different environments.
3. Optimization:
o Optimization Levels: GCC provides multiple levels of optimization
to improve the performance and efficiency of the compiled code.
These levels range from -O0 (no optimization) to -O3 (maximum
optimization).
o Example: gcc -O2 myprogram.c -o myprogram optimizes the code
for speed and performance.
4. Open Source:
o Availability: GCC is an open-source project under the GNU General
Public License (GPL). This means it is freely available for use,
modification, and distribution.
o Benefit: The open-source nature of GCC allows developers to
contribute to its development and adapt it to their needs.
5. Extensible:
o Plug-ins and Extensions: GCC supports plug-ins and extensions,
enabling developers to enhance its functionality and add new
features.
o Benefit: This extensibility makes GCC a flexible and adaptable tool
for various programming tasks.
6. Error and Warning Messages:
o Diagnostics: GCC provides comprehensive error and warning
messages to help developers identify and fix issues in their code.
o Benefit: Detailed diagnostics improve code quality and debugging
efficiency.
7. Inline Assembly:
o Support: GCC allows the inclusion of inline assembly code within
C and C++ programs. This feature is useful for low-level
programming and optimization.
o Example: Using asm keyword to include assembly instructions.
Advanced Features:
Conclusion
Ans:
Program:
#include <stdio.h>
int main() {
printf("Enter 10 numbers:\n");
scanf("%d", &numbers[i]);
sum += numbers[i];
return 0;
}
16. Explain functions in c, what are the type of function?
Ans:
Functions in C
1. Function Definition: The body of the function where the actual task is
performed.
2. Function Declaration: Also known as a function prototype, it provides
the function's name, return type, and parameters to the compiler before
its actual definition.
3. Function Call: Invoking the function to execute its defined task.
Types of Functions
1. Library Functions:
o Description: Predefined functions provided by C libraries.
o Examples: printf(), scanf(), strlen(), sqrt().
o Usage: Used for common tasks like input/output, string
manipulation, mathematical computations, etc.
2. User-Defined Functions:
Summary
Ans:
Program:
#include <stdio.h>
// Function declaration
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
return 0;
// Function definition
return a + b;
}
18. Write a program to calculate length of array.
Ans:
Program:
#include <stdio.h>
int main() {
int length;
return 0;
Explanation:
1. Array Initialization:
o int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; initializes an array
with 10 elements.
2. Calculate Length:
o sizeof(numbers) returns the total size of the array in bytes.
o sizeof(numbers[0]) returns the size of the first element (each
element is an int, so it returns the size of an integer).
o Dividing the total size of the array by the size of one element gives
the number of elements in the array: length = sizeof(numbers) /
sizeof(numbers[0]);.
3. Output:
o The program prints the calculated length of the array using printf.
19. Write a program to display even numbers upto n
Ans:
Program:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
if (i % 2 == 0) {
printf("\n");
return 0;
}
20. Explain if_else statement with an example.
The if_else statement is a control flow statement that allows you to execute
different blocks of code based on certain conditions. It is used to make
decisions in your code by evaluating a condition and then executing a
corresponding block of code based on whether the condition is true or false.
Syntax
if (condition) {
} else {
How It Works
Example Program
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
// If_else statement to check if the number is even or odd
if (number % 2 == 0) {
} else {
return 0;
Explanation
1. Variable Declaration:
o int number; declares a variable to store the user input.
2. User Input:
o printf("Enter an integer: "); prompts the user to enter a number.
o scanf("%d", &number); reads the input and stores it in the variable
number.
3. Condition Check:
o if (number % 2 == 0): The condition checks if the remainder when
number is divided by 2 is zero, meaning the number is even.
o If the condition is true, printf("%d is even.\n", number); is
executed, printing that the number is even.
o If the condition is false, the else block executes printf("%d is
odd.\n", number);, printing that the number is odd.
21. Explain Type casting in C.
Ans:
Type Casting
Type casting is the process of converting one data type into another. It is useful
when you need to perform operations between different data types or when you
want to ensure that a particular value is interpreted correctly by the compiler.
Type casting can be either implicit or explicit.
Also known as automatic type conversion, this is done by the compiler without
any explicit instruction from the programmer. It usually occurs when data
types are compatible and no data will be lost during the conversion.
1. Data Compatibility:
o Ensures that operations between different data types are
compatible.
o Example: Calculating the average of two integers and storing the
result as a float.
2. Memory Management:
o Helps in managing memory by converting larger data types to
smaller ones when precision is not critical.
o Example: Converting a double to an int for simple arithmetic
operations.
3. Precision Control:
o Ensures that values are interpreted correctly, especially in
mathematical and financial calculations where precision is
important.
o Example: Converting an integer to a float to perform division
accurately.
1. Loss of Data:
o Converting from a larger data type to a smaller one can result in
loss of data.
o Example: Casting a float to an int truncates the decimal part.
2. Precision Loss:
o Casting a floating-point number to an integer results in loss of
precision.
o Example: (int) 5.99 results in 5.
3. Undefined Behavior:
o Improper type casting can lead to undefined behavior and errors.
o Example: Casting a pointer to an incompatible type.
Summary
Type casting in C is a useful tool that allows you to convert data types for compatibility, memory
management, and precision control. It can be done implicitly by the compiler or explicitly by the
programmer using the cast operator. While powerful, it should be used with care to avoid
potential data loss or undefined behavior.
**
***
****
*****
Ans:
Program:
#include <stdio.h>
int main() {
printf(" ");
// Print stars
printf("*");
printf("\n");
return 0;
Explanation:
1. Variable Declaration:
o int n = 5; initializes the number of rows in the pyramid. You can
change this value to display a different number of rows.
2. Outer Loop:
o for (int i = 1; i <= n; i++): This loop runs from 1 to n, controlling the
number of rows.
3. Leading Spaces:
o for (int j = i; j < n; j++): This inner loop prints spaces before the
stars in each row. The number of spaces decreases as the row
number increases.
4. Print Stars:
o for (int k = 1; k <= (2 * i - 1); k++): This inner loop prints the stars
(*). The number of stars increases as the row number increases.
5. New Line:
o printf("\n"); moves the cursor to the next line after printing all
stars and spaces in a row.