0% found this document useful (0 votes)
35 views20 pages

Faq Key C

Uploaded by

kanmanikrish988
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)
35 views20 pages

Faq Key C

Uploaded by

kanmanikrish988
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

CS25C01-COMPUTER PROGRAMMING: C

FREQUENTLY ASKED QUESTIONS


UNIT-1 INTRODUCTION TO C

PART-B

1. Draw the structure of a C program and explain each part in detail. (Apr/May
2022,2024,Nov/Dec 2019,2024)
2. Explain the various data type of being supported by C
(Apr/May2023,Nov/Dec2023)
3. Enumerate the difference between‘else-if ladder’ and ‘switch-case’ statements
with appropriate C programs. (Apr/May 2022)
The else-if ladder and switch-case statements in C are both used for conditional execution,
allowing a program to choose different paths based on certain conditions. However, they
differ in their structure, flexibility, and application.
Differences:
 Expression Type:
 Else-if ladder: Can evaluate complex boolean expressions involving various data types
(integers, floats, characters, strings) and logical operators (&&, ||, !).
 Switch-case: Primarily evaluates a single integer or character expression against a list of
constant integer or character values.
 Condition Evaluation:
 Else-if ladder: Conditions are evaluated sequentially from top to bottom. The first
condition that evaluates to true has its corresponding block executed, and the rest of the
ladder is skipped.
 Switch-case: The control jumps directly to the case label whose value matches
the switch expression. This is typically more efficient for a large number of discrete
values.
 Flexibility:
 Else-if ladder: More flexible as it can handle a wider range of conditions, including
ranges and complex logical combinations.
 Switch-case: Less flexible as it's limited to equality checks against constant values for a
single expression.
Else-if Ladder Example:
#include <stdio.h>
int main() {
int score = 75;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n"); }
return 0;}
Switch-case Example:
#include <stdio.h>
int main() {
char grade_char = 'C';
switch (grade_char) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Very Good!\n");
break;
case 'C':
printf("Good!\n");
break;
case 'D':
printf("Pass!\n");
break;
case 'F':
printf("Fail!\n");
break;
default:
printf("Invalid grade character.\n");
break; }
return 0;
}
4. Is it possible to convert ‘if-else ’ladder to ‘switch…case’ statement? If yes,
illustrate with an example. if no, justify the reason (Nov/Dec 2023)
The else-if ladder and switch-case statements in C are both used for conditional execution,
allowing a program to choose different paths based on certain conditions. However, they
differ in their structure, flexibility, and application.

Differences:

 Expression Type:

 Else-if ladder: Can evaluate complex boolean expressions involving various data types
(integers, floats, characters, strings) and logical operators (&&, ||, !).

 Switch-case: Primarily evaluates a single integer or character expression against a list of


constant integer or character values.
 Condition Evaluation:

 Else-if ladder: Conditions are evaluated sequentially from top to bottom. The first
condition that evaluates to true has its corresponding block executed, and the rest of the
ladder is skipped.

 Switch-case: The control jumps directly to the case label whose value matches
the switch expression. This is typically more efficient for a large number of discrete
values.
 Flexibility:

 Else-if ladder: More flexible as it can handle a wider range of conditions, including
ranges and complex logical combinations.

 Switch-case: Less flexible as it's limited to equality checks against constant values for a
single expression.
Else-if Ladder Example:

#include <stdio.h>
int main() {
int score = 75;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n"); }
return 0;}

Switch-case Example:

#include <stdio.h>
int main() {
char grade_char = 'C';
switch (grade_char) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Very Good!\n");
break;
case 'C':
printf("Good!\n");
break;
case 'D':
printf("Pass!\n");
break;
case 'F':
printf("Fail!\n");
break;
default:
printf("Invalid grade character.\n");
break; }
return 0;}

5. Write a C program to get age and vaccination detail as input. print “senior
citizen and eligible for booster”if age>60andvaccinationinput as‘2’. Otherwise
print “below60, and eligible for vaccination”. Use conditional operator
(Nov/Dec 2023) PROGRAM :
#include <stdio.h>
int main() {
int age;
int vaccination_status; // 2 for fully vaccinated, other values for not fully
vaccinated
// Get age input
printf("Enter age: ");
scanf("%d", &age);
// Get vaccination status input
printf("Enter vaccination status (2 for completed vaccination, any other number
otherwise): ");
scanf("%d", &vaccination_status);
// Use conditional operator to determine and print the message
(age > 60 && vaccination_status == 2) ?
printf("Senior citizen and eligible for booster\n") :
printf("Below 60, and eligible for vaccination\n");
return 0;}
6. Explain the storage classes in‘C’ with suitable examples.
(Nov/Dec2022, Apr/May 2019,2016,2015,2014,2013,2009)
In C, storage classes define a variable's lifetime, scope, and memory location. The four main
storage classes are auto, register, static, and extern. 'auto' variables are local to a function
and are automatically created and destroyed; 'register' variables are stored in CPU registers
for faster access; 'static' variables retain their value throughout program execution and have
local scope; and 'extern' variables are global and can be accessed from other files, allowing
for program-wide visibility.
Here's a breakdown of each storage class:
1. Auto
 Keyword: auto (this is the default for variables declared inside a function or block, so it's
often optional).
 Scope: Local (within the block or function where they are declared).
 Lifetime: Automatic; created when the block/function begins and destroyed when it ends.
 Memory Location: Stack.
 Default Initial Value: Garbage (unpredictable).
Example:
#include <stdio.h>
void myFunction() {
auto int count = 10; // Keyword 'auto' is optional here
printf("Inside myFunction, count is: %d\n", count);}
int main() {
myFunction();
// printf("Outside myFunction, count is: %d\n", count);
// Error: 'count' is not accessible here
return 0;}
In this example, count is only visible and usable within myFunction.
2. Register
 Keyword: register.
 Scope: Local (same as auto variables).
 Lifetime: Automatic (same as auto variables).
 Memory Location: CPU register (if available), otherwise the stack.
 Default Initial Value: Undefined.
 Purpose: To suggest to the compiler to store the variable in a CPU register for faster
access. The compiler is not obligated to honor this request.
Example:
#include <stdio.h>
int main() {
register int counter = 0; // Suggests to store 'counter' in a CPU register
for (counter = 0; counter < 5; counter++) {
printf("Counter: %d\n", counter); }
// Note: Cannot take the address of a register variable using '&'
// printf("Address of counter: %p\n", &counter); // This will cause an error
return 0;}
3. Static
 Keyword: static.
 Scope: Local to the block or function where it is declared.
 Lifetime: Entire duration of the program.
 Memory Location: Data segment.
 Default Initial Value: Zero.
 Purpose: Retains its value between function calls and is initialized only once.
Example:
#include <stdio.h>
void increment Counter() {
static int static Counter = 0; // Initialized only once
static Counter++;
printf("Static counter value: %d\n", staticCounter);
}
int main() {
incrementCounter(); // Output: Static counter value: 1
incrementCounter(); // Output: Static counter value: 2
incrementCounter(); // Output: Static counter value: 3
return 0;}
4. Extern
 Keyword: extern.
 Scope: Global; visible to all functions in all program files.
 Lifetime: Entire duration of the program.
 Memory Location: Global Data Area.
 Default Initial Value: Zero.
 Purpose: Used to declare a variable that is defined in another file or later in the same file,
allowing variables to be shared across different parts of a program.

7. Explain the looping statements in ‘C’ with suitable examples.


(Nov/Dec2022, Apr/May2019, Apr/May 2023)
Looping statements in C programming allow a block of code to be executed repeatedly
as long as a specified condition remains true. C offers three main types of looping
statements: for, while, and do-while.
1. for Loop
The for loop is an entry-controlled loop used when the number of iterations is known
beforehand. It consists of three parts: initialization, condition, and update.
Syntax:
for (initialization; condition; update) {
// code to be executed}
Example: Printing numbers from 1 to 5
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;}
Output: 1 2 3 4 5
2. while Loop
The while loop is an entry-controlled loop that repeatedly executes a block of code as
long as its condition remains true. The loop body may not execute even once if the
condition is initially false.
Syntax:
while (condition) {
// code to be executed}

Example: Printing numbers from 1 to 5


#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++; }
printf("\n");
return 0;}
Output: 1 2 3 4 5
3. do-while Loop
The do-while loop is an exit-controlled loop, meaning the loop body is executed at least
once before the condition is checked. If the condition is true, the loop
continues; otherwise, it terminates.
Syntax:
do {
// code to be executed
} while (condition);
Example: Printing numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
printf("\n");
return 0;}
Output: 1 2 3 4 5

8. Explain various operators used in


C.(Nov/Dec2019,Apr/May2018,2016,2015,2014,2012,2011)
9. Write a C program to check the integer is Palindrome or not.(Apr/May 2018)
#include <stdio.h>
int main() {
int number, reversed_number = 0, original_number, remainder;
printf("Enter an integer: ");
scanf("%d", &number);
original_number = number; // Store the original number for comparison
// Reverse the number
while (number != 0) {
remainder = number % 10; // Get the last digit
reversed_number = reversed_number * 10 + remainder; // Build the reversed
number
number /= 10; // Remove the last digit from the original number
}
// Compare the original and reversed numbers
if (original_number == reversed_number) {
printf("%d is a palindrome number.\n", original_number);
} else {
printf("%d is not a palindrome number.\n", original_number); }
return 0;}
10. Explain different data types in ‘C ’with
examples.(May/Jun2016,Jan2013,May/Jun2010,2009)
11. Explain briefly the formatted and unformatted I/O functions in
C.(May/Jun2016,2012,2010)
12. Explain about the managing input and output operation in ‘C’. With a snippet code,
explain the syntax of scanf(), printf(), gets(), getchar(), and getch(). (Nov/Dec
2016)
13. What are constants? Explain the various types of constants in C. (Apr/May 2015)
14. Write short notes on pre-processor
directives.(May/Jun2016,Nov/Dec2016,Nov/Dec2024)

15. Write the algorithm and C program to print the prime numbers lesser
than500.(Jan2012)
Algorithm:
 Initialize:
Start with a number num from 2 up to 499 (since we need prime numbers less than 500).
 Prime Check Function:
Create a function, isPrime(int n), to determine if a given number n is prime.
a. If n is less than or equal to 1, it is not prime; return false.
b. Iterate from i = 2 up to the square root of n.
c. If n is divisible by i (i.e., n % i == 0), then n is not prime; return false.
d. If the loop completes without finding any divisors, n is prime; return true.
 Main Loop: In the main function, loop through each number num from 2 to 499.
 Print Primes: For each num, call the isPrime(num) function. If it returns true, print num.
