[go: up one dir, main page]

0% found this document useful (0 votes)
19 views37 pages

FOP assignment1

The document provides an overview of fundamental concepts in C programming, including tokens, identifiers, keywords, data types, arithmetic and conditional operators, loop control structures, formatted output, and functions. It explains various programming constructs with examples, such as the use of loops (for, while, do-while), the switch-case statement, and recursion. Additionally, it covers the concept of structures and the difference between call by value and call by reference in function calls.

Uploaded by

Piyaa Rathod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views37 pages

FOP assignment1

The document provides an overview of fundamental concepts in C programming, including tokens, identifiers, keywords, data types, arithmetic and conditional operators, loop control structures, formatted output, and functions. It explains various programming constructs with examples, such as the use of loops (for, while, do-while), the switch-case statement, and recursion. Additionally, it covers the concept of structures and the difference between call by value and call by reference in function calls.

Uploaded by

Piyaa Rathod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Q=1

1. C tokens 2. identifier 3. keyword

1. C Tokens:

In C, tokens are the smallest individual units in a program. There are six types of tokens in C:

• Keywords
• Identifiers
• Constants
• Strings
• Operators
• Punctuators

Example of Tokens in C:

c
int main() {
int number = 10; // `int`, `main`, `(`, `)`, `{`, `int`, `number`, `=`,
`10`, `;`, `//`, `}`, `return` are all tokens
return 0;
}

2. Identifiers:

Identifiers are names given to various elements such as variables, functions, arrays, etc., defined
by the programmer. An identifier must start with a letter (A-Z or a-z) or an underscore (_),
followed by letters, digits (0-9), or underscores.

Example of Identifiers in C:

c
#include <stdio.h>

int main() {
int age; // `age` is an identifier
float salary; // `salary` is an identifier
char initial; // `initial` is an identifier

age = 25;
salary = 50000.50;
initial = 'A';

printf("Age: %d\n", age);


printf("Salary: %.2f\n", salary);
printf("Initial: %c\n", initial);

return 0;
}
3. Keywords:

Keywords are reserved words that have special meaning in C and cannot be used as identifiers.
They are predefined by the language and are used to perform specific operations.

Example of Keywords in C:

c
#include <stdio.h>

int main() {
int sum = 0; // `int` and `return` are keywords

for(int i = 1; i <= 10; i++) { // `for`, `int`, and `return` are keywords
sum += i;
}

printf("Sum: %d\n", sum); // `printf` and `return` are not keywords; they
are functions from the standard library

return 0;
}

Q=2

1. Explain data type.


Data Types:

Data types in C specify the type of data that can be stored in a variable. They help the compiler
understand how much memory to allocate and what type of operations can be performed on that
data. Here are the primary data types in C:

• int: Used to store integers.


• float: Used to store single-precision floating-point numbers.
• double: Used to store double-precision floating-point numbers.
• char: Used to store a single character.

Example of Data Types in C:

c
#include <stdio.h>

int main() {
int age = 25; // Integer type
float height = 5.9f; // Floating-point type
double weight = 75.5; // Double-precision type
char initial = 'A'; // Character type
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Weight: %.1lf\n", weight);
printf("Initial: %c\n", initial);

return 0;
}

2. Explain arithmetic operators with example.

Arithmetic Operators:

Arithmetic operators in C are used to perform mathematical operations. Here are the common
arithmetic operators:

• + (Addition): Adds two operands.


• - (Subtraction): Subtracts the second operand from the first.
• *** (Multiplication): Multiplies two operands.
• / (Division): Divides the first operand by the second.
• % (Modulus): Returns the remainder of a division operation.

Example of Arithmetic Operators in C:

c
#include <stdio.h>

int main() {
int a = 10, b = 5;
int sum, difference, product, quotient, remainder;

sum = a + b; // Addition
difference = a - b; // Subtraction
product = a * b; // Multiplication
quotient = a / b; // Division
remainder = a % b; // Modulus

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


printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %d\n", quotient);
printf("Remainder: %d\n", remainder);

return 0;
}

1. Explain conditional operator with example.

