Sikshya Plus Get appGet the app free
Class 12 · Computer Science

Programming in C – Class 12 Computer Science Notes and Solutions

Complete solutions and answers for “Programming in C”, a chapter in Class 12 Computer Science (NEB exam preparation). This page covers Multiple Choice Questions Questions 1 – 20 · Select the correct option, Short Answer Questions Questions 1 – 12 · Concise yet comprehensive explanations and Long Answer Questions Questions 1 – 8 · Detailed explanations with programs and examples.

  • Free, no login needed
  • 33 min read
  • Updated 1 July 2026

Chapter at a glance

This chapter provides a comprehensive guide to programming in C, covering fundamental concepts like data types, operators, and control structures. It delves into advanced topics such as functions, pointers, structures, unions, and file handling, offering detailed explanations and examples for each.

  • Data Types (basic, derived, user-defined)
  • Operators (arithmetic, logical, bitwise)
  • Control Structures (if-else, switch, loops)
  • Functions (library, user-defined, recursion)
  • Pointers (declaration, dereferencing, arithmetic)
  • Structures and Unions
  • File Handling (sequential, random access)
  • Arrays (1D, 2D)

Exam focus: Students should focus on understanding the syntax and practical application of C programming concepts, especially pointers, structures, and control flow, as these are frequently tested with coding problems and theoretical questions.

Key formulas and definitions

  • Identifier Naming Rules: Must start with a letter or underscore, can contain letters, digits, underscores. Cannot be a keyword.
  • Structure Size: Sum of sizes of all members (with potential padding).
  • Union Size: Size of the largest member.
  • Pointer Declaration: data_type *pointer_name;
  • Array Indexing: Starts from 0.
On this page (3 sections)
  1. Multiple Choice Questions Questions 1 – 20 · Select the correct option
  2. Short Answer Questions Questions 1 – 12 · Concise yet comprehensive explanations
  3. Long Answer Questions Questions 1 – 8 · Detailed explanations with programs and examples

Solutions and answers

Complete exercise solutions with detailed explanations covering data types, operators, control structures, functions, pointers, structures, unions, and file handling.

📘 Approved by CDC — Innovative Computer Science, Grade XII
📋

Multiple Choice Questions Questions 1 – 20 · Select the correct option

1

Which is NOT the basic data type in C?

  • a double
  • b int
  • c char
  • d array ✓
Explanation: The four basic (fundamental/primitive) data types in C are int, char, float, and double. An array is a derived data type — it is constructed from one of the basic types to hold a collection of elements of the same type.
2

Which is the user-defined data type in C?

  • a array
  • b union
  • c structure ✓
  • d All of the above
Explanation: A structure (struct) is a user-defined data type in C that allows grouping variables of different data types under a single name. While union is also user-defined, the most standard answer expected here is structure. An array is a derived data type, not user-defined. Note: Both struct and union are user-defined; however, structure is the canonical answer for this question.
3

The %d format specifier is used for:

  • a character
  • b string
  • c float value
  • d signed integer ✓
Explanation: %d is the format specifier for printing/reading a signed decimal integer. For reference: %c → character, %s → string, %f → float, %lf → double.
4

a++ is equivalent to:

  • a a = a + 1 ✓
  • b a = a + 2
  • c a + 1 = a
  • d None of the above
Explanation: a++ is the post-increment operator. It increments the value of a by 1 after the current expression is evaluated. It is functionally equivalent to a = a + 1. Note that a+1 = a is invalid because the left side of an assignment must be an l-value (a modifiable variable).
5

Which is NOT the formatted function?

  • a gets()
  • b getch()
  • c puts()
  • d All of the above ✓
Explanation: Formatted I/O functions use format specifiers (e.g., printf(), scanf()). The functions gets(), getch(), and puts() are all unformatted I/O functions — they do not use format specifiers. Hence, all three are "not formatted functions."
6

What is the output of the below code?

C #include<stdio.h> void main(){ int a = 7; int *p = &a; printf("%d", *p); }
  • a Address of a
  • b Address of p
  • c Address of *p
  • d 7 ✓
Explanation: The pointer p stores the address of variable a. The expression *p dereferences the pointer, meaning it accesses the value stored at that address — which is 7. Using %d format specifier prints the integer value, not the address. To print the address, we would use %p and pass p (not *p).
7

Which of the following is the logical AND operator?

  • a & (bitwise AND)
  • b && ✓
  • c !!
  • d None of the above
Explanation: && is the logical AND operator in C. It evaluates to true (1) only when both operands are true. The single & is the bitwise AND operator. !! is not a single operator — ! is the logical NOT.
8

Which of the derived data type stores collection of different data types?

  • a array
  • b pointer
  • c structure ✓
  • d None of the above
Explanation: A structure is a derived/user-defined data type that can hold members of different data types (e.g., int, float, char) together. An array stores elements of the same data type. A pointer stores memory addresses.
9

A function which calls itself is called …………

  • a cursive function
  • b auto function
  • c self function
  • d recursive function ✓
Explanation: A recursive function is a function that calls itself directly or indirectly. Recursion must always have a base case (termination condition) to prevent infinite recursion. Classic examples include computing factorial and Fibonacci series.
10