C Program:
#include <stdio.h>
#include <stdbool.h> // For using bool data type
#include <math.h> // For using sqrt() function
// Function to check if a number is prime
bool isPrime(int n) {
// 0 and 1 are not prime numbers
if (n <= 1) {
return false; }
// Check for divisibility from 2 up to the square root of n
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false; // Not prime } }
return true; // Prime}
int main() {
printf("Prime numbers less than 500 are:\n");
// Loop through numbers from 2 to 499
for (int i = 2; i < 500; i++) {
if (isPrime(i)) {
printf("%d ", i); } }
printf("\n"); // Print a newline for better formatting
return 0;}

16. Write a C program to find the sum of 10 non-negative numbers entered by the
user.(Apr/May 2019)
#include <stdio.h>
int main() {
int num;
int sum = 0;
int count = 0;
printf("Enter 10 non-negative numbers:\n");
while (count < 10) {
printf("Enter number %d: ", count + 1);
scanf("%d", &num);
if (num >= 0) {
sum += num; // Add to sum only if non-negative
count++; // Increment count only for valid numbers
} else {
printf("Invalid input: Please enter a non-negative number.\n"); } }
printf("The sum of the 10 non-negative numbers is: %d\n", sum);
return 0;}
17. Write a C program to find the largest among 3 numbers entered by the
user.(Apr/May2019)
#include <stdio.h>
int main() {
int num1, num2, num3;
// Prompt the user to enter three numbers
printf("Enter three integers: ");
// Read the three numbers from the user
scanf("%d %d %d", &num1, &num2, &num3);
// Use if-else if-else to compare and find the largest
if (num1 >= num2 && num1 >= num3) {
printf("The largest number is: %d\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("The largest number is: %d\n", num2);
} else {
printf("The largest number is: %d\n", num3);
} return 0;}

18. Write a C program to find roots of a quadratic equation. (Apr/May2015,2014)


#include <stdio.h>
#include <math.h> // Required for sqrt() function
int main() {
float a, b, c; // Coefficients of the quadratic equation
float discriminant, root1, root2, realPart, imagPart;
// Prompt user for input
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
// Determine the nature of the roots based on the discriminant
if (discriminant > 0) {
// Real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct:\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
} else if (discriminant == 0) {
// Real and equal roots
root1 = root2 = -b / (2 * a);
printf("Roots are real and equal:\n");
printf("Root 1 = Root 2 = %.2f\n", root1);
} else {
// Complex roots
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and conjugate:\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imagPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imagPart);
}
return 0;}
19. Write a C program to find sum of digits of an integer.(May/Jun2014)
#include <stdio.h>

int main() {
int number, sum = 0, digit;
// Prompt the user to enter a number
printf("Enter an integer: ");
scanf("%d", &number);
// Loop to extract digits and calculate their sum
// The loop continues as long as the number is not zero
while (number != 0) {
// Extract the last digit using the modulo operator
digit = number % 10;
// Add the extracted digit to the sum
sum += digit;
// Remove the last digit from the number using integer division
number /= 10; }
// Print the sum of the digits
printf("Sum of digits: %d\n", sum);
return 0;}
20. Write a C program that reads a character and displays only the vowels using
switch case structure.(May/Jun2013).
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf(" %c", &ch);
// Added a space before %c to consume any leftover newline character
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
printf("%c is a vowel.\n", ch);
break; // Exit the switch statement after a match
default:
// If the character is not a vowel, no output is produced as per the
requirement
break; }
return 0;}
21. Write a C program that displays a pyramid structure using
numbers.(May/Jun2012)
#include <stdio.h>
int main() {
int rows, i, j, space;
printf("Enter the number of rows for the pyramid: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) { // Outer loop for rows
// Loop to print leading spaces
for (space = 1; space <= rows - i; space++) {
printf(" "); // Two spaces for alignment }
// Loop to print numbers in ascending order
for (j = i; j >= 1; j--) {
printf("%d ", j); }
// Loop to print numbers in descending order (excluding the center number)
for (j = 2; j <= i; j++) {
printf("%d ", j); }
printf("\n"); // Move to the next line after each row }
return 0;}
22. Write a C program to simulate simple calculator using switch case.
#include <stdio.h>
#include <float.h> // For DBL_MAX
int main() {
char op;
double num1, num2, result;
// Get the operator from the user
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);

// Get the two numbers from the user


printf("Enter two operands: ");
scanf("%lf %lf", &num1, &num2);
// Perform the calculation based on the operator
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("Error! Incorrect operator.\n");
// Set a flag or special value to indicate an error
result = -DBL_MAX; }
// Display the result if no error occurred
if (result != -DBL_MAX) {
printf("%.2lf %c %.2lf = %.2lf\n", num1, op, num2, result);
}
return 0;}
23. Explain the terms variable and constant. How many type of variables are supported
by C(Apr/May2024)
24. What is purpose of Decision control statement in C? Explain any two of such
types with general form simple statements (Apr/May2024)
Decision control statements in C are used to control the flow of program execution by
allowing the program to make choices and execute different blocks of code based on
specific conditions. The two main types are the if statement, which executes a block of code
only when a condition is true, and the if-else statement, which executes one block if the
condition is true and another if it is false.
Purpose of Decision Control Statements
 Dynamic Program Behavior:
They enable programs to react to varying inputs and situations, making them more
dynamic and responsive.
 Conditional Execution:
They allow specific parts of a program to be executed only when certain conditions are
met, providing logical branching.
 Flexibility and Adaptability:
By choosing different execution paths, programmers can create software that adapts to
different scenarios and complex decision-based logic.
Types of Decision Control Statements
1. if Statement:
o Purpose: Executes a block of code if a given condition is true.
o General Form:
if (condition) {
// Statements to execute if the condition is true
}
 Explanation: The program checks the condition within the parentheses. If the condition
evaluates to true, the statements inside the curly braces are executed. If the condition is
false, the block is skipped.
1. if-else Statement:
o Purpose: Executes one block of code if the condition is true and another block if it is false.
o General Form:
if (condition) {
// Statements to execute if the condition is true
} else {
// Statements to execute if the condition is false
}
 Explanation: If the condition is true, the code in the if blocks runs. If the condition is false,
the code in the else block is executed. This provides two alternative paths for the program to
follow.

25. What are the functionalities of pre-processor and compiler? With


example(Apr/May2024)
26. Write a C program to check whether the person is eligible for voting using
if/else.(Nov/Dec2024)
#include <stdio.h>
int main() {
int age;
// Prompt the user to enter their age
printf("Enter your age: ");
// Read the age entered by the user
scanf("%d", &age);
// Check voting eligibility using an if/else statement
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n"); }
return 0;}
27. Write a C program to print the grade of student using switch
statement.(Nov/Dec2024)
#include <stdio.h>
int main() {
int marks;
// Prompt the user to enter marks
printf("Enter the student's marks (0-100): ");
scanf("%d", &marks);
// Determine the grade based on marks using a switch statement
// We divide marks by 10 to get a single digit for the switch expression
// This groups marks into ranges (e.g., 9 for 90-99, 8 for 80-89, etc.)
switch (marks / 10) {
case 10: // Marks 100
case 9: // Marks 90-99
printf("Grade: A\n");
break;
case 8: // Marks 80-89
printf("Grade: B\n");
break;
case 7: // Marks 70-79
printf("Grade: C\n");
break;
case 6: // Marks 60-69
printf("Grade: D\n");
break;
default: // Marks below 60
printf("Grade: F\n");
break; }
return 0;}
28. Difference between Algorithms, Flowchart and Pseudo code.
29. Discuss about build-in Function in C.

Built-in functions in C, also known as standard library functions or predefined functions, are
functions that are already provided as part of the C standard library. These functions are
readily available for use in C programs without the need for a programmer to write their
implementation. They are designed to perform common and essential tasks, covering a wide
range of functionalities.
Key characteristics of built-in functions in C:
 Pre-defined:
Their implementation is already written and compiled into the C standard library.
 Accessible via header files:
To use a built-in function, the appropriate header file
(e.g., <stdio.h>, <string.h>, <math.h>) must be included in the C program. This inclusion
provides the function's declaration, allowing the compiler to verify its correct usage.
 Wide range of functionalities:
Built-in functions cover various categories, including:
 Input/Output: printf(), scanf(), getchar(), putchar()
 String Manipulation: strcpy(), strlen(), strcmp(), strcat()
 Mathematical Operations: sqrt(), pow(), sin(), cos()
 Memory Management: malloc(), calloc(), free()
 Utility Functions: abs(), rand(), exit()
Benefits of using built-in functions:
 Efficiency and Productivity:
They save development time and effort as programmers don't need to implement common
functionalities from scratch.
 Reliability:
They are well-tested and optimized, ensuring robust and efficient performance.
 Code Readability and Maintainability:
Using standard functions makes code more understandable and easier to maintain for other
developers.
 Portability:
Standard library functions are generally portable across different C compilers and
operating systems.
Example of using a built-in function:
#include <stdio.h> // For printf() and scanf()
#include <string.h> // For strlen()
int main() {
char name[20];
printf("Enter your name: ");
scanf("%s", name);
int length = strlen(name); // Using the built-in strlen() function
printf("Hello, %s! Your name has %d characters.\n", name, length);
return 0;}
30. Explain briefly interactive mode and script mode with examples.
31. Explain Problem Analysis chart with example?

You might also like