Conditional Operator:
The conditional operator, also known as the ternary operator, is a shorthand way of writing an
if-else statement. It takes three operands and is often used to simplify simple conditional
assignments.

Syntax:

c
condition ? expression1 : expression2;

• If the condition is true, expression1 is executed.


• If the condition is false, expression2 is executed.

Example of Conditional Operator:

c
#include <stdio.h>

int main() {
int a = 10, b = 5;
int max;

max = (a > b) ? a : b; // `max` is assigned the value of `a` if `a` is


greater than `b`, otherwise it's assigned the value of `b`.

printf("Maximum: %d\n", max);

return 0;
}

2. Explain 'switch-case' with example.

switch-case Statement:

The switch-case statement is used to execute one out of multiple blocks of code based on the
value of a variable or expression. It's an alternative to using multiple if-else statements and can
make your code more readable and organized.

Syntax:

c
switch (expression) {
case constant1:
// code to be executed if expression is equal to constant1
break;
case constant2:
// code to be executed if expression is equal to constant2
break;
...
default:
// code to be executed if expression does not match any case
}

• expression is evaluated once and compared with the values of each case.
• The break statement is used to exit the switch-case structure once a matching case is
executed.
• The default case is optional and is executed if none of the cases match the expression.

Example of switch-case Statement:

c
#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}

return 0;
}

Q=3
Explain different loop control structures with suitable examples.

Loops are a fundamental part of programming that allow you to execute a block of code multiple
times. C provides several loop control structures, each suited for different scenarios.
1. for Loop:

The for loop is typically used when you know in advance how many times you want to execute
a statement or a block of statements.

Syntax:

c
for (initialization; condition; increment/decrement) {
// Code to be executed
}

Example:

c
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}

This loop will print numbers from 1 to 5.

2. while Loop:

The while loop is used when you want to repeat a block of code as long as a condition is true.
The condition is evaluated before the execution of the loop's body.

Syntax:

c
while (condition) {
// Code to be executed
}

Example:

c
#include <stdio.h>

int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}

This loop will also print numbers from 1 to 5.

3. do-while Loop:

The do-while loop is similar to the while loop, but the condition is evaluated after the
execution of the loop's body. This ensures that the loop's body is executed at least once.

Syntax:

c
do {
// Code to be executed
} while (condition);

Example:

c
#include <stdio.h>

int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}

This loop will again print numbers from 1 to 5, but the key difference is that the loop's body is
executed before the condition is checked.

4. Nested Loops:

You can also use loops inside another loop. This is called nested loops and is useful for scenarios
such as printing a pattern or traversing a multi-dimensional array.

Example:

c
#include <stdio.h>

int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("(%d, %d) ", i, j);
}
printf("\n");
}
return 0;
}

This loop will print a grid of coordinates:

(1, 1) (1, 2) (1, 3)


(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)

Explain formatted output with suitable examples.

In C, formatted output is achieved using the printf function, which is part of the standard input-
output library (stdio.h). The printf function allows you to print variables and literals to the
console in a formatted manner.

Basic Syntax:

c
printf(format_string, argument_list);

• format_string: A string that contains text and format specifiers. The format specifiers
begin with a % symbol and indicate the type of data to be printed.
• argument_list: A list of variables or literals to be printed, corresponding to the format
specifiers.

Common Format Specifiers:

• %d or %i - Integer
• %f - Floating-point number
• %lf - Double
• %c - Character
• %s - String
• %x - Hexadecimal integer
• %o - Octal integer
• %u - Unsigned integer

Example 1: Printing Various Data Types

c
#include <stdio.h>

int main() {
int age = 25;
float height = 5.9f;
double weight = 75.5;
char initial = 'A';
char name[] = "John";
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Weight: %.1lf\n", weight);
printf("Initial: %c\n", initial);

return 0;
}

Output:

Name: John
Age: 25
Height: 5.9
Weight: 75.5
Initial: A

Example 2: Formatting Numbers

c
#include <stdio.h>

int main() {
int num = 255;

printf("Decimal: %d\n", num);


printf("Hexadecimal: %x\n", num);
printf("Octal: %o\n", num);
printf("Unsigned: %u\n", num);

return 0;
}

Output:

Decimal: 255
Hexadecimal: ff
Octal: 377
Unsigned: 255

Example 3: Formatting with Width and Precision

c
#include <stdio.h>

int main() {
float pi = 3.1415926535;

printf("Pi to 2 decimal places: %.2f\n", pi);


printf("Pi to 5 decimal places: %.5f\n", pi);
printf("Pi with width 10: %10.5f\n", pi);
return 0;
}

Output:

Pi to 2 decimal places: 3.14


Pi to 5 decimal places: 3.14159
Pi with width 10: 3.14159

Q=4

a. 'Strlen' function
b. Break
c. Structure with example

a. strlen Function:

The strlen function in C is used to determine the length of a string. It is part of the <string.h>
library. The function takes a single argument, which is a pointer to a string, and returns the
length of the string excluding the null terminator (\0).

Syntax:

c
size_t strlen(const char *str);

Example:

c
#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello, World!";
size_t length = strlen(str);

printf("The length of the string is: %zu\n", length);

return 0;
}

b. break Statement:

The break statement in C is used to exit a loop or switch statement prematurely. When break is
encountered, control immediately exits the loop or switch, and execution continues with the next
statement following the loop or switch.
Example with a Loop:

c
#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is equal to 5
}
printf("%d\n", i);
}

return 0;
}

Example with a switch Statement:

c
#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}

return 0;
}

c. Structure:

A structure in C is a user-defined data type that allows you to combine data items of different
kinds. Structures are used to represent a record.

Syntax:
c
struct structure_name {
data_type member1;
data_type member2;
// more members
};

Example:

c
#include <stdio.h>

// Define a structure named 'Student'


struct Student {
int id;
char name[50];
float grade;
};

int main() {
// Create an instance of the structure
struct Student student1;

// Assign values to the members


student1.id = 1;
strcpy(student1.name, "John Doe");
student1.grade = 88.5;

// Print the values


printf("Student ID: %d\n", student1.id);
printf("Student Name: %s\n", student1.name);
printf("Student Grade: %.2f\n", student1.grade);

return 0;
}

Q=5
1. Write code snippet to show the working of recursive function.

Recursive Function:

A recursive function is a function that calls itself in order to solve a problem. Each call to the
function reduces the problem into smaller sub-problems. Recursion is useful for tasks that can be
broken down into similar subtasks.

Example of Recursive Function: Calculating Factorial

c
#include <stdio.h>
// Function to calculate factorial using recursion
int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}

int main() {
int number = 5;
printf("Factorial of %d is %d\n", number, factorial(number));
return 0;
}

This code calculates the factorial of a number using a recursive function. For example,
factorial(5) calls factorial(4), which calls factorial(3), and so on, until it reaches the
base case.

2. Explain different categories of function calls in 'C 'with programming an


example of each.

Categories of Function Calls in C:

a. Call by Value:

In call by value, the actual value of an argument is passed to the function. Changes made to the
parameter inside the function do not affect the original value.

Example of Call by Value:

c
#include <stdio.h>

void swap(int x, int y) {


int temp = x;
x = y;
y = temp;
printf("Inside function: x = %d, y = %d\n", x, y);
}

int main() {
int a = 10, b = 20;
printf("Before function call: a = %d, b = %d\n", a, b);
swap(a, b);
printf("After function call: a = %d, b = %d\n", a, b);
return 0;
}

Output:
Before function call: a = 10, b = 20
Inside function: x = 20, y = 10
After function call: a = 10, b = 20

In this example, the values of a and b do not change after the function call because swap is called
by value.

b. Call by Reference:

In call by reference, the address of an argument is passed to the function. Changes made to the
parameter inside the function affect the original value.

Example of Call by Reference:

c
#include <stdio.h>

void swap(int *x, int *y) {


int temp = *x;
*x = *y;
*y = temp;
printf("Inside function: x = %d, y = %d\n", *x, *y);
}

int main() {
int a = 10, b = 20;
printf("Before function call: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After function call: a = %d, b = %d\n", a, b);
return 0;
}

Output:

Before function call: a = 10, b = 20


Inside function: x = 20, y = 10
After function call: a = 20, b = 10

1. Explain file opening modes in text files in 'C' language.

File Opening Modes in C:

In C, you can open files in different modes depending on the operation you want to perform
(reading, writing, appending, etc.). These modes are specified as strings when you use the fopen
function. Here are some common file opening modes:

• "r" (Read): Opens the file for reading. The file must exist.
• "w" (Write): Opens the file for writing. If the file exists, its contents are truncated. If the
file does not exist, it is created.
• "a" (Append): Opens the file for appending. Data is written at the end of the file. If the
file does not exist, it is created.
• "r+" (Read/Update): Opens the file for both reading and writing. The file must exist.
• "w+" (Write/Update): Opens the file for both reading and writing. If the file exists, its
contents are truncated. If the file does not exist, it is created.
• "a+" (Append/Update): Opens the file for both reading and appending. Data is written at
the end of the file. If the file does not exist, it is created.

Example of File Opening:

c
#include <stdio.h>

int main() {
FILE *file;

// Open file in read mode


file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
printf("File opened for reading successfully.\n");
fclose(file);

// Open file in write mode


file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
printf("File opened for writing successfully.\n");
fclose(file);

// Open file in append mode


file = fopen("example.txt", "a");
if (file == NULL) {
printf("Error opening file for appending.\n");
return 1;
}
printf("File opened for appending successfully.\n");
fclose(file);

return 0;
}

2. Write code snippet to calculate length of a string using loop.

Code Snippet to Calculate Length of a String Using a Loop:

To calculate the length of a string without using the strlen function, you can use a loop to count
the number of characters until you reach the null terminator (\0).
Example:

c
#include <stdio.h>

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

// Loop through each character in the string until the null terminator is
reached
while (str[length] != '\0') {
length++;
}

printf("The length of the string is: %d\n", length);

return 0;
}

Q=6
1. A+=12;
2. puts()
3. getch()
4. strcat(s1,"abc");
5. fscanf()

1. A += 12;

This is a shorthand assignment operator in C. It adds the value on the right (12) to the variable A
and then assigns the result back to A. It is equivalent to writing A = A + 12;.

Example:

c
#include <stdio.h>

int main() {
int A = 5;
A += 12; // A = A + 12
printf("A = %d\n", A); // Output will be 17
return 0;
}

2. puts()
The puts function is used to write a string to the standard output (usually the console). It
automatically adds a newline character at the end of the string.

Syntax:

c
int puts(const char *str);

Example:

c
#include <stdio.h>

int main() {
puts("Hello, World!"); // Outputs "Hello, World!" followed by a newline
return 0;
}

3. getch()

The getch function reads a single character from the keyboard but does not echo it to the
console. It is commonly used to pause the program execution until the user presses a key.

Syntax:

c
int getch(void);

Example:

c
#include <stdio.h>
#include <conio.h> // Required for getch()

int main() {
printf("Press any key to continue...");
getch(); // Waits for the user to press a key
printf("\nYou pressed a key!");
return 0;
}

4. strcat(s1, "abc");

The strcat function concatenates (appends) the second string ("abc") to the end of the first
string (s1). The first string (s1) must have enough space to hold the resulting concatenated
string.

Syntax:
c
char *strcat(char *dest, const char *src);

Example:

c
#include <stdio.h>
#include <string.h>

int main() {
char s1[50] = "Hello";
strcat(s1, "abc"); // Appends "abc" to the end of s1
printf("Concatenated string: %s\n", s1); // Outputs "Helloabc"
return 0;
}

5. fscanf()

The fscanf function reads formatted input from a file. It works similarly to scanf but reads data
from a file instead of standard input.

Syntax:

c
int fscanf(FILE *stream, const char *format, ...);

Example:

c
#include <stdio.h>

int main() {
FILE *file;
char name[50];
int age;

file = fopen("data.txt", "r");


if (file == NULL) {
printf("Error opening file.\n");
return 1;
}

// Read data from the file


fscanf(file, "%s %d", name, &age);

printf("Name: %s\n", name);


printf("Age: %d\n", age);

fclose(file);
return 0;
}
2022
Q=1

1. Interpreter & Compiler:

• Interpreter:
o An interpreter translates high-level code into machine code, but it does so line-by-
line, executing each line immediately.
o Example: Python is an interpreted language. When you run a Python script, the
interpreter executes the script line by line.

python

print("Hello, World!") # This line is interpreted and executed


immediately

• Compiler:
o A compiler translates the entire high-level program into machine code before
execution. The machine code is then executed directly by the computer.
o Example: C is a compiled language. When you compile a C program, the
compiler converts it into an executable file, which can then be run.

#include <stdio.h>

int main() {
printf("Hello, World!");
return 0;
}

Key Points

• Translation Process: Interpreters translate code line-by-line, while compilers translate the
entire program at once.

• Execution Speed: Interpreted code runs slower because translation happens at runtime,
whereas compiled code runs faster since it's pre-translated.

• Error Handling: Interpreters can catch errors immediately, while compilers show errors only
after the whole code is compiled.

• Flexibility: Interpreters allow for more flexibility during development, making them suitable
for scripting and rapid prototyping, whereas compilers are better for performance-critical
applications.
2. Algorithm & Flowchart:

• Algorithm:
o An algorithm is a step-by-step procedure to solve a problem. It is written in plain
language and describes the sequence of steps to be performed.
o Example: An algorithm to find the sum of the first 10 natural numbers.

plaintext

Step 1: Initialize sum to 0


Step 2: Initialize counter to 1
Step 3: While counter is less than or equal to 10, do:
a. Add counter to sum
b. Increment counter by 1
Step 4: Output sum

• Flowchart:
o A flowchart is a graphical representation of an algorithm. It uses symbols to
represent the steps and arrows to show the flow of the process.
o Example: Flowchart to find the sum of the first 10 natural numbers.

plaintext

+---------------+
| Start |
+---------------+
|
v
+---------------+
| sum = 0 |
+---------------+
|
v
+---------------+
| counter = 1 |
+---------------+
|
v
+----------------------+
| counter <= 10? |
+----------------------+
/ \
yes no
/ \
v v
+------------------+ +---------------+
| sum = sum + counter | | Output sum |
+------------------+ +---------------+
|
v
+---------------+
| counter++ |
+---------------+
|
v
+---------------+
| End |
+---------------+

Key Points:

• Representation: An algorithm is represented in a text format, while a flowchart is


represented in a graphical format.
• Understanding: Algorithms are easy to write and understand, while flowcharts are easier
to visualize and comprehend the flow of the process.
• Use Case: Algorithms are used for detailed step-by-step instructions, while flowcharts
are used for visualizing the flow of control in a process.

3. Identifier, Keyword, Variable:

• Identifier:
o An identifier is a name given to elements like variables, functions, arrays, etc. It
must start with a letter or underscore, followed by letters, digits, or underscores.
o Example:

int total; // 'total' is an identifier

• Keyword:
o Keywords are reserved words in a programming language that have a specific
meaning and cannot be used as identifiers.
o Example:

int main() {
return 0; // 'int' and 'return' are keywords
}

• Variable:
o A variable is a storage location identified by an identifier and used to store data
that can be changed during program execution.
o Example:

int age = 25; // 'age' is a variable that stores the value 25

Q=2

1. What is an Operator? Explain Conditional Operator with an Example.

Operators are symbols that perform specific operations on one or more operands (values or
variables). For example, in 5 + 3, the + symbol is an operator that adds the two operands 5 and
3.

The conditional operator, also known as the ternary operator, is a shorthand way of writing an
if-else statement. It is represented by the symbols ? :.

Syntax:

c
condition ? expression1 : expression2;

Example:

c
int x = 10;
int y = (x > 5) ? 1 : 0;

In this example, y will be assigned 1 if x is greater than 5; otherwise, y will be assigned 0.

2. What is a Data Type? Write a Note on Basic Data Types.

A data type is a classification that specifies the type of data that a variable can hold. It defines the
operations that can be performed on the data and the way it is stored in memory.

Basic Data Types:

1. Integer (int): Used to store whole numbers without a fractional part. For example: int
a = 5;.
2. Character (char): Used to store single characters. For example: char c = 'A';.
3. Float (float): Used to store floating-point numbers (numbers with a decimal point). For
example: float pi = 3.14;.
4. Double (double): Similar to float, but with double precision. For example: double g =
9.81;.
5. Boolean (bool): Used to store true or false values. For example: bool isValid =
true;.

1. Mention the Structure of a C Program

A C program typically follows a specific structure. Here is a basic outline of the structure:

c
#include <stdio.h> // Preprocessor Directive

// Function Declaration
int main() // Main Function
{
// Variable Declaration
// Body of the function
printf("Hello, World!");
return 0; // Return Statement
}
// Function Definition

Explanation:

1. Preprocessor Directive: These are lines included in the code preceded by a # symbol.
For example, #include <stdio.h> is used to include the standard input-output library.
2. Main Function: This is the starting point of the program. The execution begins from the
main function.
3. Variable Declaration: Here, variables are declared to store data.
4. Body of the Function: This is where the actual code that performs the specific tasks
resides.
5. Return Statement: This indicates the end of the main function and returns control to the
operating system.

2. Write the Syntax and Rules of the Switch Statement

The switch statement allows a variable to be tested for equality against a list of values. Each
value is called a "case," and the variable being switched on is checked for each case.

Syntax:

c
switch (expression)
{
case value1:
// Code to be executed if expression == value1
break; // Exit the switch block
case value2:
// Code to be executed if expression == value2
break;
...
default:
// Code to be executed if expression doesn't match any case
}

Rules:

1. The expression in the switch statement must be of an integral or enumeration type.


2. Each case must end with a break statement to exit the switch block. Otherwise, the
program will continue to execute the subsequent cases (fall-through behavior).
3. The default case is optional and can be used to perform actions when none of the
specified cases match the expression.

Q=3

1. What is Looping? Write and Explain the Syntax of the for Loop.

Looping is the process of repeating a block of code multiple times. In programming, loops are
used to execute a block of code as long as a specified condition is met.

Syntax of the for Loop:

c
for (initialization; condition; increment/decrement)
{
// Code to be executed
}

Example:

c
#include <stdio.h>

int main()
{
int i;
for (i = 0; i < 5; i++)
{
printf("Value of i: %d\n", i);
}
return 0;
}

In this example:

• Initialization: int i = 0; sets the starting value of the loop counter.


• Condition: i < 5; checks if the loop should continue running.
• Increment: i++ updates the loop counter after each iteration.

2. What is the Difference Between while and do..while Loop? Explain Briefly.

Both while and do..while loops are used to repeat a block of code, but they differ in how they
evaluate the condition.

while Loop:

• The condition is evaluated before executing the block of code.


• If the condition is false, the code inside the loop will not execute even once.

Syntax:

c
while (condition)
{
// Code to be executed
}

Example:

c
#include <stdio.h>

int main()
{
int i = 0;
while (i < 5)
{
printf("Value of i: %d\n", i);
i++;
}
return 0;
}

do..while Loop:

• The block of code is executed once before the condition is evaluated.


• If the condition is false, the code inside the loop will execute at least once.

Syntax:

c
do
{
// Code to be executed
} while (condition);
Example:

c
#include <stdio.h>

int main()
{
int i = 0;
do
{
printf("Value of i: %d\n", i);
i++;
} while (i < 5);
return 0;
}

3. Differentiate Between break and continue with an Example

break and continue are control statements that alter the flow of loops.

break:

• Exits the loop immediately.


• Used to terminate the loop when a specific condition is met.

Example:

c
#include <stdio.h>

int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
printf("Value of i: %d\n", i);
}
return 0;
}

In this example, the loop terminates when i equals 5.

continue:

• Skips the current iteration and moves to the next iteration.


• Used to skip certain conditions within the loop.
Example:

c
#include <stdio.h>

int main()
{
int i;
for (i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
printf("Value of i: %d\n", i);
}
return 0;
}

Q=4

1. Structure vs Union

Structure: A structure in C is a user-defined data type that groups different data types together.
It allows you to store variables of different types under a single name.

Syntax:

c
struct StructureName {
dataType member1;
dataType member2;
// More members
};

Example:

c
struct Person {
char name[50];
int age;
float height;
};

int main() {
struct Person person1;
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 5.9;
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);

return 0;
}

Union: A union in C is similar to a structure, but it allows different members to share the same
memory location. This means only one member can contain a value at any given time.

Syntax:

c
union UnionName {
dataType member1;
dataType member2;
// More members
};

Example:

c
union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

data.i = 10;
printf("data.i: %d\n", data.i);

data.f = 220.5;
printf("data.f: %.1f\n", data.f);

strcpy(data.str, "C Programming");


printf("data.str: %s\n", data.str);

return 0;
}

Key Points:
• In structures, each member has its own memory location, while in unions, all members
share the same memory location.
• Structures can store multiple values simultaneously, while unions can store only one
value at a time.

2. Pass by Value and Pass by Reference


Pass by Value: When a function is called by value, a copy of the actual parameter's value is
passed to the function. Changes made to the parameter inside the function do not affect the
original value.

Example:

c
#include <stdio.h>

void modifyValue(int num) {


num = 20;
}

int main() {
int a = 10;
modifyValue(a);
printf("Value of a: %d\n", a); // Output will be 10
return 0;
}

Pass by Reference: When a function is called by reference, the address of the actual parameter
is passed to the function. Changes made to the parameter inside the function affect the original
value.

Example:

c
#include <stdio.h>

void modifyValue(int *num) {


*num = 20;
}

int main() {
int a = 10;
modifyValue(&a);
printf("Value of a: %d\n", a); // Output will be 20
return 0;
}

Key Points:

• In pass by value, a copy of the value is passed to the function, so changes made inside the
function do not affect the original value.
• In pass by reference, the address of the variable is passed to the function, so changes
made inside the function affect the original value.
int main()

int a = 25, b = 50;

printf("\n%d", a++); // Outputs 25, then a becomes 26

printf("\n%d", b++); // Outputs 50, then b becomes 51

printf("\n%d", --b); // Decrements b to 50, then outputs 50

printf("\n%d", ++a); // Increments a to 27, then outputs 27 return 0;

Output:
25
50
50
27

Q=5

1. What is a Pointer? How Can We Use a Pointer with an Array?

A pointer is a variable that stores the memory address of another variable. Pointers are used for
dynamic memory allocation, accessing array elements, and passing arrays and functions as
arguments efficiently.

Syntax:

c
dataType *pointerName;

Example:

c
int *ptr;
int var = 10;
ptr = &var;

In this example, ptr is a pointer to an integer that stores the address of the variable var.
Using Pointers with Arrays: Pointers can be used to access and manipulate array elements. The
name of the array itself acts as a pointer to the first element of the array.

Example:

c
#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Points to the first element of the array

for (int i = 0; i < 5; i++) {


printf("Element %d: %d\n", i, *(ptr + i)); // Accessing array
elements using pointer
}

return 0;
}

2. What is Modular Programming? Write Syntax to Define a User-Defined


Function with an Example

Modular programming is a software design technique that emphasizes separating the


functionality of a program into independent, interchangeable modules. Each module contains
everything necessary to execute one aspect of the desired functionality.

Advantages:

• Improves code readability and maintainability.


• Encourages code reuse.
• Simplifies debugging and testing.

Syntax to Define a User-Defined Function:

c
returnType functionName(parameterList) {
// Function body
}

Example:

c
#include <stdio.h>

// Function declaration
void greet();

// Main function
int main() {
greet(); // Function call
return 0;
}

// Function definition
void greet() {
printf("Hello, World!");
}

1. What is Recursion? Explain with a Suitable Example.

Recursion is a programming technique where a function calls itself directly or indirectly to solve
a problem. Recursion involves breaking down a problem into smaller subproblems until a base
condition is met, and then combining the solutions of the subproblems to solve the original
problem.

Example: A classic example of recursion is the calculation of the factorial of a number. The
factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less
than or equal to n.

Recursive Function to Calculate Factorial:

c
#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return n * factorial(n - 1); // Recursive case
}
}

int main() {
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}

In this example:

• The factorial function calls itself with the argument n-1 until it reaches the base case
(n == 0).
• The base case returns 1, and the recursive calls accumulate the product of integers from n
to 1.

2. List Any Four String Functions with Syntax and Example


String functions in C are used to manipulate and perform operations on strings. Here are four
commonly used string functions:

1. strlen: Returns the length of a string. Syntax: size_t strlen(const char *str);
Example:

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello, World!";
printf("Length of the string is %lu", strlen(str));
return 0;
}

2. strcpy: Copies one string to another. Syntax: char *strcpy(char *dest, const
char *src); Example:

#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello";
char dest[10];
strcpy(dest, src);
printf("Copied string: %s", dest);
return 0;
}

3. strcmp: Compares two strings. Syntax: int strcmp(const char *str1, const char
*str2); Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal");
} else {
printf("Strings are not equal");
}
return 0;
}
4. strcat: Concatenates (joins) two strings. Syntax: char *strcat(char *dest, const
char *src); Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s", str1);
return 0;

Q=6

1. What is User-Defined Data Type? Explain Structure in Detail. Show Different


Ways to Declare and Initialize Structure Variables.

A User-Defined Data Type (UDDT) in C allows programmers to create custom data types that
fit specific needs. struct, union, and enum are examples of user-defined data types in C.

Structure (struct): A structure in C is a user-defined data type that groups different data types
together under a single name. It's particularly useful for organizing data that belongs together.

Syntax:

c
struct StructureName {
dataType1 member1;
dataType2 member2;
// More members
};

Example:

c
struct Person {
char name[50];
int age;
float height;
};

Different Ways to Declare and Initialize Structure Variables:

1. Declaration and Initialization Separately:


c

struct Person person1; // Declaration


strcpy(person1.name, "Alice"); // Initialization
person1.age = 30;
person1.height = 5.5;

2. Combined Declaration and Initialization:

struct Person person1 = {"Alice", 30, 5.5};

3. Declaration of Multiple Variables:

struct Person person1, person2;

4. Initialization with Designated Initializers (C99 Standard):

struct Person person1 = {.name = "Alice", .age = 30, .height = 5.5};

2. Write a Short Note on File Handling Functions

File handling in C involves performing operations like creating, reading, writing, and closing
files. Here are some essential file handling functions:

1. fopen(): Opens a file and returns a file pointer.


o Syntax: FILE *fopen(const char *filename, const char *mode);
o Example:

FILE *filePtr = fopen("example.txt", "r");

2. fclose(): Closes an open file.


o Syntax: int fclose(FILE *stream);
o Example:

fclose(filePtr);

3. fgetc(): Reads a character from a file.


o Syntax: int fgetc(FILE *stream);
o Example:

char ch = fgetc(filePtr);

4. fputc(): Writes a character to a file.


o Syntax: int fputc(int char, FILE *stream);
o Example:

fputc('A', filePtr);

5. fgets(): Reads a string from a file.


o Syntax: char *fgets(char *str, int n, FILE *stream);
o Example:

char str[100];
fgets(str, 100, filePtr);

6. fputs(): Writes a string to a file.


o Syntax: int fputs(const char *str, FILE *stream);
o Example:

fputs("Hello, World!", filePtr);

7. fprintf(): Writes formatted output to a file.


o Syntax: int fprintf(FILE *stream, const char *format, ...);
o Example:

fprintf(filePtr, "Name: %s, Age: %d\n", "Alice", 30);

8. fscanf(): Reads formatted input from a file.


o Syntax: int fscanf(FILE *stream, const char *format, ...);
o Example:

fscanf(filePtr, "%s %d", name, &age);

You might also like