0% found this document useful (0 votes)
17 views29 pages

Fop Long Q Ans

The document provides a comprehensive guide on C programming, covering topics such as the structure of a C program, evolution and importance of C, algorithms, flowcharts, tokens, keywords, identifiers, data types, comments, applications, operators, preprocessor directives, storage classes, decision-making statements, looping statements, arrays, searching and sorting techniques, and functions. Each section includes definitions, examples, and explanations of concepts, making it a valuable resource for understanding C programming fundamentals. The guide emphasizes the significance of C in system programming and its influence on modern programming languages.

Uploaded by

b24154866
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)
17 views29 pages

Fop Long Q Ans

The document provides a comprehensive guide on C programming, covering topics such as the structure of a C program, evolution and importance of C, algorithms, flowcharts, tokens, keywords, identifiers, data types, comments, applications, operators, preprocessor directives, storage classes, decision-making statements, looping statements, arrays, searching and sorting techniques, and functions. Each section includes definitions, examples, and explanations of concepts, making it a valuable resource for understanding C programming fundamentals. The guide emphasizes the significance of C in system programming and its influence on modern programming languages.

Uploaded by

b24154866
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

Answer Guide (Q.1 – Q.

5)
Q1. Explain the structure of a C program with a suitable example.

• Structure of a C program:
1. Documentation Section → Comments about program purpose.
2. Preprocessor Section → #include directives.
3. Global Declaration Section → Global variables, function prototypes.
4. Main Function Section → int main() where execution begins.
5. Subprogram Section → User-defined functions.
• Example:

#include <stdio.h> // Preprocessor section

// Global declaration
int sum(int, int);

int main() {
int a = 5, b = 10;
printf("Sum = %d", sum(a, b));
return 0;
}

// Function definition
int sum(int x, int y) {
return x + y;
}

Q2. Describe the evolution and importance of C programming language.

• Evolution:
o Developed by Dennis Ritchie at Bell Labs (1972).
o Derived from B language and BCPL.
o Became the foundation for UNIX OS.
o Influenced later languages: C++, Java, C#, Python.
• Importance:
o Portable and efficient.
o Close to hardware (system programming).
o Basis for operating systems, compilers, embedded systems.
o Still widely used in competitive programming and industry.

Q3. Explain the concept of algorithm and flowchart in program development.

• Algorithm:
o Step-by-step procedure to solve a problem.
o Written in simple English or pseudocode.
o Example: Algorithm to add two numbers:
1. Start
2. Input A, B
3. Compute SUM = A + B
4. Output SUM
5. Stop
• Flowchart:
o Graphical representation of algorithm using symbols:
▪ Oval → Start/Stop
▪ Parallelogram → Input/Output
▪ Rectangle → Process
▪ Diamond → Decision

Q4. What are C tokens? Explain different types of tokens in C.

• Definition:
Smallest individual unit in a C program.
• Types of Tokens:
1. Keywords → Reserved words (int, return).
2. Identifiers → Names given to variables/functions.
3. Constants → Fixed values (10, 3.14).
4. Strings → "Hello".
5. Operators → +, -, *, /.
6. Special Symbols → {}, (), ;, ,.

Q5. Explain keywords and identifiers in C.

• Keywords:
o Predefined, reserved words with special meaning.
o Cannot be used as variable names.
o Examples: int, float, return, if.
• Identifiers:
o User-defined names for variables, functions, arrays.
o Rules:
▪ Must begin with a letter or underscore.
▪ No spaces or special characters.
▪ Case-sensitive.
o Example:
o int marks; // 'marks' is an identifier
Answer Guide (Q.6 – Q.10)
Q6. Describe variables and constants in C with examples.

• Variables:
o Named memory locations used to store data.
o Value can change during program execution.
o Example:
o int age = 20; // variable 'age'
o age = 25; // value changed
• Constants:
o Fixed values that do not change during execution.
o Types:
▪ Integer constants → 10, -5
▪ Floating constants → 3.14
▪ Character constants → 'A'
▪ String constants → "Hello"
o Example:
o const float PI = 3.14159; // constant

Q7. Explain different data types available in C.

• Primary Data Types:


o int → integers (e.g., 10, -5)
o float → decimal values (e.g., 3.14)
o char → single character (e.g., 'A')
o double → large floating-point values
• Derived Data Types:
o Arrays, Pointers, Structures, Unions
• Enumeration Data Type:
o User-defined type with named integer constants.
o Example:
o enum week {Mon, Tue, Wed};

Q8. What are comments? Explain types of comments used in C programs.

• Definition:
Comments are non-executable statements used to explain code.
• Types:
1. Single-line comment:
2. // This is a single-line comment
3. Multi-line comment:
4. /* This is
5. a multi-line
6. comment */
Q9. Explain the applications and importance of C programming.

• Applications:
o Operating systems (UNIX, Linux kernel).
o Compilers and interpreters.
o Embedded systems (microcontrollers).
o Game development.
o Database systems (Oracle, MySQL).
• Importance:
o Portable and efficient.
o Foundation for modern languages (C++, Java).
o Close to hardware → system-level programming.
o Still widely used in academia and industry.

Q10. Explain the concept of operators and operands in C.

• Operators:
o Symbols that perform operations on data.
o Example: +, -, *, /
• Operands:
o Values or variables on which operators act.
o Example:
o int a = 5, b = 10;
o int sum = a + b; // '+' is operator, 'a' and 'b' are operands

Answer Guide (Q.11 – Q.15)


Q11. Explain different types of operators in C with examples.

• Arithmetic Operators: +, -, *, /, %
• int a=10, b=3;
• printf("%d", a % b); // Output: 1
• Relational Operators: ==, !=, <, >, <=, >=
• if(a > b) printf("a is greater");
• Logical Operators: &&, ||, !
• if(a>5 && b<5) printf("Condition true");
• Assignment Operators: =, +=, -=, *=, /=
• Increment/Decrement Operators: ++, --
• Bitwise Operators: &, |, ^, <<, >>
• Conditional Operator: ?:
• Special Operators: sizeof, &, * (pointer operators).
Q12. What are preprocessor directives? Explain their need in C.

• Definition:
Instructions processed before compilation begins. They start with #.
• Need:
o Code modularity and reusability.
o Easier maintenance.
o Efficient compilation.
• Examples:
o #include <stdio.h> → includes header file.
o #define PI 3.14 → defines constant.

Q13. Explain different categories of preprocessor directives used in C.

1. File Inclusion:
o #include <filename> → adds header files.
2. Macro Substitution:
o #define MAX 100
3. Conditional Compilation:
o #ifdef, #ifndef, #endif
4. Miscellaneous Directives:
o #undef → undefines a macro.
o #pragma → compiler-specific instructions.

Q14. Explain storage classes in C programming.

• Definition:
Storage classes define scope, visibility, and lifetime of variables.
• Types:
1. Automatic (auto) → default for local variables.
2. Static (static) → retains value between function calls.
3. External (extern) → refers to global variables defined elsewhere.
4. Register (register) → stores variable in CPU register for fast access.

Q15. Differentiate between automatic, static, external, and register storage


classes.

Storage Class Scope Lifetime Keyword Example


Automatic Local Till function ends auto auto int x;
Static Local/Global Entire program static static int count;
External Global Entire program extern extern int total;
Register Local Till function ends register register int i;
Answer Guide (Q.16 – Q.20)
Q16. Explain decision-making statements in C.

• Definition:
Decision-making statements allow the program to choose different paths based on
conditions.
• Types:
1. if statement → executes block if condition is true.
2. if-else statement → executes one block if true, another if false.
3. nested if → multiple conditions checked inside another if.
4. switch statement → multiple choices based on expression value.

Q17. Explain if, if-else, and nested if statements with syntax.

• if statement:
• if(condition) {
• // code
• }
• if-else statement:
• if(condition) {
• // true block
• } else {
• // false block
• }
• nested if statement:
• if(condition1) {
• if(condition2) {
• // code if both true
• }
• }

Q18. Explain switch case statement and its execution flow.

• Definition:
Used for multi-way branching based on value of an expression.
• Syntax:
• switch(expression) {
• case value1:
• // statements
• break;
• case value2:
• // statements
• break;
• default:
• // statements
• }
• Execution Flow:
o Expression evaluated once.
o Control jumps to matching case.
o break prevents fall-through.
o If no match → default executes.

Q19. Explain looping statements available in C.

• Definition:
Loops allow repeated execution of code until a condition is met.
• Types:
1. for loop → known number of iterations.
2. while loop → executes while condition is true.
3. do-while loop → executes at least once, then checks condition.

Q20. Differentiate between for, while, and do-while loops.

Loop Type Condition Check Execution Guarantee Use Case


for Before each iteration May execute 0 times Known iterations
while Before each iteration May execute 0 times Condition-controlled
do-while After each iteration Executes at least once Menu-driven programs

Example:

// for loop
for(int i=0; i<5; i++) printf("%d", i);

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

// do-while loop
int k=0;
do { printf("%d", k); k++; } while(k<5);

Answer Guide (Q.21 – Q.25)


Q21. Explain break, continue, goto, and exit statements.
• break:
Terminates the nearest loop or switch.
• for(int i=0; i<5; i++) {
• if(i==3) break; // exits loop when i=3
• printf("%d ", i);
• }
• continue:
Skips the current iteration and moves to the next.
• for(int i=0; i<5; i++) {
• if(i==2) continue; // skips printing 2
• printf("%d ", i);
• }
• goto:
Transfers control to a labeled statement.
• goto label;
• label: printf("Jumped here!");
• exit():
Terminates program execution immediately.
• exit(0); // successful termination

Q22. Define an array. Explain its advantages and limitations.

• Definition:
Array is a collection of elements of the same data type stored in contiguous memory.
• Advantages:
o Easy access using index.
o Efficient storage of multiple values.
o Simplifies code (loops for processing).
• Limitations:
o Fixed size (cannot grow/shrink).
o Same data type only.
o Memory wastage if not fully used.

Q23. Explain declaration and initialization of one-dimensional arrays.

• Declaration:
• int arr[5]; // declares array of 5 integers
• Initialization:
• int arr[5] = {10, 20, 30, 40, 50};
• Access:
• printf("%d", arr[2]); // prints 30

Q24. Explain declaration and initialization of two-dimensional arrays.

• Declaration:
• int matrix[3][3]; // 3x3 array
• Initialization:
• int matrix[2][2] = {{1,2}, {3,4}};
• Access:
• printf("%d", matrix[1][0]); // prints 3

Q25. Why is array size required during declaration? Explain.

• Reason:
o Compiler needs to allocate contiguous memory.
o Size tells how many elements will be stored.
• Example:
• int arr[10]; // reserves memory for 10 integers
• Without size, compiler cannot reserve memory properly.

Answer Guide (Q.26 – Q.30)


Q26. Explain how array elements are stored in memory.

• Storage:
o Elements are stored in contiguous memory locations.
o Index starts from 0.
o Address of element arr[i] = Base address + (i × size of data type).
• Example:
• int arr[3] = {10, 20, 30};

If base address = 1000 and int size = 2 bytes:

o arr[0] → 1000
o arr[1] → 1002
o arr[2] → 1004

Q27. Explain searching techniques on arrays.

• Linear Search:
o Traverse array sequentially.
o Time complexity: O(n).
• for(int i=0; i<n; i++) {
• if(arr[i] == key) return i;
• }
• Binary Search:
o Works on sorted arrays.
o Divide array into halves repeatedly.
o Time complexity: O(log n).
• while(low <= high) {
• mid = (low+high)/2;
• if(arr[mid] == key) return mid;
• else if(arr[mid] < key) low = mid+1;
• else high = mid-1;
• }

Q28. Explain sorting techniques on arrays.

• Bubble Sort: Repeatedly swaps adjacent elements.


• Selection Sort: Selects smallest element and places it at correct position.
• Insertion Sort: Inserts each element into its correct position in sorted part.
• Quick Sort: Divide-and-conquer using pivot.
• Merge Sort: Divide array, sort halves, merge.

Example (Bubble Sort):

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


for(int j=0; j<n-i-1; j++) {
if(arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

Q29. Differentiate between one-dimensional and two-dimensional arrays.

Feature One-Dimensional Array Two-Dimensional Array


Structure Linear list Matrix (rows & columns)
Declaration int arr[5]; int arr[3][3];
Access arr[i] arr[i][j]
Use Case Storing list of values Tables, matrices

Q30. Define a function. Explain the need of functions in C.

• Definition:
A function is a block of code that performs a specific task and can be reused.
• Need:
o Code reusability.
o Modularity (divide program into smaller parts).
o Easier debugging and maintenance.
o Improves readability.
• Example:
int sum(int a, int b) {
return a+b;
}

Answer Guide (Q.31 – Q.35)


Q31. Explain the syntax and components of a function.

• Syntax:
• return_type function_name(parameter_list) {
• // body of function
• return value;
• }
• Components:
1. Return Type → type of value returned (int, float, void).
2. Function Name → identifier for the function.
3. Parameter List → input values (optional).
4. Function Body → statements to perform task.
5. Return Statement → sends result back.

Example:

int sum(int a, int b) {


return a+b;
}

Q32. Explain different types of functions in C.

• Library Functions:
o Predefined, available in header files.
o Example: printf(), scanf(), strlen().
• User-defined Functions:
o Created by programmer for specific tasks.
o Example: int factorial(int n).

Q33. Explain categories of user-defined functions.

1. Function with no arguments and no return value


2. void display() { printf("Hello"); }
3. Function with arguments but no return value
4. void sum(int a, int b) { printf("%d", a+b); }
5. Function with no arguments but return value
6. int getNumber() { return 10; }
7. Function with arguments and return value
8. int sum(int a, int b) { return a+b; }
Q34. Explain function calling mechanism in C.

• Call by Value:
o Copy of actual parameter passed.
o Changes inside function do not affect original.
• void fun(int x) { x=20; }
• Call by Reference (using pointers):
o Address of variable passed.
o Changes inside function affect original.
• void fun(int *x) { *x=20; }

Q35. Explain recursion with advantages and limitations.

• Definition:
Function calling itself directly or indirectly.
• Example:
• int factorial(int n) {
• if(n==0) return 1;
• else return n * factorial(n-1);
• }
• Advantages:
o Simplifies code for problems like factorial, Fibonacci, tree traversal.
o Elegant solution for divide-and-conquer.
• Limitations:
o More memory usage (stack frames).
o Slower than iteration.
o Risk of infinite recursion if base case missing.

Answer Guide (Q.36 – Q.40)


Q36. Explain scope, visibility, and lifetime of variables.

• Scope:
o Region of program where a variable can be accessed.
o Types:
▪ Local scope → inside a function/block.
▪ Global scope → declared outside all functions.
• Visibility:
o Determines whether a variable can be accessed from other functions/files.
o Example: static variables have limited visibility.
• Lifetime:
o Duration for which a variable exists in memory.
o Local variables → exist until function ends.
o Static/global variables → exist until program ends.

Q37. Define structure. Explain structure declaration and initialization.

• Definition:
A structure is a user-defined data type that groups different data types under one
name.
• Declaration:
• struct Student {
• int roll;
• char name[20];
• float marks;
• };
• Initialization:
• struct Student s1 = {101, "Rahul", 85.5};

Q38. Explain arrays of structures.

• Definition:
Collection of structures stored in an array.
• Example:
• struct Student {
• int roll;
• char name[20];
• };
• struct Student s[3] = {
• {101, "Rahul"},
• {102, "Priya"},
• {103, "Amit"}
• };
• Use:
Useful for handling records like student database, employee list.

Q39. Explain nested structures.

• Definition:
A structure inside another structure.
• Example:
• struct Address {
• char city[20];
• int pin;
• };
• struct Student {
• int roll;
• char name[20];
• struct Address addr;
• };
• Access:
• printf("%s", [Link]);

Q40. Explain passing structures to functions.

• Methods:
1. Pass by Value:
Copy of structure passed.
2. void display(struct Student s) { printf("%d", [Link]); }
3. Pass by Reference:
Address of structure passed using pointer.
4. void display(struct Student *s) { printf("%d", s->roll); }
• Use:
Helps modularize code and reuse structure data in multiple functions.

Answer Guide (Q.41 – Q.45)


Q41. Define union and explain its features.

• Definition:
A union is a user-defined data type similar to a structure, but all members share the
same memory location.
• Features:
o Memory is allocated equal to the largest member.
o Only one member can hold a value at a time.
o Efficient memory usage.
• Example:
• union Data {
• int i;
• float f;
• char ch;
• };
• union Data d;
• d.i = 10; // only 'i' is valid now

Q42. Differentiate between structure and union.

Feature Structure Union


Memory Separate memory for each member Shared memory for all members
Size Sum of all members Size of largest member
Usage Can store multiple values at once Only one value at a time
Example Student record Efficient memory storage
Q43. Define pointer. Explain pointer declaration and initialization.

• Definition:
A pointer is a variable that stores the address of another variable.
• Declaration:
• int *ptr; // pointer to int
• Initialization:
• int x = 10;
• int *ptr = &x; // ptr stores address of x

Q44. Explain accessing variables using pointers.

• Steps:
1. Declare a pointer.
2. Assign address of variable using &.
3. Access value using * (dereference operator).
• Example:
• int x = 20;
• int *p = &x;
• printf("%d", *p); // prints 20

Q45. Explain pointer arithmetic.

• Definition:
Operations performed on pointers to move through memory.
• Types:
1. Increment (ptr++) → moves to next memory location.
2. Decrement (ptr--) → moves to previous memory location.
3. Addition (ptr+n) → jumps n elements forward.
4. Subtraction (ptr-n) → jumps n elements backward.
• Example:
• int arr[3] = {10,20,30};
• int *p = arr;
• p++; // now points to arr[1]

Answer Guide (Q.46 – Q.50)


Q46. Explain relationship between pointers and arrays.

• Relationship:
o Array name acts as a pointer to the first element.
o arr[i] is equivalent to *(arr+i).
• Example:
• int arr[3] = {10,20,30};
• int *p = arr; // arr points to first element
• printf("%d", *(p+1)); // prints 20

Q47. Differentiate between array and pointer.

Feature Array Pointer


Definition Collection of elements Variable storing address
Memory Fixed, contiguous block Can point anywhere in memory
Size Fixed at compile time Can be changed dynamically
Syntax arr[i] *(p+i)

Q48. Explain pointer to pointer.

• Definition:
A pointer that stores the address of another pointer.
• Declaration:
• int x = 10;
• int *p = &x;
• int **pp = &p; // pointer to pointer
• Access:
• printf("%d", **pp); // prints 10

Q49. Explain pointer to array.

• Definition:
A pointer that points to an entire array.
• Example:
• int arr[5] = {1,2,3,4,5};
• int (*p)[5] = &arr; // pointer to array of 5 ints
• Access:
• printf("%d", (*p)[2]); // prints 3

Q50. Explain passing pointer variables to functions.

• Definition:
Pointers can be passed to functions to allow direct modification of variables.
• Example:
• void update(int *p) {
• *p = *p + 10;
• }
• int main() {
• int x = 5;
• update(&x);
• printf("%d", x); // prints 15
• return 0;
• }
• Advantage:
o Efficient (avoids copying large data).
o Enables call by reference.

Answer Guide (Q.51 – Q.55)


Q51. Define string in C.

• Definition:
A string in C is a sequence of characters terminated by a null character '\0'.
• Example:
• char str[] = "Hello";
• Stored as an array of characters.

Q52. Explain different methods of string declaration and initialization.

• Method 1: Character Array


• char str[6] = {'H','e','l','l','o','\0'};
• Method 2: String Constant
• char str[] = "Hello";
• Method 3: Pointer to String
• char *str = "Hello";

Q53. Explain various string handling functions in C.

• Defined in <string.h> library.


• Common functions:
o strlen(str) → length of string.
o strcpy(dest, src) → copy string.
o strcat(str1, str2) → concatenate strings.
o strcmp(str1, str2) → compare strings.
o strchr(str, ch) → find character in string.
o strstr(str1, str2) → find substring.

Q54. Explain string comparison and string concatenation.

• String Comparison:
o Done using strcmp().
o Returns 0 if equal, <0 if first < second, >0 if first > second.
• if(strcmp("apple","apple")==0) printf("Equal");
• String Concatenation:
o Done using strcat().
o Appends one string to another.
• char str1[20]="Hello ";
• char str2[]="World";
• strcat(str1,str2); // str1 = "Hello World"

Q55. Explain procedural oriented programming.

• Definition:
Programming paradigm based on procedures (functions).
• Features:
o Program divided into functions.
o Emphasis on functions rather than data.
o Data is global and functions operate on it.
• Advantages:
o Simple and easy to implement.
o Good for small programs.
• Limitations:
o Not suitable for large, complex systems.
o Data security is low (global access).

Answer Guide (Q.56 – Q.60)


Q56. Explain object-oriented programming concepts.

• Definition:
OOP is a paradigm based on objects that combine data and functions.
• Key Concepts:
1. Class → blueprint for objects.
2. Object → instance of a class.
3. Encapsulation → binding data and methods together.
4. Abstraction → hiding implementation details.
5. Inheritance → deriving new classes from existing ones.
6. Polymorphism → ability to take many forms (function overloading,
overriding).

Q57. Differentiate between procedural and object-oriented programming.


Procedural Programming Object-Oriented Programming
Feature
(POP) (OOP)
Approach Function-based Object-based
Focus Procedures (functions) Data and objects
Data Security Low (global access) High (encapsulation)
Reusability Limited High (inheritance, polymorphism)
Example
C C++, Java, Python
Languages

Q58. Explain features and benefits of object-oriented programming.

• Features:
o Encapsulation
o Abstraction
o Inheritance
o Polymorphism
• Benefits:
o Code reusability.
o Easier maintenance.
o Better data security.
o Models real-world problems effectively.

Q59. Explain applications of object-oriented programming.

• Applications:
o GUI applications (Java, C++).
o Game development.
o Simulation and modeling.
o Database systems.
o Large-scale enterprise software.
o Mobile applications.

Q60. Explain the basic structure of a C++ program.

• Structure:
1. Documentation Section → comments.
2. Preprocessor Directives → #include <iostream>.
3. Namespace Declaration → using namespace std;.
4. Main Function → int main() { ... }.
5. Class/Function Definitions → user-defined code.

Example:
#include <iostream>
using namespace std;

int main() {
cout << "Hello, C++!";
return 0;
}

Answer Guide (Q.61 – Q.65)


Q61. Explain namespaces in C++.

• Definition:
A namespace is a container that groups identifiers (classes, functions, variables) to
avoid name conflicts.
• Syntax:
• namespace MySpace {
• int x = 10;
• void display() { cout << x; }
• }
• Usage:
• using namespace MySpace;
• display(); // prints 10
• Benefit:
Prevents clashes when multiple libraries have same function/variable names.

Q62. Explain data types in C++.

• Basic Data Types: int, float, double, char, bool.


• Derived Data Types: Arrays, Pointers, Functions, References.
• User-defined Data Types:
o struct
o class
o enum
o typedef
• Example:
• int a = 10;
• float b = 3.14;
• bool flag = true;

Q63. How are constants defined in C++?

• Using const keyword:


• const int MAX = 100;
• Using #define preprocessor:
• #define PI 3.14159
• Using enum:
• enum days {Mon, Tue, Wed};
• Using constexpr (C++11 onwards):
• constexpr int SIZE = 50;

Q64. Explain typecasting in C++.

• Definition:
Converting one data type into another.
• Types:
1. Implicit (Type Promotion):
Done automatically by compiler.
2. int a = 10; float b = a; // implicit
3. Explicit (Type Casting):
Done manually by programmer.
4. float x = 3.14;
5. int y = (int)x; // explicit
• C++ Specific Casts:
o static_cast
o dynamic_cast
o const_cast
o reinterpret_cast

Q65. Explain control structures in C++.

• Definition:
Control structures define the flow of program execution.
• Types:
1. Sequence Structure → statements executed in order.
2. Decision-making Structure → if, if-else, switch.
3. Looping Structure → for, while, do-while.
4. Jump Statements → break, continue, goto, return.

Example:

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


cout << i << " ";
}

Answer Guide (Q.66 – Q.70)


Q66. Explain scope resolution operator with example.
• Definition:
The scope resolution operator :: is used in C++ to access global variables or class
members outside their scope.
• Uses:
1. To access a global variable when a local variable has the same name.
2. To define a function outside the class.
• Example:
• int x = 10; // global variable
• class Test {
• public:
• int x;
• void show();
• };
• void Test::show() { // defined outside class
• cout << ::x; // accesses global x
• }

Q67. Explain functions in C++.

• Definition:
Functions are blocks of code that perform specific tasks.
• Types:
1. Library Functions → predefined (cout, cin, sqrt()).
2. User-defined Functions → created by programmer.
• Syntax:
• return_type function_name(parameters) {
• // body
• }
• Example:
• int add(int a, int b) { return a+b; }

Q68. Explain parameter passing mechanisms in C++.

• Call by Value:
o Copy of actual parameter passed.
o Changes inside function do not affect original.
• void fun(int x) { x=20; }
• Call by Reference:
o Actual variable passed using reference (&).
o Changes affect original variable.
• void fun(int &x) { x=20; }
• Call by Pointer:
o Address of variable passed.
o Changes affect original variable.
• void fun(int *x) { *x=20; }

Q69. Explain inline functions and their advantages.


• Definition:
Inline functions are expanded at the point of call instead of normal function
invocation.
• Syntax:
• inline int square(int x) { return x*x; }
• Advantages:
o Reduces function call overhead.
o Faster execution for small functions.
o Improves performance in frequently used functions.
• Limitations:
o Not suitable for large/complex functions.
o Compiler may ignore inline request.

Q70. Explain macros in C++.

• Definition:
Macros are preprocessor directives used to define constants or functions.
• Syntax:
• #define PI 3.14159
• #define SQUARE(x) (x*x)
• Features:
o Text substitution before compilation.
o Faster but less type-safe compared to inline functions.

Answer Guide (Q.71 – Q.75)


Q71. Differentiate between macro and inline function.

Feature Macro (#define) Inline Function (inline)


Handled by preprocessor (text Handled by compiler (function
Processing
substitution) expansion)
Type
No type checking Type checking enforced
Safety
Debugging Difficult (expanded text) Easier (function semantics)
Efficiency Fast but error-prone Fast and safer
inline int square(int x){return
Example #define SQUARE(x) (x*x)
x*x;}

Q72. Explain function overloading with example.


• Definition:
Function overloading allows multiple functions with the same name but different
parameter lists.
• Example:
• int add(int a, int b) { return a+b; }
• double add(double a, double b) { return a+b; }

• cout << add(2,3); // calls int version
• cout << add(2.5,3.5); // calls double version

Q73. Explain default arguments in C++ functions.

• Definition:
Default arguments are values automatically assigned to parameters if no value is
provided.
• Syntax:
• int sum(int a, int b=10) {
• return a+b;
• }
• cout << sum(5); // uses default b=10 → 15
• Rule:
Default arguments must be given from rightmost parameters.

Q74. Explain evaluation of default parameters in C++.

• Concept:
Default parameters are evaluated at the time of function call.
• Example:
• void display(int a=5, int b=10) {
• cout << a << " " << b;
• }
• display(); // prints 5 10
• display(20); // prints 20 10
• display(20,30); // prints 20 30
• Note:
Default values are substituted by compiler during function call.

Q75. Explain the concept of class and object.

• Class:
o Blueprint for creating objects.
o Defines data members and member functions.
• class Student {
• int roll;
• string name;
• public:
• void setData(int r, string n) { roll=r; name=n; }
• void display() { cout<<roll<<" "<<name; }
• };
• Object:
o Instance of a class.
• Student s1;
• [Link](101,"Rahul");
• [Link]();

Answer Guide (Q.76 – Q.80)


Q76. Differentiate between class and object.

Feature Class Object


Definition Blueprint/template Instance of a class
Memory No memory allocated Memory allocated when created
Use Defines properties & methods Represents real-world entity
Example class Student { ... }; Student s1;

Q77. Explain access specifiers in C++.

• Definition:
Access specifiers define the visibility of class members.
• Types:
1. Public: Accessible from anywhere.
2. public: int roll;
3. Private: Accessible only within the class.
4. private: int marks;
5. Protected: Accessible within class and derived classes.
6. protected: int age;

Q78. Explain constructor and its types.

• Definition:
Special member function used to initialize objects.
• Features:
o Same name as class.
o No return type.
• Types:
1. Default Constructor: No parameters.
2. Student() { roll=0; }
3. Parameterized Constructor: Accepts arguments.
4. Student(int r) { roll=r; }
5. Copy Constructor: Initializes object from another object.
6. Student(Student &s) { roll=[Link]; }

Q79. Explain static data members and static member functions.

• Static Data Members:


o Shared among all objects of a class.
o Declared using static.
• class Test {
• static int count;
• };
• int Test::count = 0;
• Static Member Functions:
o Can access only static data members.
o Called using class name.
• class Test {
• static void show() { cout<<"Hello"; }
• };
• Test::show();

Q80. Explain friend function and its advantages.

• Definition:
A non-member function that can access private/protected members of a class.
• Syntax:
• class Student {
• int roll;
• friend void display(Student s);
• };
• void display(Student s) { cout<<[Link]; }
• Advantages:
o Provides controlled access to private data.
o Useful for operator overloading.
o Helps in functions that need access to multiple classes.
Condensed Revision Chart (Q1–Q80)
[Link] Topic Key Points / Summary
Documentation, Preprocessor, Global declarations,
1 Structure of C program
main(), Functions
Developed by Dennis Ritchie (1972), basis of UNIX,
2 Evolution of C
portable, efficient
Algorithm = stepwise procedure; Flowchart = graphical
3 Algorithm & Flowchart
symbols (oval, rectangle, diamond)
Keywords, Identifiers, Constants, Strings, Operators,
4 C Tokens
Special symbols
5 Keywords & Identifiers Keywords = reserved; Identifiers = user-defined names
6 Variables & Constants Variables change; Constants fixed (const, literals)
Primary (int, float, char, double), Derived (arrays,
7 Data Types in C
pointers), Enum
8 Comments Single-line //, Multi-line /*...*/
9 Applications of C OS, compilers, embedded systems, databases, games
10 Operators & Operands Operators = symbols; Operands = values/variables
Arithmetic, Relational, Logical, Assignment, Bitwise,
11 Types of Operators
Conditional
12 Preprocessor Directives Instructions before compilation (#include, #define)
File inclusion, Macro substitution, Conditional
13 Categories of Directives
compilation, Misc
14 Storage Classes auto, static, extern, register
15 Storage Class Differences Scope, lifetime, visibility compared in table
16 Decision-making if, if-else, nested if, switch
17 if Statements Syntax for if, if-else, nested if
18 switch Case Multi-way branching, break, default
19 Loops for, while, do-while
for = known iterations, while = condition, do-while =
20 Loop Differences
executes at least once
21 Jump Statements break, continue, goto, exit
22 Array Definition Collection of same type, contiguous memory
23 1D Array Declaration int arr[5];, initialization {...}
24 2D Array Declaration int arr[3][3];, initialization
{{...},{...}}
25 Array Size Needed for memory allocation
26 Array Storage Contiguous memory, address = base + index × size
27 Searching Linear search O(n), Binary search O(log n)
28 Sorting Bubble, Selection, Insertion, Quick, Merge
[Link] Topic Key Points / Summary
29 1D vs 2D Array Linear vs matrix, syntax difference
30 Functions Block of code, modularity, reusability
31 Function Syntax Return type, name, parameters, body, return
32 Types of Functions Library vs user-defined
Categories of User
33 No arg/no return, arg/no return, no arg/return, arg/return
Functions
34 Function Calling Call by value vs call by reference
Function calls itself, pros = elegant, cons = memory
35 Recursion
heavy
36 Scope/Visibility/Lifetime Local vs global, static lifetime
37 Structure User-defined type grouping variables
38 Array of Structures Collection of structures in array
39 Nested Structures Structure inside another
40 Passing Structures By value or by reference (pointer)
41 Union Shared memory, one member active
42 Structure vs Union Structure = separate memory, Union = shared memory
43 Pointer Stores address of variable
44 Access via Pointer *p dereferences value
45 Pointer Arithmetic Increment, decrement, addition, subtraction
46 Pointer & Array Array name = pointer to first element
47 Array vs Pointer Fixed block vs flexible address
48 Pointer to Pointer Stores address of another pointer
49 Pointer to Array Pointer to entire array (int (*p)[5])
50 Passing Pointers Enables call by reference
51 String in C Sequence of chars ending with \0
52 String Declaration Char array, string constant, pointer
53 String Functions strlen, strcpy, strcat, strcmp, strchr, strstr
54 String Ops Comparison (strcmp), Concatenation (strcat)
55 Procedural Programming Function-based, global data, less secure
Class, Object, Encapsulation, Abstraction, Inheritance,
56 OOP Concepts
Polymorphism
57 POP vs OOP Function vs object focus, low vs high security
58 OOP Features Encapsulation, Abstraction, Inheritance, Polymorphism
59 OOP Applications GUI, games, databases, enterprise apps
60 C++ Program Structure #include, namespace, main(), classes/functions
61 Namespaces Avoid name conflicts, namespace MySpace {}
62 Data Types in C++ Basic, Derived, User-defined
63 Constants in C++ const, #define, enum, constexpr
64 Typecasting Implicit vs explicit, C++ casts (static_cast, etc.)
65 Control Structures Sequence, decision, looping, jump
[Link] Topic Key Points / Summary
66 Scope Resolution Operator :: to access global/class members
67 Functions in C++ Library vs user-defined
68 Parameter Passing Value, reference, pointer
69 Inline Functions Expanded at call, faster, small functions
70 Macros Preprocessor substitution, #define
71 Macro vs Inline Macro = preprocessor, Inline = compiler
72 Function Overloading Same name, different parameters
73 Default Arguments Values auto-assigned if not provided
Default Parameter
74 Substituted at call time
Evaluation
75 Class & Object Class = blueprint, Object = instance
76 Class vs Object Blueprint vs instance
77 Access Specifiers Public, Private, Protected
78 Constructors Default, Parameterized, Copy
79 Static Members Shared among objects, accessed via class
80 Friend Function Non-member with access to private data

You might also like