The size of the union is equal to:

  • a sum of sizes of members
  • b size of first member
  • c size of smallest member
  • d size of largest member ✓
Explanation: In a union, all members share the same memory location. Therefore, the compiler allocates memory equal to the size of the largest member so that any member can be stored. This is unlike a structure, where the size is the sum of all members.
11

scanf("%[^\n]s", ch); refers to:

  • a syntax error
  • b read all characters
  • c read only new line character
  • d read all characters till new line ✓
Explanation: The %[^\n] is a scanset specifier. It tells scanf() to read all characters until a newline (\n) is encountered. The ^ inside the brackets means "read everything except the character after the caret." This is a common technique to read an entire line including spaces.
12

A file mode which is used to open an existing data file for both reading and writing purpose:

  • a w
  • b W+
  • c r+ ✓
  • d a+
Explanation: The r+ mode opens an existing file for both reading and writing. The file must exist, otherwise fopen() returns NULL. w+ creates a new file (or truncates existing), and a+ opens for appending and reading.
13

Which function in C reads a single character from a file at a time?

  • a scanf()
  • b getch()
  • c fgets()
  • d fgetc() ✓
Explanation: fgetc() reads a single character from the specified file stream and advances the file position indicator. scanf() reads formatted input, getch() reads from keyboard, and fgets() reads a string/line from a file.
14

Which is the proper declaration of an integer pointer?

  • a int &x
  • b int x*
  • c int *x ✓
  • d float *x
Explanation: The correct syntax to declare a pointer to an integer is int *x;. The * indicates that x is a pointer. int &x uses C++ reference syntax (not C). int x* has incorrect placement of *. float *x declares a pointer to float, not integer.
15

The memory size occupied by a structure is:

  • a The size of the longest member in the structure
  • b The sum of the memory sizes of all members in the structure ✓
  • c The size of the first member in the structure
  • d Determined by a compiler
Explanation: In a structure, each member gets its own separate memory location. The total size is the sum of the sizes of all members (plus possible padding for alignment). This contrasts with a union, where the size equals the largest member.
16

A function can return ………… value or values to the calling function module.

  • a 1 ✓
  • b 2
  • c 3
  • d 4
Explanation: In C, a function can return only one value using the return statement. To "return" multiple values, programmers use pointers, arrays, or structures as workarounds — but the function itself returns a single value.
17

Automatic variable is a variable that is:

  • a declared within a function module ✓
  • b declared outside of all the functions
  • c declared with automatic keyword
  • d None of the above
Explanation: Automatic variables (also called local variables) are declared inside a function or block. They exist only during the execution of that function/block. Variables declared outside all functions are external/global variables. The auto keyword is optional — it is the default for variables inside a function.
18

The variable declaration with no storage class specified is by default …………

  • a automatic variable ✓
  • b external variable
  • c static variable
  • d register variable
Explanation: When a variable is declared inside a function without specifying a storage class, it defaults to automatic (auto). Its scope is limited to the block in which it is declared, and it is destroyed when the block exits.
19

A compiler cannot detect ………… error.

  • a syntax
  • b logical ✓
  • c run time
  • d None of the above
Explanation: The compiler can detect syntax errors (violations of language grammar) and some semantic errors. However, logical errors — where the program runs but produces incorrect results due to flawed logic — cannot be detected by the compiler. They must be found through testing and debugging.
20

The && and || operators are used to:

  • a join two different numbers
  • b join two different characters
  • c compare two numbers
  • d None of the above ✓
Explanation: && (logical AND) and || (logical OR) are logical operators. They are used to combine two or more conditions/relational expressions, not to "join" or "compare" numbers directly. Comparison is done by relational operators (==, !=, <, >, <=, >=). Since none of the options a, b, c accurately describe their purpose, the answer is None of the above.
✏️

Short Answer Questions Questions 1 – 12 · Concise yet comprehensive explanations

1

What is an identifier? Write the rules for naming identifiers.

Definition An identifier is a name given to various program elements such as variables, functions, arrays, structures, labels, and other user-defined items. It is used to uniquely identify these elements within a program.

Rules for Naming Identifiers

  • An identifier must begin with a letter (a–z or A–Z) or an underscore (_). It cannot start with a digit.
  • An identifier can contain only letters, digits (0–9), and underscores. Special characters like @, #, $, %, spaces, etc., are not allowed.
  • An identifier cannot be a C keyword (reserved word) such as int, float, if, while, return, etc.
  • C is case-sensitive: Age, age, and AGE are three different identifiers.
  • There is no length limit on identifiers in modern C, though only the first 31 characters are guaranteed to be significant in ANSI C.
  • Identifiers should be meaningful and descriptive (e.g., totalMarks is better than tm).
Examples Valid identifiers: int student_age; float totalMarks; char _grade; int sum123; Invalid identifiers: int 2students; starts with digit float total marks; contains space int while; keyword char #name; special character
2

What is an operator? List the operators in arithmetic operator.

Definition An operator is a symbol that tells the compiler to perform a specific mathematical, relational, logical, or other manipulation on one or more operands (values/variables).

