QB ans (1)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 50

1. What is a token?

List and discuss the different types of tokens


available in C programming.

Definition:

A token is the smallest element of a C program that is meaningful to the


compiler.

Types of Tokens:

1. Keywords: Reserved words predefined by the language (e.g., int,


return).
2. Identifiers: Names used for variables, functions, arrays, etc.
3. Constants: Fixed values like 10, 3.14, 'A'.
4. Strings: Sequence of characters enclosed in double quotes (e.g.,
"Hello").
5. Operators: Symbols used for computations (e.g., +, -, *).
6. Special Characters: Symbols like {, }, [, ], ;, etc.

2. Write an algorithm and flowchart to print the multiplication of


two numbers.

Algorithm:

1. Start.
2. Input two numbers, num1 and num2.
3. Multiply num1 and num2, store the result in product.
4. Display product.
5. End.

Flowchart:

I can create a flowchart diagram if required.


3. What is an operator? List and explain various types of operators
with examples.

Definition:

An operator is a symbol that tells the compiler to perform specific


mathematical or logical operations.

Types:

1. Arithmetic Operators: +, -, *, /, %
Example: int sum = a + b;
2. Relational Operators: ==, !=, <, >, <=, >=
Example: if (a > b)
3. Logical Operators: &&, ||, !
Example: if (a > 0 && b < 10)
4. Bitwise Operators: &, |, ^, ~, <<, >>
Example: a = b & c;
5. Assignment Operators: =, +=, -=, *=, /=, %=
Example: a += 5;
6. Increment/Decrement Operators: ++, --
Example: a++;
7. Conditional (Ternary) Operator: ? :
Example: a = (b > c) ? b : c;

4. Write a program to compute the addition, subtraction, product,


quotient, and remainder of two given numbers using functions.

c
Copy code
#include <stdio.h>

int add(int a, int b) { return a + b; }


int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return a / b; }
int remainder(int a, int b) { return a % b; }

int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

printf("Addition: %d\n", add(num1, num2));


printf("Subtraction: %d\n", subtract(num1, num2));
printf("Multiplication: %d\n", multiply(num1, num2));
printf("Division: %d\n", divide(num1, num2));
printf("Remainder: %d\n", remainder(num1, num2));

return 0;
}

5. Write a program to print the day when the user enters the day
number using a switch-case.

#include <stdio.h>

int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);

switch (day) {
case 1: printf("Sunday\n"); break;
case 2: printf("Monday\n"); break;
case 3: printf("Tuesday\n"); break;
case 4: printf("Wednesday\n"); break;
case 5: printf("Thursday\n"); break;
case 6: printf("Friday\n"); break;
case 7: printf("Saturday\n"); break;
default: printf("Invalid day number!\n");
}

return 0;
}

6. Write a program to print employee ID and employee name using a


structure.
#include <stdio.h>

struct Employee {
int id;
char name[50];
};

int main() {
struct Employee emp;

printf("Enter Employee ID: ");


scanf("%d", &emp.id);
printf("Enter Employee Name: ");
scanf("%s", emp.name);

printf("\nEmployee Details:\n");
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);

return 0;
}
7. Write a program to print the Fibonacci series up to a given number.
#include <stdio.h>
int main() {
int n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");


for (int i = 1; i <= n; ++i) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}

return 0;
}

8. Write a C program to find the even numbers from 1 to 10 using a


for loop.
#include <stdio.h>

int main() {
printf("Even numbers from 1 to 10:\n");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
printf("%d ", i);
}
}
return 0;
}

9. Draw the block diagram of a computer system and discuss each


part.
A block diagram typically includes the following components:

1. Input Unit: Devices like keyboard, mouse, etc., for user input.
2. Central Processing Unit (CPU):
o Control Unit (CU): Manages operations and instructions.
o Arithmetic Logic Unit (ALU): Performs mathematical and
logical operations.
o Registers: Temporary storage within the CPU.
3. Memory Unit:
o Primary Memory: RAM, ROM for storing data.
o Secondary Memory: Hard drives, SSDs, etc., for long-term
storage.
4. Output Unit: Devices like monitors and printers for displaying
results.

10. What is the CPU? Discuss its components.

Definition:

The CPU (Central Processing Unit) is the brain of the computer,


executing instructions to perform tasks.

Components:

1. Control Unit (CU): Directs the operations of the processor,


including fetching, decoding, and executing instructions.
2. Arithmetic Logic Unit (ALU): Performs arithmetic and logical
operations.
3. Registers: Small, fast storage locations for temporary data.
4. Cache: High-speed memory for frequently used data.

11. Define the terms compiler, interpreter, and assembler.

1. Compiler:
o Converts the entire source code into machine code before
execution.
o Example: GCC (GNU Compiler Collection).
2. Interpreter:
o Translates and executes the source code line by line.
o Example: Python Interpreter.
3. Assembler:
o Converts assembly language code into machine code.
o Example: NASM (Netwide Assembler).

12. Define the three levels of computer languages.

1. Machine Language:
o Low-level language written in binary (0s and 1s).
o Directly understood by computers but difficult for humans to
write.
2. Assembly Language:
o Low-level language using symbolic instructions (e.g., ADD,
MOV).
o Requires an assembler to convert it to machine code.
3. High-Level Language:
o User-friendly and closer to human language (e.g., C, Java).
o Requires a compiler or interpreter to translate it into machine
code.

13.Difference between a flowchart and an algorithm.

Aspect Algorithm Flowchart


Step-by-step procedure to Diagrammatic representation
Definition
solve a problem. of an algorithm.
Written in plain text using Visual with symbols like ovals
Format
structured steps. and rectangles.
Easier for detailed Easier to visualize and
Readability
understanding. understand at a glance.
Aspect Algorithm Flowchart
Used for detailed and
Used for quick representation
Usage complex problems.
and analysis.

14. What is a flowchart? List and discuss the different types of


symbols used in the flowchart.

Definition:

A flowchart is a graphical representation of a process, showing the steps


in sequential order.

Symbols:

1. Oval: Represents the start or end of a process.


2. Rectangle: Represents a process or operation.
3. Diamond: Represents a decision point (e.g., if-else).
4. Arrow: Indicates the flow of control or data.
5. Parallelogram: Represents input/output operations.

15. Write an algorithm and flowchart to find if a number is even or


odd.

Algorithm:

1. Start.
2. Input a number, num.
3. Check if num % 2 == 0.
o If true, print "Even".
o Otherwise, print "Odd".
4. End.

Flowchart:

+----------------------+
| Start |

+----------------------+

+----------------------+

| Input num |

+----------------------+

+----------------------+

| num % 2 == 0? |

+----------------------+

/ \

/ \

Yes / \ No

/ \

v v

+---------------+ +----------------+

| Print "Even" | | Print "Odd" |

+---------------+ +----------------+
\ /

\ /

v v

+----------------------+

| End |

16. Write an algorithm to print the table of number 2.

Algorithm:

1. Start.
2. Initialize num = 2.
3. For i from 1 to 10:
o Compute result = num * i.
o Print result.
4. End.

17. Write an algorithm and flowchart to print numbers from 1 to 15.

Algorithm:

1. Start.
2. For i = 1 to 15:
o Print i.
3. End.

18. What is a header file? Why do we use preprocessor directives?

1. Header File:
o A file containing function declarations, macros, and
definitions used in a program.
Example: <stdio.h> provides input/output functions like
o
printf and scanf.
2. Preprocessor Directives:
o Special instructions processed before the compilation of the
program.
o Examples: #include (to include header files), #define (for
macros).

Purpose: To manage code modularity, reuse, and configuration.

19. What are primary data types? List all the primary data types.

Definition:

Primary data types are the fundamental data types provided by C for
storing basic values.

Types:

1. Integer: int (e.g., 1, 45).


2. Floating Point: float (e.g., 3.14).
3. Character: char (e.g., 'A').
4. Double: double (e.g., 3.14159).

20. What are secondary data types? List all.

Definition:

Secondary data types are derived or constructed using primary data


types.

Types:

1. Array: Collection of elements of the same type.


2. Pointer: Stores the address of a variable.
3. Structure: Groups different types of variables under one name.
4. Union: Stores different types of variables in the same memory
location.

