FOP assignment1
FOP assignment1
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';
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
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:
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;
}
Arithmetic Operators:
Arithmetic operators in C are used to perform mathematical operations. Here are the common
arithmetic operators:
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
return 0;
}
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;
c
#include <stdio.h>
int main() {
int a = 10, b = 5;
int max;
return 0;
}
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.
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;
}
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;
}
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;
}
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.
• %d or %i - Integer
• %f - Floating-point number
• %lf - Double
• %c - Character
• %s - String
• %x - Hexadecimal integer
• %o - Octal integer
• %u - Unsigned integer
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
c
#include <stdio.h>
int main() {
int num = 255;
return 0;
}
Output:
Decimal: 255
Hexadecimal: ff
Octal: 377
Unsigned: 255
c
#include <stdio.h>
int main() {
float pi = 3.1415926535;
Output:
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);
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;
}
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>
int main() {
// Create an instance of the structure
struct Student student1;
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.
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.
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.
c
#include <stdio.h>
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.
c
#include <stdio.h>
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:
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.
c
#include <stdio.h>
int main() {
FILE *file;
return 0;
}
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++;
}
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;
fclose(file);
return 0;
}
2022
Q=1
• 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
• 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
• 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:
• 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:
• 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:
Q=2
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;
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.
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;.
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.
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:
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.
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:
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:
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:
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;
}
break and continue are control statements that alter the flow of loops.
break:
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;
}
continue:
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);
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.
Example:
c
#include <stdio.h>
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>
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()
Output:
25
50
50
27
Q=5
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
return 0;
}
Advantages:
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!");
}
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.
c
#include <stdio.h>
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.
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
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;
};
File handling in C involves performing operations like creating, reading, writing, and closing
files. Here are some essential file handling functions:
fclose(filePtr);
char ch = fgetc(filePtr);
fputc('A', filePtr);
char str[100];
fgets(str, 100, filePtr);