Arithmetic Operators in C

Operator Name Description Example
+AdditionAdds two operandsa + b
-SubtractionSubtracts second from firsta - b
*MultiplicationMultiplies two operandsa * b
/DivisionDivides first by seconda / b
%ModulusReturns the remaindera % b
Important Note When both operands of / are integers, integer division is performed (the fractional part is discarded). For example, 7 / 2 gives 3, not 3.5. The modulus operator % works only with integer operands.
3

What is a loop? Explain the different looping statements used in C program.

Definition A loop is a control structure that allows a block of code to be executed repeatedly as long as a specified condition remains true. Loops are used to avoid repetitive code and to perform iterative tasks efficiently.

Types of Looping Statements in C

C provides three types of loops:

1. forLoop

Used when the number of iterations is known in advance. It combines initialization, condition checking, and update in a single line.

C for (initialization; condition; update) { body of the loop } Example: for (int i = 1; i <= 5; i++) { printf("%d ", i); } Output: 1 2 3 4 5

2. whileLoop (Entry-controlled)

Used when the number of iterations is not known in advance. The condition is checked before each iteration. If the condition is false initially, the loop body is never executed.

C while (condition) { body of the loop update statement } Example: int i = 1; while (i <= 5) { printf("%d ", i); i++; }

3. do-whileLoop (Exit-controlled)

Similar to while, but the condition is checked after each iteration. This guarantees that the loop body executes at least once, even if the condition is initially false.

C do { body of the loop update statement } while (condition); Example: int i = 1; do { printf("%d ", i); i++; } while (i <= 5);
4

What is a control structure? Explain shortly about if statement and switch…case statement.

Definition A control structure determines the order in which statements are executed in a program. It controls the flow of program execution based on conditions or loops.

ifStatement

The if statement is a conditional control structure that executes a block of code only when a specified condition evaluates to true (non-zero).

C Simple if if (marks >= 40) { printf("Passed!"); } if-else if (marks >= 40) { printf("Passed!"); } else { printf("Failed!"); } if-else-if ladder if (marks >= 80) printf("Distinction"); else if (marks >= 60) printf("First Division"); else if (marks >= 40) printf("Second Division"); else printf("Fail");

switch…caseStatement

The switch statement is a multi-way branching (selection) control structure. It evaluates an expression and matches its value against multiple case labels to decide which block of code to execute.

C switch (expression) { case value1: statements break; case value2: statements break; default: default statements }
  • The expression in switch must evaluate to an integer or character type.
  • Each case label must be a unique constant.
  • The break statement prevents fall-through to subsequent cases.
  • The default case executes when no case matches (optional).
5

Define library function and user-defined function.

Library Function (Built-in Function)

Definition A library function is a pre-defined function provided by the C standard library. These functions are already written, compiled, and stored in header files. Programmers can directly call them by including the appropriate header file.
  • Declared in header files such as <stdio.h>, <math.h>, <string.h>, <stdlib.h>, etc.
  • Examples: printf(), scanf(), sqrt(), strlen(), pow(), strcpy()
  • Saves development time — no need to write code from scratch.
  • They are reliable, optimized, and well-tested.

User-Defined Function

Definition A user-defined function is a function created by the programmer to perform a specific task. It promotes modularity, code reusability, and organized programming.
  • The programmer defines the function name, parameters, return type, and body.
  • Must be declared (prototype) and defined before or within the program.
  • Helps break a large problem into smaller, manageable sub-problems.
C User-defined function example int add(int a, int b) { return a + b; } void main() { int result = add(5, 3); Calling user-defined function printf("Sum = %d", result); Library function }
6

What is an argument? How does it differ from a parameter? Explain.

Argument (Actual Parameter)

Definition An argument is the actual value or expression that is passed to a function during a function call. It is also known as an actual parameter.

Parameter (Formal Parameter)

Definition A parameter is the variable listed in the function definition (declaration) that receives the value of the argument. It is also known as a formal parameter.
Arguments (Actual)
  • Used in the function call
  • Can be constants, variables, or expressions
  • Passed to the function
  • Number and type must match parameters
Parameters (Formal)
  • Used in the function definition
  • Always declared as variables
  • Receive values from arguments
  • Exist only within the function scope
C 'a' and 'b' are PARAMETERS (formal) int add(int a, int b) { return a + b; } void main() { int x = 10, y = 20; printf("%d", add(x, y)); ^ ^ ARGUMENTS (actual): x and y }
7

What is a storage class? Define automatic and external variable with examples.

Definition A storage class in C determines the scope (visibility), lifetime (duration), and default initial value of a variable. C has four storage classes: auto, extern, static, and register.

Automatic Variable (auto)

  • Declared inside a function or block.
  • Scope is local — accessible only within the function/block where declared.
  • Lifetime: created when the function is called and destroyed when it exits.
  • Default initial value: garbage (undefined/random).
  • The auto keyword is optional — it is the default storage class for local variables.
C void main() { auto int x = 10; 'auto' is optional int y = 20; Also automatic by default printf("%d %d", x, y); Output: 10 20 } x and y do not exist outside main()

