Fop Long Q Ans
Fop Long Q Ans
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:
// 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;
}
• 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.
• 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
• 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 → {}, (), ;, ,.
• 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
• 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.
• 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
• 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.
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.
• 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.
• 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.
• 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
• }
• }
• 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.
• 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.
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);
• 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.
• 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
• Declaration:
• int matrix[3][3]; // 3x3 array
• Initialization:
• int matrix[2][2] = {{1,2}, {3,4}};
• Access:
• printf("%d", matrix[1][0]); // prints 3
• 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.
• 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};
o arr[0] → 1000
o arr[1] → 1002
o arr[2] → 1004
• 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;
• }
• 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;
}
• 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:
• 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).
• 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; }
• 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.
• 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.
• 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};
• 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.
• 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]);
• 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.
• 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
• 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
• 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
• 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]
• 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
• 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
• 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
• 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.
• 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.
• 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"
• 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).
• 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).
• 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.
• Applications:
o GUI applications (Java, C++).
o Game development.
o Simulation and modeling.
o Database systems.
o Large-scale enterprise software.
o Mobile applications.
• 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;
}
• 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.
• 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
• 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:
• 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; }
• 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; }
• 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.
• 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.
• 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.
• 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]();
• 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;
• 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]; }
• 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