IA 1 & 2 Answer Keys
IA 1 & 2 Answer Keys
Definition:
An identifier is the name used to identify variables, functions, or other user-defined elements in
a program. It acts as a reference to memory locations for storing and retrieving data.
Rules:
Program Example:
#include <stdio.h>
int main() {
int studentAge = 20; // 'studentAge' is a valid identifier
float _percentage = 85.6; // '_percentage' is also valid
printf("Student's age is %d and percentage is %.2f\n", studentAge, _percentage);
return 0;
}
Concept:
If the user’s age is greater than or equal to 18, they are eligible to vote.
Program:
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
Steps:
1. Substitute a=5,b=10,c=3,d=2
2. a = 5, b = 10, c = 3, d = 2.
3. Simplify:
E=3⋅(5+10)3−2=3⋅5−2=13
Program:
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 3, d = 2;
int E = 3 * (a + b) / c - d;
printf("The value of E is: %d\n", E);
return 0;
}
Concept:
The sum of nn natural numbers is S=n(n+1)2, Using a loop, we add numbers from 1 to n.
Program:
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
printf("The sum of the first 10 natural numbers is: %d\n", sum);
return 0;
}
Section B
Tokens are the smallest building blocks of a C program. They are fundamental components that
the C compiler recognizes and uses to construct a program.
Types of Tokens in C
1. Keywords
Definition:
Keywords are predefined, reserved words in C, which have specific meanings to the compiler.
These words cannot be used as identifiers.
Examples:
auto, break, case, char, const, continue, default, do, double, else,
enum, extern, float, for, goto, if, int, long, register, return, short,
signed, sizeof, static, struct, switch, typedef, union, unsigned, void,
volatile, while
Example Program:
#include <stdio.h>
int main() {
int number = 10; // 'int' is a keyword
printf("Number is: %d\n", number);
return 0; // 'return' is also a keyword
}
2. Identifiers
Definition:
Identifiers are names assigned to variables, functions, arrays, or any user-defined elements. They
are created by the programmer and follow strict rules.
3. Constants
Definition:
Constants are fixed values that do not change during the execution of a program. They can be of
various types:
Types of Constants:
Example Program:
#include <stdio.h>
int main() {
const float PI = 3.14; // Constant declaration
printf("Value of PI is: %.2f\n", PI);
return 0;
}
4. Strings
Definition:
Strings are sequences of characters enclosed in double quotes (" "). They are stored as arrays of
characters in C.
Examples:
● "Hello, World!"
● "C Programming"
Example Program:
#include <stdio.h>
int main() {
char greeting[] = "Hello, World!";
printf("%s\n", greeting);
return 0;
}
5. Operators
Definition:
Operators are symbols that perform operations on variables and values.
Categories of Operators:
● Arithmetic Operators: +, -, *, /, %
● Relational Operators: ==, !=, >, <, >=, <=
● Logical Operators: &&, ||, !
● Bitwise Operators: &, |, ^, ~, <<, >>
● Assignment Operators: =, +=, -=, *=, /=
● Increment/Decrement Operators: ++, --
● Special Operators: sizeof, &, * (pointer-related)
Example Program:
#include <stdio.h>
int main() {
int a = 10, b = 20;
printf("Sum: %d\n", a + b); // Arithmetic operator
printf("Comparison: %d\n", a < b); // Relational operator
printf("Logical AND: %d\n", (a < b) && (b > 15)); // Logical operator
return 0;
}
6. Special Symbols
Definition:
These are special characters used in the syntax of the C program.
Examples:
Example Program:
#include <stdio.h>
int main() {
int array[5] = {1, 2, 3, 4, 5}; // Square brackets for array
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
return 0;
}
7. Punctuators
Definition:
Punctuators are symbols that mark the structure of a C program.
Common Punctuators in C:
Typecasting in C refers to converting a variable from one data type to another. It helps in
manipulating data by altering its type explicitly or implicitly during computations.
Types of Typecasting
● Definition:
Performed automatically by the compiler. Smaller data types (like int) are automatically
converted to larger data types (like float) to prevent data loss during operations.
Example:
#include <stdio.h>
int main() {
int a = 5;
float b = 2.5;
float result = a + b; // 'a' (int) is promoted to float
printf("Result: %.2f\n", result);
return 0;
}
●
● Output:
Result: 7.50
2. Explicit Typecasting:
Definition:
Done manually by the programmer using a cast operator.
● Purpose:
Used to convert a variable from one type to another intentionally, which may lead to
truncation or other changes.
Example:
#include <stdio.h>
int main() {
float num = 5.75;
int truncated = (int)num; // Explicitly converting float to int
printf("Truncated value: %d\n", truncated);
return 0;
}
●
● Output:
Truncated value: 5
#include <stdio.h>
int main() {
float value = 10.9;
int result = (int)value; // Explicit typecasting
printf("Converted value: %d\n", result);
return 0;
}
#include <stdio.h>
int main() {
int a = 7, b = 2;
float result = (float)a / b; // Explicitly casting 'a' to float
printf("Result: %.2f\n", result);
return 0;
}
Output: Result: 3.50
#include <stdio.h>
int main() {
int x = 5;
double y = 2.0;
double result = x / (double)y; // Explicit typecasting to avoid integer division
printf("Result: %.2f\n", result);
return 0;
}
Definition:
The switch statement allows multiple conditional branches based on the value of an expression.
Program:
#include <stdio.h>
int main() {
int choice;
printf("Enter a number (1-3): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You selected option 1.\n");
break;
case 2:
printf("You selected option 2.\n");
break;
case 3:
printf("You selected option 3.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
Section C
●
● Example Program:
●
Program:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
return 0;
}
Q2. a) Categories of Operators in C.
In C, operators are symbols used to perform operations on variables and values. They are the
backbone of computational tasks in a program. Operators can be classified into several categories
based on their functionality.
1. Arithmetic Operators
+ Addition a+b
- Subtraction a-b
* Multiplication a * b
/ Division a/b
Example Program:
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division: %d\n", a / b);
printf("Modulus: %d\n", a % b);
return 0;
}
Used to compare two values and return a boolean result (1 for true, 0 for false).
!= Not equal to a != b
Example Program:
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("Is a equal to b? %d\n", a == b);
printf("Is a greater than b? %d\n", a > b);
printf("Is a less than or equal to b? %d\n", a <= b);
return 0;
}
3. Logical Operators
` `
Example Program:
#include <stdio.h>
int main() {
int a = 10, b = 20;
printf("Logical AND: %d\n", (a > 5) && (b > 15));
printf("Logical OR: %d\n", (a < 5) || (b > 15));
printf("Logical NOT: %d\n", !(a < b));
return 0;
}
4. Bitwise Operators
` ` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
Example Program:
#include <stdio.h>
int main() {
int a = 5, b = 3; // Binary: a = 0101, b = 0011
printf("Bitwise AND: %d\n", a & b); // 0001 = 1
printf("Bitwise OR: %d\n", a | b); // 0111 = 7
printf("Left Shift: %d\n", a << 1); // 1010 = 10
printf("Right Shift: %d\n", a >> 1); // 0010 = 2
return 0;
}
5. Assignment Operators
= Assign a=b
+= Add and assign a += b (a = a + b)
Example Program:
#include <stdio.h>
int main() {
int a = 10;
a += 5; // a = a + 5
printf("New value of a: %d\n", a);
return 0;
}
++ Increment ++a or
a++
Example Program:
#include <stdio.h>
int main() {
int a = 5;
printf("Post-increment: %d\n", a++); // Prints 5, then increments to 6
printf("Pre-increment: %d\n", ++a); // Increments to 7, then prints
return 0;
}
7. Special Operators
Sizeof Operator (sizeof):
Returns the size (in bytes) of a data type or variable.
Example:
#include <stdio.h>
int main() {
printf("Size of int: %lu\n", sizeof(int));
printf("Size of float: %lu\n", sizeof(float));
return 0;
}
Syntax:
condition ? expression1 : expression2
Example Program:
#include <stdio.h>
int main() {
int a = 5, b = 10;
int max = (a > b) ? a : b;
printf("Maximum value: %d\n", max);
return 0;
}
Q2. b) Grading Program Using Else-If Ladder.
Program:
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 80) {
printf("Grade: B\n");
} else if (marks >= 70) {
printf("Grade: C\n");
} else if (marks >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Section A: 2x2=4
Definition: A function is a block of code that performs a specific task. It takes input values
(parameters), processes them, and returns a result (if applicable).
1. Function Declaration (or Function Prototype) tells the compiler about the function's
name, return type, and parameters (if any), but doesn't include the function's body. It is
usually placed before the main() function.
2. Function Definition is where the actual logic of the function is written, including the
return type, function name, parameters, and the body of the function.
Syntax:
Function Declaration:
return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...);
Function Definition:
return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...) {
// function body
}
Example Program:
#include <stdio.h>
int main() {
int result = add(5, 10); // Function call
printf("Sum: %d\n", result);
return 0;
}
// Function Definition
int add(int a, int b) {
return a + b; // Return the sum of a and b
}
char str[] = "Hello"; // Implicit size is determined by string length (6 including '\0')
Explicit Size:
char str[10] = "World"; // Space for 10 characters (with null terminator at end)
Character-by-Character Initialization:
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Explicit null-termination
Example Program:
#include <stdio.h>
#include <string.h>
int main() {
char greeting[] = "Hello"; // Declare and initialize string
char name[10];
strcpy(name, "World"); // Copy string "World" into 'name'
Definition: A static variable in C retains its value between function calls. Unlike local
variables, which are destroyed after the function execution, static variables persist for the entire
program duration but remain confined to the block where they are declared.
#include <stdio.h>
void count_calls() {
static int count = 0; // Static variable to retain count value
count++;
printf("Function called %d times.\n", count);
}
int main() {
count_calls();
count_calls();
count_calls();
return 0;
}
Output:
Definition: A pointer is a variable that stores the memory address of another variable. Pointers
are powerful for dynamic memory management, arrays, and passing large data to functions
without copying it.
● Dereferencing a pointer allows access to the value stored at the memory location it
points to.
Syntax:
Pointer Declaration:
data_type *pointer_name;
#include <stdio.h>
int main() {
int a = 42;
int *ptr = &a; // Pointer storing the address of variable 'a'
return 0;
}
Output:
Value of a: 42
Address of a: 0x7ffee07ba6a4 (some memory address)
Value through pointer: 42
New value of a: 99
Section B: 2x4=8
Strings in C are represented as arrays of characters. Since C does not have a built-in string data
type, strings are handled using character arrays, with the null character '\0' marking the end of the
string. Below are the common operations that can be performed on strings in C, along with
explanations and example programs:
1. String Input and Output
Explanation:
● Input: Strings can be read from the user using functions like scanf() or fgets().
● Output: Strings can be printed to the console using printf().
Example:
#include <stdio.h>
int main() {
char str[100]; // Declare a string (character array)
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string with spaces
printf("You entered: %s\n", str); // Print the entered string
return 0;
}
● fgets() is used to read a string (including spaces) until a newline or the specified size limit
is reached.
● scanf("%s", str) can be used, but it doesn't handle spaces well.
2. String Length
Explanation:
● The length of a string (number of characters before the null character) can be found using
the strlen() function from the C standard library (<string.h>).
Example:
#include <stdio.h>
#include <string.h> // For strlen()
int main() {
char str[] = "Hello, World!";
int length = strlen(str); // Get length of the string
printf("Length of string: %d\n", length);
return 0;
}
● strlen(str) returns the length of the string excluding the null character.
3. String Concatenation
Explanation:
● Concatenation is the operation of joining two strings together. This can be done using
the strcat() function.
Example:
#include <stdio.h>
#include <string.h> // For strcat()
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
strcat(str1, str2); // Concatenate str2 to str1
printf("Concatenated string: %s\n", str1); // Output: "Hello World!"
return 0;
}
4. String Copy
Explanation:
● Copying one string to another is done using the strcpy() function, which copies the
contents of the source string to the destination string.
Example:
#include <stdio.h>
#include <string.h> // For strcpy()
int main() {
char source[] = "Hello, World!";
char destination[50];
strcpy(destination, source); // Copy source to destination
printf("Copied string: %s\n", destination);
return 0;
}
5. String Comparison
Explanation:
● Comparison of two strings can be done using the strcmp() function, which compares two
strings lexicographically (i.e., character by character).
Example:
#include <stdio.h>
#include <string.h> // For strcmp()
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2); // Compare str1 with str2
if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("str1 is less than str2.\n");
} else {
printf("str1 is greater than str2.\n");
}
return 0;
}
Explanation:
● To search for a substring within a string, you can use the strstr() function. It returns a
pointer to the first occurrence of the substring, or NULL if the substring is not found.
Example:
#include <stdio.h>
#include <string.h> // For strstr()
int main() {
char str[] = "Programming in C is fun!";
char *ptr = strstr(str, "in"); // Search for "in" in str
if (ptr != NULL) {
printf("Substring found at: %s\n", ptr); // Prints from "in"
} else {
printf("Substring not found.\n");
}
return 0;
}
● strstr(str, "in") finds the first occurrence of "in" in the string str and returns a pointer to
the first occurrence. If not found, it returns NULL.
7. String Reverse
Explanation:
● Reversing a string can be done manually by iterating through the string from the last
character to the first or using the strrev() function (though it is not part of the standard
library but available in some compilers like Turbo C).
#include <stdio.h>
#include <string.h> // For strlen()
int main() {
char str[] = "Hello";
reverse(str);
printf("Reversed string: %s\n", str); // Output: "olleH"
return 0;
}
This program manually reverses the string by swapping characters from the beginning and the
end.
Example Program:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements
int sum = 0;
Example Program:
#include <stdio.h>
#include <ctype.h> // for tolower()
int main() {
char str[] = "Hello World!";
int count = 0;
File Modes in C:
"w" Open file for writing (overwrite). Creates a file if it doesn’t exist.
"a" Open file for appending. Data is added to the end of the file.
"r+" Open file for reading and writing. File must exist.
"w+" Open file for reading and writing. Overwrites existing content.
"a+" Open file for reading and appending. File is created if it doesn’t exist.
Example Program:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file) {
fprintf(file, "Hello, File!"); // Write text to file
fclose(file); // Close the file after writing
}
return 0;
}
Section C: 1x8=8
Functions in C can be categorized based on the number of arguments and the type of return
value. Here’s a detailed explanation of the different types of functions in C along with their
definitions and example programs:
A function that neither takes any arguments nor returns any value. These functions are useful
when you want to perform some operation but don't need to pass any data to the function or
return any result.
● Definition:
#include <stdio.h>
void greet() {
int main() {
return 0;
Explanation: greet() is defined with no arguments and no return value. When called in
main(), it simply prints the message "Hello, World!" to the console.
A function that takes one or more arguments but does not return any value. These are useful
when you need to process some data passed to the function but do not need a result back.
Definition:
Example Program:
#include <stdio.h>
// Function with arguments but no return value
int main() {
return 0;
A function that takes arguments and returns a value. These functions are used when you need to
perform a calculation or operation using the passed data and return the result to the calling code.
● Definition:
Example Program:
#include <stdio.h>
}
int main() {
return 0;
Explanation: The add() function takes two integers (a and b) and returns their sum. The
result is stored in result and printed to the console.
A function that does not take any arguments but returns a value. These functions are used when
you want to provide a specific value without needing input from the caller.
● Definition:
Example Program:
#include <stdio.h>
int getNumber() {
int main() {
return 0;
}
Explanation: getNumber() does not take any arguments but returns the value 42. This value is
printed in main().
1b) Explain the differences between passing arguments by value and by reference in C.
1. Pass-by-Value:
○ In pass-by-value, a copy of the actual parameter is passed to the function.
○ The function operates on the copy, and changes made to the parameter inside the
function do not affect the original variable.
○ This is the default method for passing arguments in C.
Example:
#include <stdio.h>
void modifyValue(int x) {
x = 100; // Only modifies the copy of 'x'
}
int main() {
int num = 10;
modifyValue(num); // Passing by value
printf("Value of num after function call: %d\n", num); // num remains 10
return 0;
}
2. Pass-by-Reference:
Example:
#include <stdio.h>
int main() {
int num = 10;
modifyValue(&num); // Passing by reference using the address of 'num'
printf("Value of num after function call: %d\n", num); // num is now 100
return 0;
}
2a) Write a program to illustrate the use of automatic and external variables.
1. Automatic Variables:
○ External variables are declared outside all functions, usually at the beginning of
the program.
○ These variables have a global scope and can be accessed by all functions in the
program.
○ They retain their values for the entire program execution.
Example Program:
#include <stdio.h>
// External variable
int extVar = 100; // Declared outside any function
void display() {
// Automatic variable (local to function)
int autoVar = 20;
printf("Automatic variable: %d\n", autoVar);
printf("External variable: %d\n", extVar); // Accessing external variable
}
int main() {
display();
// Modifying external variable
extVar = 200;
display();
return 0;
}
2b) Compare object-like macros and function-like macros, with an example program.
1. Object-like Macros:
Example:
#include <stdio.h>
int main() {
// Object-like macro
printf("Value of PI: %f\n", PI);
// Function-like macro
int num = 5;
printf("Square of %d: %d\n", num, SQUARE(num));
return 0;
}
Output:
Value of PI: 3.140000
Square of 5: 25