External Variable (extern)

  • Declared outside all functions (at the file level).
  • Scope is global — accessible by all functions in the program.
  • Lifetime: exists for the entire duration of the program.
  • Default initial value: zero (0 for int, 0.0 for float, '\0' for char).
  • The extern keyword is used to declare a variable that is defined in another file or later in the same file.
C int count = 0; External (global) variable void increment() { count++; Accessible here } void main() { count = 5; Accessible here too increment(); printf("%d", count); Output: 6 }
8

What is a structure? Write the advantages of structure.

Definition A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. It is defined using the struct keyword.
C struct Student { char name[50]; int roll; float marks; };

Advantages of Structure

  • Groups heterogeneous data: Can store members of different data types (int, float, char, array, etc.) in a single unit.
  • Improves code organization: Related data is logically grouped, making the program more readable and maintainable.
  • Code reusability: A structure template can be used to create multiple variables of the same type.
  • Easy data transfer: An entire structure can be passed to a function as a single argument, avoiding multiple parameters.
  • Nesting possible: Structures can contain other structures, enabling complex data modeling.
  • Array of structures: An array can hold multiple records (e.g., a list of students).
  • Reduces complexity: Simplifies working with complex data by encapsulating related fields.
9

What is a union? Write the differences between union and structure.

Definition A union is a user-defined data type in C where all members share the same memory location. Only one member can hold a value at any given time. It is defined using the union keyword.
C union Data { int i; float f; char ch; };

Differences Between Structure and Union

Structure (struct)
  • Each member has its own separate memory location
  • Size = sum of sizes of all members
  • All members can be accessed simultaneously
  • Changing one member does not affect others
  • Uses keyword struct
Union (union)
  • All members share the same memory location
  • Size = size of the largest member
  • Only one member can hold a value at a time
  • Changing one member overwrites others
  • Uses keyword union
C Structure: sizeof = 4 + 4 + 1 = 9 (approx, with padding) struct S { int a; float b; char c; }; Union: sizeof = 4 (size of largest member = float/int) union U { int a; float b; char c; };
10

What is a structure? How are members accessed? Explain with example.

Definition A structure is a composite user-defined data type that groups related variables of different types under one name. Each variable within a structure is called a member.

Accessing Members of a Structure

Members of a structure are accessed using the dot (.) operator, also called the member access operator.

Syntax: structure_variable.member_name

If a structure pointer is used, the arrow (→) operator is used instead: pointer_variable->member_name

C #include <stdio.h> #include <string.h> struct Student { char name[50]; int roll; float marks; }; void main() { struct Student s1; Assigning values using dot operator strcpy(s1.name, "Ram Sharma"); s1.roll = 101; s1.marks = 85.5; Accessing values using dot operator printf("Name: %s\n", s1.name); printf("Roll: %d\n", s1.roll); printf("Marks: %.1f\n", s1.marks); }
Output Name: Ram Sharma Roll: 101 Marks: 85.5
11

What is a pointer? How are pointers declared in C program? How are they accessed in a program?

Definition A pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, it "points to" the location where the data is stored in memory.

Declaration of Pointers

Syntax: data_type *pointer_name;

The * (asterisk) indicates that the variable is a pointer, not a regular variable.

C int *ptr; pointer to integer float *fptr; pointer to float char *cptr; pointer to character double *dptr; pointer to double

Accessing Pointers — Two Key Operators

  • & (Address-of operator): Returns the memory address of a variable. Used to assign an address to a pointer.
  • * (Dereference/Indirection operator): Accesses the value stored at the address held by a pointer.
C #include <stdio.h> void main() { int num = 42; int *ptr; Declaration ptr = &num; Assign address of num to ptr printf("Value of num: %d\n", num); 42 printf("Address of num: %p\n", &num); e.g., 0x7ffd... printf("Value in ptr: %p\n", ptr); same address printf("Value pointed by ptr: %d\n", *ptr); 42 *ptr = 100; Modify value via pointer printf("New value of num: %d\n", num); 100 }
Output Value of num: 42 Address of num: 0x7ffd4a3b2c18 Value in ptr: 0x7ffd4a3b2c18 Value pointed by ptr: 42 New value of num: 100
12

What is a data file? Write the differences between sequential and random data files.

Definition A data file is a collection of related data stored on a secondary storage device (like a hard disk). Files are used for permanent storage of data that can be read, written, or manipulated by programs using file handling functions.

Differences Between Sequential and Random (Direct-Access) Files

Sequential File
  • Data is read/written in order, from beginning to end
  • To access the nth record, all previous n-1 records must be traversed
  • Slower for accessing specific records
  • Simpler to implement
  • Best suited for batch processing
  • Used with fgetc(), fgets(), fscanf(), etc.
Random (Direct-Access) File
  • Data can be accessed at any position directly
  • Uses fseek() to jump to a specific record
  • Faster for accessing specific records
  • More complex implementation
  • Best suited for database-type operations
  • Used with fread(), fwrite(), fseek(), ftell()
📝

Long Answer Questions Questions 1 – 8 · Detailed explanations with programs and examples

1
What is an array? Describe the use of an array in a program with examples.
Definition An array is a collection of elements of the same data type stored in contiguous (adjacent) memory locations. Each element is accessed using an index (subscript) starting from 0.

Key Characteristics of Arrays

  • All elements must be of the same data type.
  • Elements are stored in contiguous memory.
  • Indexing starts from 0 (zero-based).
  • Random access is possible using the index — accessing any element takes constant time O(1).
  • The size of an array is fixed at the time of declaration.

Declaration and Initialization

C Declaration int marks[5]; Array of 5 integers float salary[10]; Array of 10 floats char name[20]; Array of 20 characters Initialization int marks[5] = {80, 90, 75, 85, 95}; Accessing elements marks[0] First element → 80 marks[4] Last element → 95

Types of Arrays

  • One-Dimensional (1D) Array: A linear array with a single row of elements.
  • Two-Dimensional (2D) Array: A matrix-like array with rows and columns (array of arrays).
  • Multi-Dimensional Array: Arrays with three or more dimensions.

Complete Program Example: Store and Display Student Marks

C #include <stdio.h> void main() { int marks[5]; int i, total = 0; float average; Input marks printf("Enter marks of 5 students:\n"); for (i = 0; i < 5; i++) { printf("Student %d: ", i + 1); scanf("%d", &marks[i]); total += marks[i]; } Calculate average average = total / 5.0; Display results printf("\nMarks: "); for (i = 0; i < 5; i++) { printf("%d ", marks[i]); } printf("\nTotal = %d", total); printf("\nAverage = %.2f", average); }
Sample Output Enter marks of 5 students: Student 1: 80 Student 2: 90 Student 3: 75 Student 4: 85 Student 5: 95 Marks: 80 90 75 85 95 Total = 425 Average = 85.00

2D Array Example: Matrix Addition

C #include <stdio.h> void main() { int a[2][2] = {{1, 2}, {3, 4}}; int b[2][2] = {{5, 6}, {7, 8}}; int sum[2][2]; int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { sum[i][j] = a[i][j] + b[i][j]; } } printf("Sum Matrix:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("%d\t", sum[i][j]); } printf("\n"); } }
Output Sum Matrix: 6 8 10 12
2
What is a function? Write its importance. Can a C program be written without a function? Explain.
Definition A function is a self-contained, reusable block of code that performs a specific task. It takes input (parameters), processes it, and optionally returns an output. Functions help in breaking a large program into smaller, manageable modules.

Components of a Function

  • Function declaration (prototype): Tells the compiler about the function's name, return type, and parameters.
  • Function definition: Contains the actual code (body) of the function.
  • Function call: Invokes the function from another part of the program.
C 1. Function Declaration (Prototype) int add(int, int); 2. Function Definition int add(int a, int b) { return a + b; } void main() { 3. Function Call int result = add(10, 20); printf("Sum = %d", result); }

Types of Functions

  • Library functions: Pre-defined (e.g., printf(), scanf(), sqrt())
  • User-defined functions: Created by the programmer

Importance of Functions

  • Modularity: Breaks a complex program into smaller, logical units.
  • Code reusability: A function can be called multiple times without rewriting code.
  • Easier debugging: Each function can be tested independently.
  • Readability: Well-named functions make code self-documenting.
  • Maintainability: Changes in one function don't affect others (if well-designed).
  • Collaboration: Different programmers can work on different functions simultaneously.
  • Abstraction: Users can call functions without knowing the internal implementation.

Can a C Program Be Written Without a Function?

