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)
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 XIIMultiple Choice Questions Questions 1 – 20 · Select the correct option
Which is NOT the basic data type in C?
Which is the user-defined data type in C?
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.
The %d format specifier is used for:
%d is the format specifier for printing/reading a signed decimal integer. For reference: %c → character, %s → string, %f → float, %lf → double.
a++ is equivalent to:
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).
Which is NOT the formatted function?
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."
What is the output of the below code?
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).
Which of the following is the logical AND operator?
&& 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.
Which of the derived data type stores collection of different data types?
A function which calls itself is called …………
The size of the union is equal to:
scanf("%[^\n]s", ch); refers to:
%[^\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.
A file mode which is used to open an existing data file for both reading and writing purpose:
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.
Which function in C reads a single character from a file at a time?
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.
Which is the proper declaration of an integer pointer?
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.
The memory size occupied by a structure is:
A function can return ………… value or values to the calling function module.
return statement. To "return" multiple values, programmers use pointers, arrays, or structures as workarounds — but the function itself returns a single value.
Automatic variable is a variable that is:
auto keyword is optional — it is the default for variables inside a function.
The variable declaration with no storage class specified is by default …………
auto). Its scope is limited to the block in which it is declared, and it is destroyed when the block exits.
A compiler cannot detect ………… error.
The && and || operators are used to:
&& (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
What is an identifier? Write the rules for naming identifiers.
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, andAGEare 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.,
totalMarksis better thantm).
What is an operator? List the operators in arithmetic operator.
Arithmetic Operators in C
| Operator | Name | Description | Example |
|---|---|---|---|
+ | Addition | Adds two operands | a + b |
- | Subtraction | Subtracts second from first | a - b |
* | Multiplication | Multiplies two operands | a * b |
/ | Division | Divides first by second | a / b |
% | Modulus | Returns the remainder | a % b |
/ 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.
What is a loop? Explain the different looping statements used in C program.
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.
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.
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.
What is a control structure? Explain shortly about if statement and switch…case statement.
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).
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.
- The expression in
switchmust evaluate to an integer or character type. - Each
caselabel must be a unique constant. - The
breakstatement prevents fall-through to subsequent cases. - The
defaultcase executes when no case matches (optional).
Define library function and user-defined function.
Library Function (Built-in Function)
- 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
- 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.
What is an argument? How does it differ from a parameter? Explain.
Argument (Actual Parameter)
Parameter (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
What is a storage class? Define automatic and external variable with examples.
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
autokeyword is optional — it is the default storage class for local variables.
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
externkeyword is used to declare a variable that is defined in another file or later in the same file.
What is a structure? Write the advantages of structure.
struct keyword.
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.
What is a union? Write the differences between union and structure.
union keyword.
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
What is a structure? How are members accessed? Explain with example.
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
What is a pointer? How are pointers declared in C program? How are they accessed in a program?
Declaration of Pointers
Syntax: data_type *pointer_name;
The * (asterisk) indicates that the variable is a pointer, not a regular variable.
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.
What is a data file? Write the differences between sequential and random data files.
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.
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
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
2D Array Example: Matrix Addition
2
What is a function? Write its importance. Can a C program be written without a function? Explain.
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.
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?
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.
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.
Two Essential Components of Recursion
Example: Factorial of a Number
The factorial of a number n (denoted as $n!$) is defined as:
How Recursion Works — Step-by-Step Trace
When factorial(5) is called:
Now the results unwind back through the call stack:
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
4
What is a structure? How are members accessed? Explain with example.
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:
Declaring Structure Variables
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
Reading Structure Members via scanf()
5
How is an array of structure defined? Explain how it is used in a program with an example.
Declaration of Array of Structure
Accessing Elements
Use the array index with the dot operator: students[i].member
students[0].name— Name of the first studentstudents[0].roll— Roll number of the first studentstudents[2].marks— Marks of the third student
Complete Program: Store and Display Student Records
6
What are the possible operations that can be performed on a pointer? Explain.
1. Pointer Declaration
Declaring a pointer to store the address of a variable of a specific type.
2. Address Assignment (Initialization)
Storing the address of a variable using the & operator.
3. Dereferencing (Accessing Value)
Reading or modifying the value at the address stored in a pointer using the * operator.
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.
5. Pointer Comparison
Two pointers can be compared using relational operators (==, !=, <, >).
6. Pointer to Pointer (Double Pointer)
A pointer that stores the address of another pointer.
7. Pointer and Array Relationship
An array name acts as a pointer to its first element.
8. Passing Pointers to Functions
Pointers allow functions to modify the original variable (pass by reference).
9. Returning Pointer from Function
10. Null Pointer
A pointer that does not point to any valid memory location.
7
Explain the ways to pass pointers as arguments to a 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.
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.
3. Swapping Two Numbers Using Pointers
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.
5. Passing Structure Pointer to Function
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.
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
Reading from a File
Appending to a File
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 |
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
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.




- 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.