21. Write a short note on user-defined data types.

Definition:

User-defined data types allow programmers to create new data types that
model real-world entities.

Examples:

1. Structure (struct):
Groups variables of different types under one name.
Example:

struct Student {

int id;

char name[50];

};

2.Union (union):
Similar to structures but shares the same memory for all members.
Example:
union Data {
int i;
float f;
};

3.Enumeration (enum):
Used to define constants.
Example:
enum Days { MON, TUE, WED };

22. What is a token? List all the tokens.

Definition:

A token is the smallest individual unit of a C program.

Types:

1. Keywords: Reserved words (e.g., int, return).


2. Identifiers: Names for variables, functions, etc.
3. Constants: Fixed values (e.g., 5, 3.14).
4. Operators: Symbols for operations (e.g., +, -).
5. Strings: Text enclosed in double quotes (e.g., "hello").
6. Special Characters: {, }, ;, etc.

23. Discuss the following terms with suitable examples.

a. Reserved Word:

Keywords predefined in the C language and cannot be used as


identifiers.
Example: int, return.

b. Literals or Constants:

Values that do not change during program execution.


Example: 5, 'A', "Hello".

c. Operators:

Symbols that perform specific operations.


Example: Arithmetic (+, -), Logical (&&), etc.
d. Identifier:

The name used to identify variables, functions, arrays, etc.


Example:

int age;
float salary;

24. What is an operator? List all the different operators used in C


programming.

Definition:

An operator is a symbol that performs an operation on operands.

Types of Operators:

1. Arithmetic: +, -, *, /, %.
2. Relational: ==, !=, <, >, <=, >=.
3. Logical: &&, ||, !.
4. Bitwise: &, |, ^, ~, <<, >>.
5. Assignment: =, +=, -=, *=, /=.
6. Increment/Decrement: ++, --.
7. Ternary: ? :.
8. Special: sizeof, &, *.

25. What is the increment and decrement operator? List their types.

Definition:

These operators are used to increase or decrease the value of a variable


by 1.

Types:
1. Pre-Increment/Decrement:
o Increments/decrements before using the variable.
Example:

int a = 5;

int b = ++a; // a = 6, b = 6

2.Post-Increment/Decrement:

 Increments/decrements after using the variable.


Example:

int a = 5;

int b = a++; // a = 6, b = 5

26. Discuss the pre- and post-increment/decrement operators with


suitable examples.

Pre-Increment (++var):

Increments the value before using it in the expression.


Example:

int x = 5;
int y = ++x; // x = 6, y = 6

Post-Increment (var++):

Increments the value after using it in the expression.


Example:

int x = 5;
int y = x++; // x = 6, y = 5
Pre-Decrement (--var):

Decrements the value before using it in the expression.


Example:

int x = 5;
int y = --x; // x = 4, y = 4

Post-Decrement (var--):

Decrements the value after using it in the expression.


Example:

int x = 5;
int y = x--; // x = 4, y = 5

27. What are gets and puts? Define with suitable examples.

Definition:

1. gets: Reads a string input from the user, including spaces.


2. puts: Outputs a string to the console.

Example:

#include <stdio.h>

int main() {
char name[50];

printf("Enter your name: ");


gets(name); // Reads input with spaces.
puts("Your name is:");
puts(name); // Prints the name.
return 0;

28. What is a loop? List the different types of loops used in C


programming.

Definition:

A loop is a control structure that allows a block of code to be executed


repeatedly based on a condition.

Types of Loops:

1. For Loop:
Executes a block of code a specific number of times.
Example:

for (int i = 0; i < 5; i++) {


printf("%d ", i);
}

2. While Loop:
Executes a block of code as long as a condition is true.
Example:

int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}

3. Do-While Loop:
Similar to a while loop but executes the code at least once.
Example:
int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);

29. What is the if statement? Write its syntax.

Definition:

The if statement allows conditional execution of code.

Syntax:

if (condition) {
// Code to execute if condition is true
}

Example:

int a = 10;
if (a > 5) {
printf("a is greater than 5");
}

30. What is the for loop? Write its syntax and give one example.

Definition:

A for loop is a control structure for iterating a fixed number of times.

Syntax:

for (initialization; condition; increment/decrement) {


// Code to execute
}

Example:

for (int i = 1; i <= 10; i++) {


printf("%d ", i);
}

31. What is the difference between the while loop and the do-while
loop? Explain with a suitable example.

Aspect While Loop Do-While Loop


Condition is checked Executes at least once before
Execution
before execution. checking the condition.
Example Below: Below:

Example:

While Loop:

int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}

Do-While Loop:

int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);

32. What is the if-else statement? Write its syntax. Write a C


program to find whether a given number is even or odd using the if-
else statement.

Syntax:

if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Program:

#include <stdio.h>

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}

return 0;
}

33. What is the switch-case statement? Write its syntax. Write a


program to print the day when the user enters the day number.
Syntax:

switch (expression) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
default:
// Code to execute if no cases match
}

Program:

#include <stdio.h>

int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);

switch (day) {
case 1: printf("Sunday\n"); break;
case 2: printf("Monday\n"); break;
case 3: printf("Tuesday\n"); break;
case 4: printf("Wednesday\n"); break;
case 5: printf("Thursday\n"); break;
case 6: printf("Friday\n"); break;
case 7: printf("Saturday\n"); break;
default: printf("Invalid day number!\n");
}

return 0;
}
34. What is the conditional operator? Write its syntax and
flowchart.

Definition:

A conditional operator (?:) is a shorthand for if-else.

Syntax:

condition ? expression1 : expression2;

Example:

int a = 5, b = 10, max;


max = (a > b) ? a : b; // max will hold the larger value

Flowchart:

A flowchart for the conditional operator would resemble a decision-


making diamond for if-else.

35. Write a C program to find the maximum of two numbers using


the conditional operator.

#include <stdio.h>

int main() {
int num1, num2, max;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

max = (num1 > num2) ? num1 : num2;


printf("The maximum number is: %d\n", max);

return 0;
}

36. Write a program to print the multiplication table using both for
and while loops.

Using for Loop:

#include <stdio.h>

int main() {
int num;
printf("Enter a number for the multiplication table: ");
scanf("%d", &num);

printf("Multiplication Table for %d:\n", num);


for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}

return 0;
}

Using while Loop:

#include <stdio.h>

int main() {
int num, i = 1;
printf("Enter a number for the multiplication table: ");
scanf("%d", &num);

printf("Multiplication Table for %d:\n", num);


while (i <= 10) {
printf("%d x %d = %d\n", num, i, num * i);
i++;
}

return 0;
}

37. What is a prime number? Write a program to check if a number


is prime.

Definition:

A prime number is a number greater than 1 that has only two divisors: 1
and itself. Examples include 2, 3, 5, 7, 11.

Program:

#include <stdio.h>

int main() {
int num, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &num);

if (num <= 1) {
printf("%d is not a prime number.\n", num);
return 0;
}

for (int i = 2; i <= num / 2; i++) {


if (num % i == 0) {
isPrime = 0;
break;
}
}

if (isPrime) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}

return 0;
}

38. What is an array? How to declare it? Write its syntax and give
one example.

Definition:

An array is a collection of elements of the same data type stored in


contiguous memory locations.

Syntax:

data_type array_name[size];

Example:

int numbers[5]; // Declares an array to store 5 integers

39. How to initialize an integer array and how to access its elements?
Explain with an example.

Initialization:

int numbers[5] = {1, 2, 3, 4, 5};

Accessing Elements:

Elements are accessed using the index, starting from 0.


Example:
#include <stdio.h>

int main() {
int numbers[5] = {1, 2, 3, 4, 5};
printf("First Element: %d\n", numbers[0]);
printf("Last Element: %d\n", numbers[4]);
return 0;
}

40. Write a program to read five elements into an integer array and
print them with and without using a loop.

Program:

#include <stdio.h>

int main() {
int numbers[5];

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

printf("Numbers using a loop:\n");


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

printf("\nNumbers without a loop:\n");


printf("%d %d %d %d %d\n", numbers[0], numbers[1], numbers[2],
numbers[3], numbers[4]);

return 0;
}
41. What is an integer array? Write a program to count the number
of positive and negative numbers from an array of 10 numbers.

Definition:

An integer array is a collection of integer values stored in contiguous


memory.

Program:

#include <stdio.h>

int main() {
int numbers[10], positive = 0, negative = 0;

printf("Enter 10 numbers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &numbers[i]);
if (numbers[i] > 0) {
positive++;
} else if (numbers[i] < 0) {
negative++;
}
}

printf("Number of positive numbers: %d\n", positive);


printf("Number of negative numbers: %d\n", negative);

return 0;
}
42. Develop a program to read n numbers in an array and print
them in reverse order.

Program:

#include <stdio.h>

int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);

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

printf("Numbers in reverse order:\n");


for (int i = n - 1; i >= 0; i--) {
printf("%d ", numbers[i]);
}

return 0;
}

43. What is a multidimensional array? Write its syntax and a


program to enter elements in a 3x3 matrix and print them.

Definition:

A multidimensional array is an array of arrays, allowing storage of data


in a table-like format.
Syntax:

data_type array_name[rows][columns];

Program:

#include <stdio.h>

int main() {
int matrix[3][3];

printf("Enter elements for a 3x3 matrix:\n");


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

printf("Matrix elements are:\n");


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

return 0;
}

44. Explain the following string functions with examples.

a. strcat(s1, s2):

Concatenates s2 to the end of s1.


#include <string.h>
#include <stdio.h>
int main() {
char s1[20] = "Hello, ";
char s2[] = "World!";
strcat(s1, s2);
printf("Concatenated string: %s\n", s1);
return 0;
}

b. strstr(s1, s2):

Finds the first occurrence of s2 in s1.

#include <string.h>
#include <stdio.h>
int main() {
char s1[] = "Hello, World!";
char *result = strstr(s1, "World");
printf("Substring found: %s\n", result);
return 0;
}

c. strrev(s1):

Reverses a string. (Not standard in some compilers.)

#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Hello";
strrev(s1); // May need custom implementation if unavailable
printf("Reversed string: %s\n", s1);
return 0;
}

d. strupr(s1):

Converts string to uppercase.

#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "hello";
strupr(s1); // May need custom implementation if unavailable
printf("Uppercase string: %s\n", s1);
return 0;
}

45. What is gets and puts? Write a program to read and print
characters using gets and puts.

Program:

#include <stdio.h>

int main() {
char str[100];

printf("Enter a string: ");


gets(str); // Reads input with spaces

printf("You entered: ");


puts(str); // Prints the string

return 0;
}
46. List and discuss the different types of looping statements with
suitable examples.

1. For Loop:
o Executes a block of code a specific number of times.
o Example:

for (int i = 1; i <= 5; i++) {


printf("%d ", i);
}

2. While Loop:
o Executes a block of code as long as a condition is true.
o Example:

int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}

3. Do-While Loop:
o Executes the block at least once, then checks the condition.
o Example:

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);

47. Write a C program to find the even numbers from 1 to 10 using


a for loop.

Program:
#include <stdio.h>

int main() {
printf("Even numbers from 1 to 10:\n");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
printf("%d ", i);
}
}
return 0;
}

48. What is an array? Explain the declaration and initialization of


one-dimensional and two-dimensional arrays with examples.

One-Dimensional Array:

 Declaration: int arr[5];


 Initialization: int arr[5] = {1, 2, 3, 4, 5};

Two-Dimensional Array:

 Declaration: int matrix[2][3];


 Initialization:

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

49. Define string. How is a string declared and initialized? Explain


string input/output functions with an example.

Definition:
A string is a sequence of characters terminated by a null character \0.

Declaration and Initialization:

char str[20] = "Hello, World!";

Input/Output Example:

#include <stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
gets(str); // Input
printf("You entered: ");
puts(str); // Output
return 0;
}

50. Write a C program to check if a given string is a palindrome.

Program:

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

int main() {
char str[100], reversed[100];
printf("Enter a string: ");
scanf("%s", str);

strcpy(reversed, str);
strrev(reversed);

if (strcmp(str, reversed) == 0) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}

return 0;
}

51. What is a function? Explain the difference between user-defined


and library functions.

Definition:

A function is a block of code designed to perform a specific task.


Functions improve code modularity and reusability.

Differences:

User-Defined
Aspect Library Functions
Functions
Written by the Predefined in
Definition
programmer. libraries.
printf(), scanf(),
Examples void display()
strlen().
For custom logic or Commonly used
Purpose
tasks. operations.
Code Defined within the Stored in header
Location program. files.

52. What is recursion? Write a C program to find the factorial of a


number using recursion.

Definition:
Recursion is a process in which a function calls itself directly or
indirectly.

Program:

#include <stdio.h>

int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

printf("Factorial of %d is %d\n", num, factorial(num));


return 0;
}

53. What is a structure? Write its syntax.

Definition:

A structure is a user-defined data type that groups variables of different


types under one name.

Syntax:

struct StructureName {
data_type member1;
data_type member2;
// More members...
};

54. Write a C program to read and display student information


using a structure.

Program:

#include <stdio.h>

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

int main() {
struct Student s;

printf("Enter Student ID: ");


scanf("%d", &s.id);
printf("Enter Student Name: ");
scanf("%s", s.name);
printf("Enter Student Marks: ");
scanf("%f", &s.marks);

printf("\nStudent Information:\n");
printf("ID: %d\n", s.id);
printf("Name: %s\n", s.name);
printf("Marks: %.2f\n", s.marks);

return 0;
}
55. What is a pointer? Explain how pointer variables are declared
and initialized.

Definition:

A pointer is a variable that stores the memory address of another


variable.

Declaration and Initialization:

int *ptr; // Declares a pointer to an integer


int a = 10;
ptr = &a; // Initializes the pointer with the address of `a`

56. Write a C program to find the sum of two numbers using a


pointer to a function.

Program:

#include <stdio.h>

int sum(int a, int b) {


return a + b;
}

int main() {
int (*ptr)(int, int); // Pointer to a function
ptr = sum;

int num1, num2;


printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

printf("Sum is: %d\n", ptr(num1, num2)); // Calling function using


pointer
return 0;
}

57. What is a file system? Write the different types of modes


available to open a file.

Definition:

A file system in C enables handling data stored in files (e.g., reading,


writing, appending).

File Opening Modes:

1. r: Opens a file for reading.


2. w: Opens a file for writing; creates or overwrites.
3. a: Opens a file for appending.
4. r+: Opens a file for reading and writing.
5. w+: Opens a file for reading and writing; creates or overwrites.
6. a+: Opens a file for reading and appending.

58. Write a C program to display the content of a given file.

Program:

#include <stdio.h>

