0% found this document useful (0 votes)
23 views

IA 1 & 2 Answer Keys

Key answer of c
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

IA 1 & 2 Answer Keys

Key answer of c
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Section A

Q1. What is an Identifier in C? State the rules for naming an identifier.

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:

1. Must start with a letter (A-Z or a-z) or underscore _.


2. Can include letters, digits (0-9), and underscores.
3. Cannot use keywords as identifiers.
4. No special characters or spaces.
5. Case-sensitive (e.g., Age and age are different).

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;
}

Q2. Program to determine if a user is eligible to vote.

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;
}

Q3. Evaluate E=3⋅(a+b)c−d

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;
}

Q4. Calculate the sum of the first 10 natural numbers.

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

Q5. What are C Tokens? Explain types with examples.

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:

● int (used to declare integer variables)


● return (used to return a value from a function)
● if, else (control structures)

List of Common Keywords in C:

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.

Rules for Identifiers:

● Must start with a letter (A-Z or a-z) or underscore _.


● Can contain letters, digits (0-9), and underscores.
● Cannot use keywords as names.
● Case-sensitive (Age and age are different).
● No spaces or special characters allowed.

Examples of Valid Identifiers:


_value, count1, total_sum

Examples of Invalid Identifiers:


1value, total-sum, int

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:

● Integer Constants: Whole numbers like 10, -25.


● Floating-Point Constants: Decimal numbers like 3.14, -0.5.
● Character Constants: Single characters enclosed in single quotes, e.g., 'A', '3'.
● String Constants: Sequence of characters enclosed in double quotes, e.g., "Hello".

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:

● {, }: Used for grouping statements into blocks.


● ;: Terminates a statement.
● #: Preprocessor directive (e.g., #include).
● []: Denotes arrays.
● (): Encloses function arguments or conditional expressions.

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:

● { } : Curly braces for block definition.


● [ ] : Square brackets for arrays.
● ( ) : Parentheses for function arguments.
● ; : Semicolon to end statements.
● : : Colon in case labels (e.g., case 1:).
● , : Comma for separating arguments.
Q6. What is Typecasting? Explain with examples.

Detailed Explanation of Typecasting 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

1. Implicit Typecasting (Type Promotion):

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

The syntax is: (type) expression

● 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

Typecasting Scenarios and Examples

1. Converting float to int:

● Used to truncate decimal parts of a floating-point number.

#include <stdio.h>
int main() {
float value = 10.9;
int result = (int)value; // Explicit typecasting
printf("Converted value: %d\n", result);
return 0;
}

Output: Converted value: 10

2. Converting int to float:

● Useful for precision in division operations.

#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

3. Typecasting in Arithmetic Operations:

● Example with mixed data types:

#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;
}

Output: Result: 2.50

Q7. Explain the switch statement with an example.

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

Q1. a) Describe the structure of a C program.

● Documentation Section: Used for comments to describe the program.


● Link Section: Includes necessary header files, like <stdio.h> for input/output operations.
● Global Declarations: Any variables that need to be accessed globally.
● Function Prototype: Tells the compiler about a function before its actual definition.
● Main Function: Contains variable declarations, input/output operations, logic, and
function calls.
● User-Defined Function Definitions: Contains the actual definitions of any custom
functions used in the program.


● Example Program:

Q1. b) Check if a number is even or odd.

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.

Detailed Explanation 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

Used to perform basic mathematical operations.

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a * b

/ Division a/b

% Modulus a % b (remainder of division)

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;
}

2. Relational (Comparison) Operators

Used to compare two values and return a boolean result (1 for true, 0 for false).

Operator Description Example


== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or 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

Used to combine conditional statements.

Operator Description Example

&& Logical AND (a > b) && (b < c)

` `

! Logical NOT !(a > b)

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

Perform bit-level operations on data.

Operator Description Example

& Bitwise AND a & b

` ` Bitwise OR

^ Bitwise XOR a ^ b

~ Bitwise NOT ~a

<< Left shift a << 2

>> Right shift a >> 2

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

Used to assign values to variables.

Operator Description Example

= Assign a=b
+= Add and assign a += b (a = a + b)

-= Subtract and assign a -= b (a = a - b)

*= Multiply and assign a *= b (a = a * b)

/= Divide and assign a /= b (a = a / b)

%= Modulus 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;
}

6. Increment and Decrement Operators

Used to increase or decrease the value of a variable by 1.

Operator Description Example

++ Increment ++a or
a++

-- Decrement --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;
}

Pointer Operators (&, *):


Used for pointer manipulation.
Example:
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a; // Pointer stores the address of a
printf("Address of a: %p\n", ptr);
printf("Value of a: %d\n", *ptr); // Dereferencing the pointer
return 0;
}

8. Conditional (Ternary) Operator

Used for shorthand if-else.

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

1) How can a function be declared and defined in C?

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>

// Function Declaration (or Prototype)


int add(int, int);

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
}

2) How are strings declared and initialized in C?

Definition: A string in C is essentially an array of characters, terminated by a null character '\0'.


Strings are stored in contiguous memory locations, and the '\0' marks the end of the string.

Syntax for String Declaration and Initialization:

Implicit Size (Based on the string literal):

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'

// Concatenate greeting and name


strcat(greeting, " ");
strcat(greeting, name);

printf("%s\n", greeting); // Output: Hello World


printf("Length of greeting: %lu\n", strlen(greeting)); // Length of string
return 0;
}

3) Why are static variables used in C?

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.

● Scope: Static variables have local scope.


● Lifetime: They exist for the entire lifetime of the program.

Syntax: static data_type variable_name;


Example Program:

#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:

Function called 1 times.


Function called 2 times.
Function called 3 times.

4) What is a pointer? Provide an example.

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;

Dereferencing (Accessing the value stored at the pointer's address):


*pointer_name
Example Program:

#include <stdio.h>

int main() {
int a = 42;
int *ptr = &a; // Pointer storing the address of variable 'a'

// Access the value using the pointer


printf("Value of a: %d\n", a); // Direct access
printf("Address of a: %p\n", &a); // Print address of 'a'
printf("Value through pointer: %d\n", *ptr); // Dereferencing the pointer

*ptr = 99; // Modifying value of 'a' through pointer


printf("New value of a: %d\n", 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

5) Discuss the different operations that can be performed on strings in C.

Operations that can be performed on strings in C

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;
}

● strcat(str1, str2) appends str2 to the end of str1.

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;
}

● strcpy(destination, source) copies the entire string source into destination.

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;
}

● strcmp(str1, str2) returns:


○ 0 if both strings are identical.
○ A negative number if str1 is lexicographically smaller than str2.
○ A positive number if str1 is lexicographically greater than str2.
6. String Searching

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

Example Program (Manual Reversal):

#include <stdio.h>
#include <string.h> // For strlen()

void reverse(char str[]) {


int start = 0;
int end = strlen(str) - 1;
while (start < end) {
// Swap characters at start and end
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}

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.

Summary of String Operations in C

Operation Description Example Function

Input Reading a string from the user fgets() or scanf()

Output Displaying a string to the console printf()

Length Finding the length of a string strlen()

Concatenation Joining two strings together strcat()

Copying Copying one string to another strcpy()

Comparison Comparing two strings strcmp()

Searching Finding a substring within a string strstr()


6) Write a program to calculate the sum of elements in a one-dimensional array.

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;

// Loop through the array and add elements to sum


for (int i = 0; i < n; i++) {
sum += arr[i];
}

printf("Sum of elements: %d\n", sum);


return 0;
}

7) Write a C program to count the vowels in a given string.

Example Program:

#include <stdio.h>
#include <ctype.h> // for tolower()

int main() {
char str[] = "Hello World!";
int count = 0;

// Loop through the string and check for vowels


for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]); // Convert to lowercase
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++; // Increment count for vowels
}
}
printf("Number of vowels: %d\n", count);
return 0;
}

8) What are file modes in C? Explain their usage.

File Modes in C:

Mode Description Example

"r" Open file for reading. File must exist.

"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
}

// Reopen the file in read mode to display the content


file = fopen("example.txt", "r");
if (file) {
char ch;
while ((ch = fgetc(file)) != EOF) { // Read and print each character
putchar(ch);
}
fclose(file);
}

return 0;
}

Section C: 1x8=8

1a) Describe the various types of functions in C.

Different Types of Functions in C

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:

1. Functions with No Arguments and No Return Value

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:

○ The function does not take any parameters (arguments).


○ The function does not return any value (its return type is void).
Example Program:

#include <stdio.h>

// Function with no arguments and no return value

void greet() {

printf("Hello, World!\n"); // Prints a message to the console

int main() {

greet(); // Function call

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.

2. Functions with Arguments but No Return Value

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:

○ The function takes parameters (arguments).


○ The function does not return a value (its return type is void).

Example Program:

#include <stdio.h>
// Function with arguments but no return value

void greet(char name[]) {

printf("Hello, %s!\n", name); // Greets the user with their name

int main() {

greet("Alice"); // Function call with an argument

return 0;

Explanation: greet() accepts a string (char name[]) as an argument and prints a


personalized greeting. In this case, "Alice" is passed as an argument.

3. Functions with Arguments and Return Value

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:

○ The function takes one or more parameters.


○ The function returns a value of a specific type (such as int, float, etc.).

Example Program:

#include <stdio.h>

// Function with arguments and a return value

int add(int a, int b) {

return a + b; // Returns the sum of a and b

}
int main() {

int result = add(10, 20); // Function call with two arguments

printf("Sum: %d\n", result); // Prints the result of the addition

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.

4. Functions with No Arguments but Returns a Value

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:

○ The function does not take any parameters (arguments).


○ The function returns a value of a specific type (such as int, float, etc.).

Example Program:

#include <stdio.h>

// Function with no arguments but returns a value

int getNumber() {

return 42; // Returns a constant number

int main() {

printf("Number: %d\n", getNumber()); // Prints the returned value

return 0;

}
Explanation: getNumber() does not take any arguments but returns the value 42. This value is
printed in main().

Summary of Function Types

Type Arguments Return Use Case


Value

No None void Functions that perform


Arguments, an action without
No Return returning data.
Value

With One or void Functions that perform


Arguments, more actions based on input
No Return arguments arguments but don’t
Value need to return data.

With One or A specific Functions that process


Arguments more data type data and return a result.
and Return arguments (e.g., int,
Value float)

No None A specific Functions that provide


Arguments, data type a value without
Returns a (e.g., int, needing input.
Value float)

1b) Explain the differences between passing arguments by value and by reference in C.

In C, when passing arguments to a function, there are two methods:

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:

○ In pass-by-reference, the memory address (reference) of the actual parameter is


passed to the function.
○ The function operates on the original variable because it works with the memory
address.
○ Changes made inside the function affect the original variable.
○ To implement this, we use pointers in C.

Example:

#include <stdio.h>

void modifyValue(int *x) {


*x = 100; // Modifies the actual variable by dereferencing the pointer
}

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:

○ Automatic variables are the default type of local variables.


○ They are automatically created when the block (function) is executed and
destroyed when the block is exited.
○ Automatic variables are initialized to garbage values if not explicitly initialized.
2. External 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:

○ Object-like macros are used to define constant values or simple substitutions.


○ These macros do not take arguments.
○ Defined using the #define directive.
2. Function-like Macros:

○ Function-like macros take arguments and behave like functions.


○ They are expanded by the preprocessor before the program is compiled.
○ Defined using the #define directive with arguments.

Example:

#include <stdio.h>

#define PI 3.14 // Object-like macro


#define SQUARE(x) ((x) * (x)) // Function-like macro

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

You might also like