Important Concept Technically, no. Every C program must have at least one function — the main() function. It is the entry point of program execution. Without main(), the compiler will not compile the program (or it won't execute properly).

However, it is possible to write a C program without any user-defined function other than main(). The entire logic can be placed inside main(). But this is not recommended for larger programs because:

  • The code becomes long and difficult to manage.
  • Debugging becomes harder.
  • Code reusability is lost.
  • The program loses its modular structure.
C – Without User-Defined Function #include <stdio.h> void main() { int a = 10, b = 20; printf("Sum = %d", a + b); No separate function used }

So while we can avoid user-defined functions, using them is always the best practice for writing clean, organized, and maintainable code.

3
What is a recursive function? Explain how does it work with an example.
Definition A recursive function is a function that calls itself either directly or indirectly. Recursion is a powerful technique where a complex problem is solved by breaking it down into smaller, identical sub-problems until a base case (terminating condition) is reached.

Two Essential Components of Recursion

1
Base Case The condition under which the function stops calling itself. Without a base case, recursion leads to infinite calls and a stack overflow error.
2
Recursive Case The part where the function calls itself with a modified argument, moving towards the base case.

Example: Factorial of a Number

The factorial of a number n (denoted as $n!$) is defined as:

n!=n×(n−1)×(n−2)×…×2×1n! = n \times (n-1) \times (n-2) \times \ldots \times 2 \times 1 0!=1 (base case)0! = 1 \text{ (base case)} n!=n×(n−1)! (recursive definition)n! = n \times (n-1)! \text{ (recursive definition)}
C – Factorial Using Recursion #include <stdio.h> int factorial(int n) { if (n == 0 || n == 1) Base case return 1; else return n * factorial(n - 1); Recursive call } void main() { int n = 5; printf("Factorial of %d = %d", n, factorial(n)); }
Output Factorial of 5 = 120

How Recursion Works — Step-by-Step Trace

When factorial(5) is called:

1
factorial(5) 5 ≠ 0, so → return 5 × factorial(4)
2
factorial(4) 4 ≠ 0, so → return 4 × factorial(3)
3
factorial(3) 3 ≠ 0, so → return 3 × factorial(2)
4
factorial(2) 2 ≠ 0, so → return 2 × factorial(1)
5
factorial(1) 1 == 1 → Base case reached! Returns 1.

Now the results unwind back through the call stack:

Unwinding:
factorial(1) = 1
factorial(2) = 2 × 1 = 2
factorial(3) = 3 × 2 = 6
factorial(4) = 4 × 6 = 24
factorial(5) = 5 × 24 = 120

Another Example: Fibonacci Series Using Recursion

C #include <stdio.h> int fibonacci(int n) { if (n <= 0) return 0; Base case 1 if (n == 1) return 1; Base case 2 return fibonacci(n - 1) + fibonacci(n - 2); Recursive } void main() { printf("Fibonacci Series: "); for (int i = 0; i < 8; i++) { printf("%d ", fibonacci(i)); } }
Output Fibonacci Series: 0 1 1 2 3 5 8 13
4
What is a structure? How are members accessed? Explain with example.
Definition A structure (struct) is a user-defined composite data type in C that allows grouping of variables of different data types into a single logical unit. Each variable inside a structure is called a member or field.

Defining a Structure

Syntax:

C struct structure_name { data_type member1; data_type member2; data_type member3; ... more members };

Declaring Structure Variables

C Method 1: After structure definition struct Employee { char name[50]; int id; float salary; }; struct Employee emp1, emp2; Method 2: Along with structure definition struct Point { int x, y; } p1, p2;

Accessing Structure Members

There are two ways to access structure members:

  • Dot (.) operator: Used with structure variables — variable.member
  • Arrow (→) operator: Used with structure pointers — pointer->member

Complete Program Example

C #include <stdio.h> #include <string.h> struct Employee { char name[50]; int id; float salary; }; void display(struct Employee e) { printf("ID: %d\n", e.id); printf("Name: %s\n", e.name); printf("Salary: Rs.%.2f\n", e.salary); } void main() { struct Employee emp1; Assigning values using dot operator emp1.id = 1001; strcpy(emp1.name, "Sita Rai"); emp1.salary = 55000.00; Passing structure to function display(emp1); Using pointer to access members struct Employee *ptr = &emp1; printf("\nUsing pointer → Salary: Rs.%.2f\n", ptr->salary); }
Output ID: 1001 Name: Sita Rai Salary: Rs.55000.00 Using pointer → Salary: Rs.55000.00

Reading Structure Members via scanf()

C void main() { struct Employee e; printf("Enter ID: "); scanf("%d", &e.id); printf("Enter Name: "); scanf("%s", e.name); printf("Enter Salary: "); scanf("%f", &e.salary); printf("\n%d %s %.2f", e.id, e.name, e.salary); }
5
How is an array of structure defined? Explain how it is used in a program with an example.
Definition An array of structures is an array where each element is a structure variable. It allows storing multiple records (each with multiple fields) in a systematic way — similar to a table with rows and columns.

Declaration of Array of Structure

C struct Student { char name[50]; int roll; float marks; }; Array of structures: 5 students struct Student students[5];

Accessing Elements

Use the array index with the dot operator: students[i].member

  • students[0].name — Name of the first student
  • students[0].roll — Roll number of the first student
  • students[2].marks — Marks of the third student

Complete Program: Store and Display Student Records

C #include <stdio.h> struct Student { char name[50]; int roll; float marks; }; void main() { struct Student s[3]; int i; Input data for 3 students for (i = 0; i < 3; i++) { printf("\n--- Student %d ---\n", i + 1); printf("Enter name: "); scanf("%s", s[i].name); printf("Enter roll: "); scanf("%d", &s[i].roll); printf("Enter marks: "); scanf("%f", &s[i].marks); } Display all records printf("\n%-10s %-8s %-8s\n", "Name", "Roll", "Marks"); printf("-------------------------\n"); for (i = 0; i < 3; i++) { printf("%-10s %-8d %-8.2f\n", s[i].name, s[i].roll, s[i].marks); } Find highest marks int maxIdx = 0; for (i = 1; i < 3; i++) { if (s[i].marks > s[maxIdx].marks) maxIdx = i; } printf("\nHighest: %s with %.2f marks\n", s[maxIdx].name, s[maxIdx].marks); }
Sample Output --- Student 1 --- Enter name: Ram Enter roll: 1 Enter marks: 85.5 --- Student 2 --- Enter name: Sita Enter roll: 2 Enter marks: 92.0 --- Student 3 --- Enter name: Hari Enter roll: 3 Enter marks: 78.5 Name Roll Marks ------------------------- Ram 1 85.50 Sita 2 92.00 Hari 3 78.50 Highest: Sita with 92.00 marks
6
What are the possible operations that can be performed on a pointer? Explain.
Overview Pointers in C are powerful tools that enable direct memory manipulation. The following operations can be performed on pointers:

1. Pointer Declaration

Declaring a pointer to store the address of a variable of a specific type.

C int *ptr; Pointer to integer float *fptr; Pointer to float char *cptr; Pointer to char

2. Address Assignment (Initialization)

Storing the address of a variable using the & operator.

C int x = 10; int *ptr = &x; ptr now holds the address of x

3. Dereferencing (Accessing Value)

Reading or modifying the value at the address stored in a pointer using the * operator.

C int value = *ptr; Read: value = 10 *ptr = 20; Modify: x is now 20

4. Pointer Arithmetic

Performing arithmetic operations on pointers. When you add/subtract an integer to a pointer, it moves by n × sizeof(data_type) bytes.

C int arr[] = {10, 20, 30, 40}; int *ptr = arr; Points to arr[0] ptr++; Now points to arr[1] (20) ptr--; Back to arr[0] (10) ptr = ptr + 2; Now points to arr[2] (30) Pointer subtraction: number of elements between two pointers int diff = &arr[3] - &arr[0]; diff = 3

5. Pointer Comparison

Two pointers can be compared using relational operators (==, !=, <, >).

C int *p1 = &arr[0]; int *p2 = &arr[2]; if (p1 < p2) printf("p1 points to an earlier element");

6. Pointer to Pointer (Double Pointer)

A pointer that stores the address of another pointer.

C int x = 100; int *p = &x; p → x int **pp = &p; pp → p → x printf("%d", **pp); Output: 100

7. Pointer and Array Relationship

An array name acts as a pointer to its first element.

C int arr[] = {5, 10, 15}; int *ptr = arr; All these access the same element (arr[0]): printf("%d", arr[0]); 5 printf("%d", *arr); 5 printf("%d", *ptr); 5 printf("%d", *(ptr + 1)); 10 (arr[1]) printf("%d", ptr[2]); 15 (arr[2])

8. Passing Pointers to Functions

Pointers allow functions to modify the original variable (pass by reference).

C void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void main() { int x = 5, y = 10; swap(&x, &y); printf("x=%d, y=%d", x, y); x=10, y=5 }

9. Returning Pointer from Function

C int* getMax(int *a, int *b) { if (*a > *b) return a; else return b; }

10. Null Pointer

A pointer that does not point to any valid memory location.

C int *ptr = NULL; Null pointer if (ptr == NULL) printf("Pointer does not point to anything.");
7
Explain the ways to pass pointers as arguments to a function.
Overview In C, arguments can be passed to functions in two main ways: Pass by Value and Pass by Reference (using pointers). Pointers enable functions to modify the original variables in the calling function.

1. Pass by Value

A copy of the argument's value is passed to the function. Changes inside the function do not affect the original variable.

C #include <stdio.h> void changeValue(int x) { x = 100; Changes only the local copy printf("Inside function: x = %d\n", x); } void main() { int a = 10; changeValue(a); printf("After function call: a = %d\n", a); }
Output Inside function: x = 100 After function call: a = 10 ← Original unchanged!

2. Pass by Reference (Using Pointers)

The address of the variable is passed to the function. The function can directly access and modify the original variable through the pointer.

C #include <stdio.h> void changeValue(int *ptr) { *ptr = 100; Modifies the original variable printf("Inside function: *ptr = %d\n", *ptr); } void main() { int a = 10; changeValue(&a); Pass address of a printf("After function call: a = %d\n", a); }
Output Inside function: *ptr = 100 After function call: a = 100 ← Original modified!

3. Swapping Two Numbers Using Pointers

C #include <stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void main() { int x = 25, y = 50; printf("Before swap: x=%d, y=%d\n", x, y); swap(&x, &y); printf("After swap: x=%d, y=%d\n", x, y); }
Output Before swap: x=25, y=50 After swap: x=50, y=25

4. Passing Array to Function Using Pointer

When an array is passed to a function, it is automatically passed as a pointer to its first element.

C #include <stdio.h> int sumArray(int *arr, int size) { int total = 0; for (int i = 0; i < size; i++) { total += arr[i]; or *(arr + i) } return total; } void main() { int numbers[] = {10, 20, 30, 40, 50}; int result = sumArray(numbers, 5); printf("Sum = %d", result); 150 }

5. Passing Structure Pointer to Function

C #include <stdio.h> #include <string.h> struct Student { char name[50]; int marks; }; void updateMarks(struct Student *s, int newMarks) { s->marks = newMarks; Arrow operator for pointer } void main() { struct Student stu; strcpy(stu.name, "Ram"); stu.marks = 75; updateMarks(&stu, 90); printf("%s: %d", stu.name, stu.marks); Ram: 90 }

Summary of Ways to Pass Pointers

  • Pass variable's address: function(&variable) — allows modifying the original variable.
  • Pass array name: function(arrayName) — automatically passes pointer to first element.
  • Pass pointer variable: function(pointer) — passes an already-declared pointer.
  • Pass structure address: function(&structVar) — allows modifying structure members via →.
8
List the different file modes with their purposes.
Definition File modes specify the purpose for which a file is opened. They are passed as the second argument to the fopen() function. The mode determines whether the file will be read from, written to, appended to, or a combination.

Text File Modes

Mode Description File Must Exist? Can Read? Can Write? Position
"r" Open for reading only Yes ✓ ✗ Beginning
"w" Open for writing only. Creates a new file or truncates (empties) existing file. No (created) ✗ ✓ Beginning
"a" Open for appending. Data is added at the end. Creates file if not exists. No (created) ✗ ✓ End
"r+" Open for both reading and writing. File must exist. Yes ✓ ✓ Beginning
"w+" Open for writing and reading. Creates or truncates file. No (created) ✓ ✓ Beginning
"a+" Open for appending and reading. Creates file if not exists. No (created) ✓ ✓ End

Binary File Modes

Mode Description
"rb" Open binary file for reading
"wb" Open binary file for writing (creates/truncates)
"ab" Open binary file for appending
"rb+" Open binary file for reading and writing
"wb+" Open binary file for writing and reading (creates/truncates)
"ab+" Open binary file for appending and reading

Program Examples

Writing to a File

C #include <stdio.h> void main() { FILE *fp; fp = fopen("data.txt", "w"); Write mode if (fp == NULL) { printf("Error opening file!\n"); } else { fprintf(fp, "Hello, World!\n"); fprintf(fp, "Grade 12 Computer Science\n"); fclose(fp); printf("Data written successfully.\n"); } }

Reading from a File

C #include <stdio.h> void main() { FILE *fp; char line[100]; fp = fopen("data.txt", "r"); Read mode if (fp == NULL) { printf("File not found!\n"); } else { while (fgets(line, 100, fp) != NULL) { printf("%s", line); } fclose(fp); } }

Appending to a File

C #include <stdio.h> void main() { FILE *fp; fp = fopen("data.txt", "a"); Append mode if (fp != NULL) { fprintf(fp, "Appended line.\n"); fclose(fp); } }

Common File Handling Functions

Function Purpose
fopen()Opens a file and returns a FILE pointer
fclose()Closes an opened file
fprintf()Writes formatted data to a file
fscanf()Reads formatted data from a file
fgetc()Reads a single character from a file
fputc()Writes a single character to a file
fgets()Reads a string/line from a file
fputs()Writes a string to a file
fread()Reads binary data from a file
fwrite()Writes binary data to a file
fseek()Moves the file pointer to a specific position
ftell()Returns the current position of the file pointer
feof()Checks if End-of-File has been reached
rewind()Moves the file pointer to the beginning
Best Practice Always check if fopen() returns NULL before performing any file operation. This prevents runtime errors caused by missing files or permission issues. Always close files using fclose() after operations are complete.
↑

Frequently asked questions

What is Programming in C about?

This chapter provides a comprehensive guide to programming in C, covering fundamental concepts like data types, operators, and control structures. It delves into advanced topics such as functions, pointers, structures, unions, and file handling, offering detailed explanations and examples for each.

Which topics are covered in Programming in C?

Class 12 Computer Science “Programming in C” covers: Data Types (basic, derived, user-defined); Operators (arithmetic, logical, bitwise); Control Structures (if-else, switch, loops); Functions (library, user-defined, recursion); Pointers (declaration, dereferencing, arithmetic); Structures and Unions; File Handling (sequential, random access); Arrays (1D, 2D).

What should I focus on in Programming in C for the exam?

Students should focus on understanding the syntax and practical application of C programming concepts, especially pointers, structures, and control flow, as these are frequently tested with coding problems and theoretical questions.

What are the key formulas or definitions in Programming in C?

Identifier Naming Rules: Must start with a letter or underscore, can contain letters, digits, underscores. Cannot be a keyword.; Structure Size: Sum of sizes of all members (with potential padding).; Union Size: Size of the largest member.; Pointer Declaration: data_type *pointer_name;; Array Indexing: Starts from 0..

Where can I read the Class 12 Computer Science “Programming in C” solutions?

Right on this page. They are free and you do not need to sign up. For chapter quizzes and the AI tutor, install the Sikshya Plus app.

Study tips

Free for Class 9 to 12

Do not just read it. Practice it.

You have read the solutions for Programming in C. Now test yourself, ask the AI tutor and keep your streak going.

Sikshya Plus chapter quiz screen with class, subject and difficulty options
Sikshya AI personal tutor chat inside the app
Sikshya Plus AI tools screen: question assistant, summarizer, translator, grammar checker
Chapter list with Past Q, materials, posts and books tabs
  • AI quizzes for this chapterTest yourself with instant feedback and explanations after every answer.
  • AI tutor, free, 24/7Stuck on a question? Ask in your own words and get a step-by-step explanation.
  • 14 AI tools in one appSummarizer, grammar checker, flashcards, essay help, math solver and more.
  • Past questions and notesPast papers and your own notes organized chapter by chapter.
Download free on Google Play Scan with your phone to install