int main() {
FILE *file;
char ch;

file = fopen("example.txt", "r");


if (file == NULL) {
printf("Error: Cannot open file.\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}

fclose(file);
return 0;
}

59. What are file positioning functions? List and explain their types
with examples

Definition:

File positioning functions allow navigating a file's content.

Types:

1. fseek(FILE *stream, long offset, int whence): Sets the file


position.
Example:

fseek(file, 0, SEEK_END); // Moves to the end of the file

2. ftell(FILE *stream): Returns the current file position.


Example:

long pos = ftell(file); // Gets current position

3. rewind(FILE *stream): Resets the position to the beginning of


the file.
Example:

rewind(file);
60. Write a C program that counts the number of lines, words, tabs,
and characters in a file.

Program:

#include <stdio.h>
#include <ctype.h>

int main() {
FILE *file;
char ch;
int lines = 0, words = 0, tabs = 0, chars = 0;

file = fopen("example.txt", "r");


if (file == NULL) {
printf("Error: Cannot open file.\n");
return 1;
}

while ((ch = fgetc(file)) != EOF) {


chars++;
if (ch == '\n') lines++;
if (ch == '\t') tabs++;
if (isspace(ch)) words++;
}

fclose(file);

printf("Lines: %d\nWords: %d\nTabs: %d\nCharacters: %d\n", lines,


words, tabs, chars);
return 0;
}

61. Explain the general structure of a C program with an example.


General Structure:

1. Preprocessor Directives: Includes header files using #include.


2. Global Declarations: Global variables and constants.
3. Main Function: Execution begins here.
4. Functions: User-defined or library functions.

Example:

#include <stdio.h> // Preprocessor directive

int globalVar = 10; // Global declaration

void display() { // Function definition


printf("This is a function.\n");
}

int main() { // Main function


printf("Hello, World!\n");
display();
return 0;
}

62. Define: Variable, Constant, Associativity, Precedence.

1. Variable:
A named storage location that holds a value.
Example: int x = 5;
2. Constant:
A value that does not change during program execution.
Example: const int PI = 3.14;
3. Associativity:
Determines the direction of evaluation for operators with the same
precedence.
Example: a + b - c evaluates left-to-right.
4. Precedence:
Defines the order in which operators are evaluated.
Example: * has higher precedence than +.

63. List all conditional control statements used in C.

1. if Statement
2. if-else Statement
3. else-if Ladder
4. switch-case Statement
5. Conditional (Ternary) Operator

Differences Between while and do-while Loops:

Refer to question 31 for details.

C Program to Find the Sum of Natural Numbers from 1 to N Using


for Loop:

#include <stdio.h>

int main() {
int n, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);

for (int i = 1; i <= n; i++) {


sum += i;
}

printf("Sum of natural numbers: %d\n", sum);


return 0;
}
64. What is an array? Explain one-dimensional and two-
dimensional arrays with examples.

Definition:

An array is a collection of elements of the same data type.

One-Dimensional Array Example:

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


printf("First Element: %d", arr[0]);

Two-Dimensional Array Example:

int matrix[2][2] = {{1, 2}, {3, 4}};


printf("Matrix Element: %d", matrix[0][1]);

65. Define string. How is it declared and initialized? Explain string


input/output functions.

Definition:

A string is a sequence of characters terminated by a null character (\0).

Declaration and Initialization:

char str[10] = "Hello";

Input/Output Functions:

 gets(): Reads a string with spaces.


 puts(): Prints a string.

66. Write a C program to count the frequency of vowels and


consonants in a string.
Program:

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

int main() {
char str[100];
int vowels = 0, consonants = 0;

printf("Enter a string: ");


gets(str);

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


char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else if ((ch >= 'a' && ch <= 'z')) {
consonants++;
}
}

printf("Vowels: %d, Consonants: %d\n", vowels, consonants);


return 0;
}

67. What is a function? Explain the difference between user-defined


and library functions.

Refer to 51 for details.

68. What is recursion? Write a C program to find the factorial of a


number using recursion.

Refer to 52 for details.


69. What is a structure? Explain the syntax of structure declaration
with an example.

Refer to 53 for the syntax.

Example:

struct Student {
int id;
char name[50];
float marks;
};
70. Explain the difference between arrays and structures.

Aspect Array Structure


Data Holds elements of the same Holds variables of different
Type type. types.
Continuous memory for all Separate memory for each
Memory
elements. member.
Accessed using member
Access Accessed using indices.
names.

71. What is a pointer? Explain how pointer variables are declared


and initialized.

Refer to 55 for details.

72. Write a C program to swap two numbers using pointers (call by


address method).

Program:

#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);

printf("Before swap: x = %d, y = %d\n", x, y);


swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);

return 0;
}

73. Write the syntax for opening a file with various modes and
closing a file.

Syntax:

FILE *file;
file = fopen("filename", "mode");
fclose(file);

Modes:

 r (read), w (write), a (append), r+ (read/write), w+ (read/write,


overwrite), a+ (read/append).

74. Discuss command line arguments in detail with examples.

Definition:

Command-line arguments allow the user to pass inputs to a program


during execution.

Example:
#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Program Name: %s\n", argv[0]);
if (argc > 1) {
printf("Argument: %s\n", argv[1]);
} else {
printf("No arguments passed.\n");
}
return 0;
}

75. Write a C program to read a file name and display its contents
on the screen.

Program:

#include <stdio.h>

int main() {
FILE *file;
char filename[100], ch;

printf("Enter the file name: ");


scanf("%s", filename);

file = fopen(filename, "r");


if (file == NULL) {
printf("Cannot open file.\n");
return 1;
}

while ((ch = fgetc(file)) != EOF) {


putchar(ch);
}
fclose(file);
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy