Unit 2: Principles of programming - Subjective Questions
CAP1008 — C Programming • Practice Questions with Detailed Answers
20 questions
Explain the basic structure of a C program with the help of a suitable example. Describe each section briefly.
A C program is organized into several well-defined sections that give it a standard structure.
Sections of a C program:
- Documentation section: Comments describing the program (
/* ... */or// ...). - Link section (Preprocessor directives): Includes header files, e.g.
#include <stdio.h>. - Definition section: Defines symbolic constants using
#define. - Global declaration section: Declares global variables and function prototypes.
main()function section: The entry point of every C program. Execution begins here.- Subprogram section: User-defined functions.
Example:
#include <stdio.h> // Link section
#define PI 3.14 // Definition section
int area(int r); // Global declaration
int main() { // main function
int r = 5;
printf("Area = %d", area(r));
return 0;
}
int area(int r) { // Subprogram section
return PI * r * r;
}Every C program must contain a main() function, which is where execution starts and typically ends.
What is a character set in C? Describe the different categories of characters used in the C language.
The character set in C refers to the set of valid characters that can be used to write a C program. The compiler recognizes only these characters.
Categories of the C character set:
- Letters (Alphabets): Uppercase
A–Zand lowercasea–z. - Digits:
0to9. - Special characters: Symbols such as
+ - * / % = ( ) { } [ ] ; : , . ' " ! & | < > # ? _etc. - White space characters: Blank space, horizontal tab, vertical tab, newline, and carriage return.
These characters are combined to form tokens such as keywords, identifiers, constants, and operators, which are the building blocks of a C program.
Define identifiers and keywords. State the rules for constructing valid identifiers in C.
Identifiers: Names given by the programmer to program elements such as variables, functions, arrays, and structures.
Keywords: Reserved words that have a predefined meaning in the C language and cannot be used as identifiers. C has 32 keywords such as int, float, if, else, while, return, for, void, etc.
Rules for constructing valid identifiers:
- The first character must be a letter or an underscore (
_). - Subsequent characters may be letters, digits, or underscores.
- Keywords cannot be used as identifiers.
- No special characters (except underscore) or spaces are allowed.
- C is case-sensitive, so
Sumandsumare different. - The name should ideally be meaningful.
Examples:
- Valid:
total,_count,num1,student_age - Invalid:
1num,float,total sum,roll#no
Distinguish between constants and variables. Explain the different types of constants in C with examples.
Variable: A named memory location whose value can change during program execution, e.g. int x = 10; where x can later be reassigned.
Constant: A fixed value that does not change during program execution.
Difference:
| Basis | Constant | Variable |
|---|---|---|
| Value | Fixed | Can change |
| Declaration | const / #define |
Data type declaration |
| Example | const int a = 5; |
int a = 5; |
Types of constants in C:
- Integer constant: Whole numbers, e.g.
100,-25. - Real/Floating-point constant: Numbers with decimals, e.g.
3.14,2.5e3. - Character constant: A single character in single quotes, e.g.
'A','5'. - String constant: A sequence of characters in double quotes, e.g.
"Hello".
Constants can be defined using #define PI 3.14 or the const keyword: const float pi = 3.14;.
Explain the primary (basic) data types available in C along with their typical size and range.
Data types specify the type of data a variable can hold and how much memory it occupies.
Primary (basic) data types in C:
int: Stores integers. Typically 2 or 4 bytes. Range (4 bytes): to .char: Stores a single character. 1 byte. Range: to .float: Stores single-precision floating-point numbers. 4 bytes. Range approx to .double: Stores double-precision floating-point numbers. 8 bytes. Larger range and precision thanfloat.void: Represents "no value". Used for functions returning nothing and generic pointers.
Note: Sizes may vary depending on the compiler and machine architecture. The sizeof operator can be used to find the exact size, e.g. sizeof(int).
Differentiate between formatted and unformatted I/O functions in C with examples.
Formatted I/O functions allow input and output of data in a specific format using format specifiers.
- Examples:
printf(),scanf(). - They use format specifiers like
%d,%f,%c,%s. - Can handle multiple values of different data types at once.
- Example:
scanf("%d %f", &a, &b);andprintf("%d %f", a, b);
Unformatted I/O functions deal with input/output of single characters or strings without any format specifiers.
- Examples:
getchar(),putchar(),gets(),puts(). - They work only with characters and strings.
- Faster and simpler but less flexible.
- Example:
ch = getchar();andputchar(ch);
Key difference: Formatted functions offer control over data format and support mixed data types, whereas unformatted functions handle raw character/string data without formatting.
Explain the working of printf() and scanf() functions with syntax, format specifiers, and examples.
printf() function: Used to display output on the screen in a formatted manner.
- Syntax:
printf("format string", arg1, arg2, ...); - The format string contains text and format specifiers.
- Example:
printf("Sum = %d", sum);
scanf() function: Used to read formatted input from the keyboard.
- Syntax:
scanf("format string", &arg1, &arg2, ...); - Requires the address (&) of variables.
- Example:
scanf("%d %f", &age, &salary);
Common format specifiers:
| Specifier | Data Type |
|---|---|
%d |
Integer |
%f |
Float |
%c |
Character |
%s |
String |
%lf |
Double |
%x |
Hexadecimal |
Complete example:
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d", num);The & operator in scanf() passes the memory address so the input value can be stored in the variable.
Describe the functions puts(), gets(), getchar(), and putchar() with their syntax and examples.
These are unformatted I/O functions used for handling characters and strings.
-
getchar(): Reads a single character from the keyboard.- Syntax:
ch = getchar(); - Example:
char c = getchar();
- Syntax:
-
putchar(): Displays a single character on the screen.- Syntax:
putchar(ch); - Example:
putchar(c);
- Syntax:
-
gets(): Reads a string (including spaces) from the keyboard until Enter is pressed.- Syntax:
gets(str); - Example:
gets(name);
- Syntax:
-
puts(): Displays a string on the screen followed by a newline.- Syntax:
puts(str); - Example:
puts(name);
- Syntax:
Example program:
#include <stdio.h>
int main() {
char name[50];
puts("Enter your name:");
gets(name);
puts("Hello,");
puts(name);
return 0;
}Note: gets() is unsafe because it does not check array bounds and can cause buffer overflow; fgets() is preferred in modern C.
What is an expression in C? Explain the different types of expressions with examples.
An expression in C is a combination of operands (variables, constants) and operators that evaluates to a single value.
Types of expressions:
- Arithmetic expression: Uses arithmetic operators.
- Example:
a + b * c
- Example:
- Relational expression: Compares two values, returns true/false.
- Example:
a > b
- Example:
- Logical expression: Combines conditions using logical operators.
- Example:
(a > b) && (c < d)
- Example:
- Assignment expression: Assigns a value to a variable.
- Example:
x = a + b
- Example:
- Conditional expression: Uses the ternary operator.
- Example:
max = (a > b) ? a : b
- Example:
- Bitwise expression: Operates at the bit level.
- Example:
a & b
- Example:
Every expression produces a result value, which can be stored in a variable or used in further operations.
Explain the arithmetic operators in C. Discuss integer arithmetic, real arithmetic, and mixed-mode arithmetic with examples.
Arithmetic operators perform mathematical operations on operands.
| Operator | Meaning | Example |
|---|---|---|
+ |
Addition | a + b |
- |
Subtraction | a - b |
* |
Multiplication | a * b |
/ |
Division | a / b |
% |
Modulus (remainder) | a % b |
Integer arithmetic: When both operands are integers, the result is an integer. Division truncates the fractional part.
- Example:
7 / 2 = 3,7 % 2 = 1
Real (floating-point) arithmetic: When operands are real numbers, results include decimals. The % operator cannot be used with float.
- Example:
7.0 / 2.0 = 3.5
Mixed-mode arithmetic: When one operand is integer and the other is real, the integer is converted to real (implicit conversion) and the result is real.
- Example:
7 / 2.0 = 3.5
Understanding these rules is important to avoid unexpected truncation of results.
What are unary operators? Explain increment and decrement operators, distinguishing between prefix and postfix forms with examples.
Unary operators operate on a single operand.
Common unary operators: + (unary plus), - (unary minus), ++ (increment), -- (decrement), ! (logical NOT), sizeof, & (address-of).
Increment (++) and Decrement (--) operators:
- Increment adds 1 to the operand.
- Decrement subtracts 1 from the operand.
Prefix form (++a): The value is changed first, then used.
int a = 5;
int b = ++a; // a = 6, b = 6Postfix form (a++): The value is used first, then changed.
int a = 5;
int b = a++; // b = 5, a = 6Summary:
- Prefix: modify then use.
- Postfix: use then modify.
When used as a standalone statement (a++; or ++a;), both produce the same result.
Explain relational operators in C. Write a program to demonstrate their use.
Relational operators are used to compare two values or expressions. They return 1 (true) or 0 (false).
| Operator | Meaning | Example |
|---|---|---|
< |
Less than | a < b |
> |
Greater than | a > b |
<= |
Less than or equal to | a <= b |
>= |
Greater than or equal to | a >= b |
== |
Equal to | a == b |
!= |
Not equal to | a != b |
Example program:
#include <stdio.h>
int main() {
int a = 10, b = 20;
printf("a > b : %d\n", a > b); // 0
printf("a < b : %d\n", a < b); // 1
printf("a == b: %d\n", a == b); // 0
printf("a != b: %d\n", a != b); // 1
return 0;
}Relational operators are commonly used in decision-making statements like if and loops.
Explain logical operators in C with truth tables and examples.
Logical operators are used to combine or negate conditions (relational expressions). They return 1 (true) or 0 (false).
Types:
- Logical AND (
&&): True only if both operands are true. - Logical OR (
||): True if at least one operand is true. - Logical NOT (
!): Reverses the truth value.
Truth tables:
| A | B | A && B | A \ | \ | B |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | ||
| 0 | 1 | ||||
| 1 | 0 | 0 | 1 | ||
| 1 | 1 | 1 | 1 |
| A | !A |
|---|---|
| 0 | 1 |
| 1 | 0 |
Example:
int a = 5, b = 10;
if (a > 0 && b > 0)
printf("Both positive");
if (a > 0 || b < 0)
printf("At least one condition true");Logical operators use short-circuit evaluation: in &&, if the first operand is false, the second is not evaluated; in ||, if the first is true, the second is skipped.
Explain the assignment operator and its shorthand (compound) forms in C with examples.
The assignment operator (=) assigns the value of the right-hand side expression to the left-hand side variable.
- Syntax:
variable = expression; - Example:
x = a + b;
Shorthand (compound) assignment operators combine an arithmetic operation with assignment, making code shorter.
| Operator | Example | Equivalent to |
|---|---|---|
+= |
a += b |
a = a + b |
-= |
a -= b |
a = a - b |
*= |
a *= b |
a = a * b |
/= |
a /= b |
a = a / b |
%= |
a %= b |
a = a % b |
Example:
int a = 10;
a += 5; // a = 15
a *= 2; // a = 30
a -= 10; // a = 20Advantages: Shorthand operators are more concise, improve readability, and can be slightly more efficient. C also allows multiple assignments: a = b = c = 0;.
Explain the conditional (ternary) operator in C with its syntax and an example program.
The conditional operator (also called the ternary operator) is the only operator in C that works on three operands. It provides a compact way to write simple if-else statements.
Syntax:
expression1 ? expression2 : expression3;expression1is a condition.- If it is true,
expression2is evaluated. - If it is false,
expression3is evaluated.
Example: Finding the larger of two numbers
#include <stdio.h>
int main() {
int a = 15, b = 25, max;
max = (a > b) ? a : b;
printf("Largest = %d", max); // Output: 25
return 0;
}Equivalent if-else:
if (a > b)
max = a;
else
max = b;The ternary operator makes the code shorter and is useful for simple conditional assignments.
Explain bitwise operators in C in detail. Illustrate each operator with an example.
Bitwise operators work at the bit level, operating directly on the binary representation of integers.
| Operator | Meaning |
|---|---|
& |
Bitwise AND |
\| |
Bitwise OR |
^ |
Bitwise XOR |
~ |
Bitwise NOT (Complement) |
<< |
Left shift |
>> |
Right shift |
Example: Let a = 12 () and b = 10 ().
- AND:
a & b= = 8 - OR:
a | b= = 14 - XOR:
a ^ b= = 6 - NOT:
~a= (inverts all bits) - Left shift:
a << 1= = 24 (multiplies by 2) - Right shift:
a >> 1= = 6 (divides by 2)
Key point: Left shift by bits multiplies by , and right shift by bits divides by . Bitwise operators are used in low-level programming, flags, masking, and optimization.
What is type conversion in C? Explain implicit and explicit type conversion with examples.
Type conversion is the process of converting a value from one data type to another. It is necessary when operations involve operands of different types.
1. Implicit Type Conversion (Type Promotion):
- Performed automatically by the compiler.
- The lower data type is automatically converted to the higher data type to avoid data loss.
- Conversion hierarchy:
char → int → float → double.
int a = 5;
float b = 2.0;
float c = a + b; // a is converted to float, c = 7.02. Explicit Type Conversion (Type Casting):
- Done manually by the programmer using the cast operator.
- Syntax:
(data_type) expression
float x = 7.5;
int y = (int) x; // y = 7 (fractional part discarded)
int a = 5, b = 2;
float res = (float) a / b; // res = 2.5Difference: Implicit conversion is automatic and safe (promotion), while explicit conversion is programmer-controlled and may cause data loss (demotion).
Explain type modifiers (qualifiers) in C. Describe signed, unsigned, short, and long with their effect on data types.
Type modifiers alter the meaning of the basic data types by changing their size or range (the set of values they can store).
Main type modifiers:
-
signed: Allows a variable to store both positive and negative values. This is the default forintandchar.signed intrange (4 bytes): to .
-
unsigned: Allows only non-negative values, doubling the positive range.unsigned intrange (4 bytes): to .
-
short: Reduces the storage size (usually 2 bytes forint).short intrange: to .
-
long: Increases the storage size for larger values.long inttypically 4 or 8 bytes;long long intat least 8 bytes.
Examples:
unsigned int count = 500;
long int population = 1000000L;
short int temp = -20;
signed char c = -50;These modifiers help optimize memory usage and select the appropriate range for a variable.
Explain operator precedence and associativity in C. Evaluate the expression a = 5 + 3 * 2 - 8 / 4 step by step.
Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first.
Operator associativity decides the order of evaluation when operators have the same precedence (left-to-right or right-to-left).
Precedence (high to low, partial):
()Parentheses*,/,%(left-to-right)+,-(left-to-right)- Relational
< > <= >= ==,!=&&,||=(right-to-left)
Step-by-step evaluation of a = 5 + 3 * 2 - 8 / 4:
- Multiplication and division first (left to right):
3 * 2 = 68 / 4 = 2
- Expression becomes:
5 + 6 - 2 - Addition and subtraction (left to right):
5 + 6 = 1111 - 2 = 9
- Finally assignment:
a = 9
Result: a = 9
Understanding precedence and associativity prevents logical errors and avoids the overuse of parentheses.
Write a complete C program to accept two integers from the user and display their sum, difference, product, quotient, and remainder. Explain the program with proper use of I/O and arithmetic operators.
This program demonstrates the use of formatted I/O functions (scanf, printf) and arithmetic operators.
Program:
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
printf("Difference = %d\n", a - b);
printf("Product = %d\n", a * b);
if (b != 0) {
printf("Quotient = %d\n", a / b);
printf("Remainder = %d\n", a % b);
} else {
printf("Division by zero not allowed\n");
}
return 0;
}Explanation:
#include <stdio.h>includes the standard I/O library.scanf("%d %d", &a, &b);reads two integers using the&(address-of) operator.- Arithmetic operators
+,-,*,/,%compute the results. - A check for
b != 0avoids division by zero, which would cause a runtime error. printf()displays each result with the%dformat specifier.
Sample output:
Enter two integers: 17 5
Sum = 22
Difference = 12
Product = 85
Quotient = 3
Remainder = 2
This program combines input, processing, and output — the core of any C program.
Explain the basic structure of a C program with the help of a suitable example. Describe each section briefly.
A C program is organized into several well-defined sections that give it a standard structure.
Sections of a C program:
- Documentation section: Comments describing the program (
/* ... */or// ...). - Link section (Preprocessor directives): Includes header files, e.g.
#include <stdio.h>. - Definition section: Defines symbolic constants using
#define. - Global declaration section: Declares global variables and function prototypes.
main()function section: The entry point of every C program. Execution begins here.- Subprogram section: User-defined functions.
Example:
#include <stdio.h> // Link section
#define PI 3.14 // Definition section
int area(int r); // Global declaration
int main() { // main function
int r = 5;
printf("Area = %d", area(r));
return 0;
}
int area(int r) { // Subprogram section
return PI * r * r;
}Every C program must contain a main() function, which is where execution starts and typically ends.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →