Understanding Programming Concepts: From Variables to Loops
List the advantages and disadvantages of global variable. Assume the two data files “numl.Txt” and “num2.Txt” containing integers. Merge these two files to the third file named ” file3.Txt”. Here, the integers of ” file3.T-xt” must be written in sorted order. ( 2+ 8 marks)
Sure, let’s start with the advantages and disadvantages of global variables:
Advantages
1.Accessibility: Global variables can be accessed from any part of the program, making them useful for sharing data across different functions or modules.
2.Simplicity: They can simplify code by avoiding the need to pass variables as parameters between functions
3.Persistence: Global variables retain their values throughout the execution of the program, which can be useful for storing state information.
Disadvantages
1.Complexity: They can make code harder to understand and debug, especially in large programs, because any part of the program can modify them.
2.Potential for Name Clashes: Since global variables are accessible from anywhere, there’s a risk of accidentally overwriting their values or causing conflicts with variables in other parts of the program.
3.Scope Issues: Global variables can lead to scope-related bugs, as it might not always be clear where a variable is being modified or accessed.
Now, for merging the two files “num1.Txt” and “num2.Txt” into a third file “file3.Txt” with sorted integers, you can use the following Python code:
# Read integers from num1.Txt and num2.Txt
with open(‘num1.Txt’, ‘r’) as file1, open(‘num2.Txt’, ‘r’) as file2:
nums1 = [int(num) for num in file1.Readlines()]
nums2 = [int(num) for num in file2.Readlines()]
# Merge and sort the integers
merged_nums = sorted(nums1 + nums2)
# Write sorted integers to file3.Txt
with open(‘file3.Txt’, ‘w’) as file3:
for num in merged_nums:
file3.Write(str(n
um) + ‘\n’)
2
How nested Structure is defined and initialized? Explain with an example. Write a program, using structure, to input records of 10 students. Members include name, roll number, marks obtained in math, C program and English. Display the records of students who have passed in C Program. ? ( 4+6 marks)
In C programming, a nested structure is defined by including one structure within another structure. Here’s an example:
#include <stdio.H>
struct Marks {
int math;
int c_program;
int english;
};
struct Student {
char name[50];
int roll_number;
struct Marks marks;
};
int main() {
struct Student students[10];
// Input records of 10 students
printf(“Enter records of 10 students:\n”);
for (int i = 0; i < 10; i++) {
printf(“Enter name of student %d: “, i + 1);
scanf(“%s”, students[i].Name);
printf(“Enter roll number of student %d: “, i + 1);
scanf(“%d”, &students[i].Roll_number);
printf(“Enter marks obtained in math: “);
scanf(“%d”, &students[i].Marks.Math);
printf(“Enter marks obtained in C program: “);
scanf(“%d”, &students[i].Marks.C_program);
printf(“Enter marks obtained in English: “);
scanf(“%d”, &students[i].Marks.English);
}
// Display records of students who have passed in C Program
printf(“\nRecords of students who have passed in C Program:\n”);
for (int i = 0; i < 10; i++) {
if (students[i].Marks.C_program >= 50) {
printf(“Name: %s\n”, students[i].Name);
printf(“Roll Number: %d\n”, students[i].Roll_number);
printf(“Math Marks: %d\n”, students[i].Marks.Math);
printf(“C Program Marks: %d\n”,students[i].Marks.C_program);
printf(“English Marks: %d\n”, students[i].Marks.English);
printf(“\n”);
}
}
return 0;
}
When do we use for loop and while loop? Compare the while and do while loop with suitable example. Write a program to find average, minimum and maximum age in a class of 20 students. ? (2+2+6 marks )
We use a for loop when we know the number of iterations beforehand, such as when looping through elements in an array.
We use a while loop when we’re unsure of the number of iterations needed or when the loop condition depends on some external factor.
Here’s a comparison between while and do-while loops:
.While Loop: It checks the condition before entering the loop. If the condition is false initially, the loop won’t execute at all.
Int i = 0;
While (i < 5) {
System.Out.Println(i);
I++
}
Do-While Loop: It executes the block of code first, then checks the condition. This ensures the block of code executes at least once.
int i = 0;
do {
System.Out.Println(i);
i++;
} while (i <
5);
For the program to find average, minimum, and maximum age in a class of 20 students, here’s a sample Java program:
import java.Util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.In);
int totalAge = 0;
int minAge = Integer.MAX_VALUE;
int maxAge = Integer.MIN_VALUE;
for (int i = 1; i <= 20; i++) {
System.Out.Print(“Enter age of student ” + i + “: “);
int age = scanner.NextInt();
totalAge += age;
if (age < minAge) {
minAge = age;
}
if (age > maxAge) {
maxAge = age;
}
}
double averageAge = (double) totalAge / 20;
System.Out.Println(“Average age: ” + averageAge);
System.Out.Println(“Minimum age: ” + minAge);
System.Out.Println(“Maximum
age: ” + maxAge);
}
}
What is an array? How an array can be passed as function argument? Write a program to arrange an array having 10 integer numbers in ascending order using function. ( 2+2+6 marks)
An array is a data structure that stores a fixed-size sequential collection of elements of the same type. It allows you to store multiple values of the same data type under a single variable name. Arrays can be passed as function arguments by specifying the array’s name without square brackets. When an array is passed to a function, it is passed by reference, allowing the function to modify the original array.
Here’s a program in C to arrange an array of 10 integers in ascending order using a function:
#include <stdio.H>
// Function to swap two integers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to arrange an array in ascending order
void arrangeAscending(int arr[], int size) {
for (int i = 0; i < size – 1; i++) {
for (int j = 0; j < size – i – 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf(“%d “, arr[i]);
}
printf(“\n”);
}
int main() {
int arr[10] = {5, 2, 9, 1, 7, 4, 8, 3, 6, 0};
int size = sizeof(arr) / sizeof(arr[0]);
printf(“Original array: “);
printArray(arr, size);
arrangeAscending(arr, size);
printf(“Array in ascending order: “);
p
rintArray(arr, size);
return 0;
}
This program defines three functions:
‘swap’: Swaps two integers.
‘arrangeAscending’: Arranges an array in ascending order using bubble sort.
‘printArray’: Prints the elements of an array.
In the :main’ function, an array of 10 integers is declared and initialized, then passed to the ‘arrangeAscending’function to sort it in ascending order. Finally, the sorted array is printed.
Explain different control structures in C. Write a program in C to perform different arithmetic operations on two integers and display the result based on choice made by user using switch statement?. ( 4+6 marks)
In C, control structures include:
1?Sequential Structure: Executing statements one after another.
2.Selection Structure: Making decisions based on conditions, like if-else statements
3.Repetition Structure: Executing a block of code repeatedly, like for loops, while loops, and do-while loops
Here’s a program in C to perform different arithmetic operations on two integers based on the user’s choice using a switch statement:
#include <stdio.H>
int main() {
int num1, num2, choice, result;
printf(“Enter two integers: “);
scanf(“%d %d”, &num1, &num2);
printf(“Choose an operation:\n”);
printf(“1. Addition\n”);
printf(“2. Subtraction\n”);
printf(“3. Multiplication\n”);
printf(“4. Division\n”);
printf(“Enter your choice: “);
scanf(“%d”, &choice);
switch(choice) {
case 1:
result = num1 + num2;
printf(“Result: %d\n”, result);
break;
case 2:
result = num1 – num2;
printf(“Result: %d\n”, result);
break;
case 3:
result = num1 * num2;
printf(“Result: %d\n”, result);
break;
case 4:
if(num2 != 0) {
result = num1 / num2;
printf(“Result: %d\n”, result);
} else {
printf(“Cannot divide by zero\n”);
}
break;
default:
printf(“Inva
lid choice\n”);
}
return 0;
}
Differentiate between structure and union? Write a program to read employ id, name, post and salary of 20 employee and display detail of those employee whose post is “clerk”. ? ( 4+6 marks)
Sure, I can help with that!
Structure vs Union:
1.Structure: A structure is a user-defined data type in C that allows you to combine different data types under a single name. Each element within a structure has its own memory location.
2.Union: A union, like a structure, allows you to combine different data types under a single name. However, in a union, all elements share the same memory location, and the size of the union is determined by the largest member within it.
Example Program:
#include <stdio.H>
#include <string.H>
// Define a structure for employee details
struct Employee {
int emp_id;
char name[50];
char post[50];
float salary;
};
int main() {
// Define an array of structures to store details of 20 employees
struct Employee emp[20];
// Read details of 20 employees
for(int i = 0; i < 20; i++) {
printf(“Enter details for employee %d:\n”, i+1);
printf(“Employee ID: “);
scanf(“%d”, &emp[i].Emp_id);
printf(“Name: “);
scanf(“%s”, emp[i].Name); // Assuming names have no spaces
printf(“Post: “);
scanf(“%s”, emp[i].Post); // Assuming posts have no spaces
printf(“Salary: “);
scanf(“%f”, &emp[i].Salary);
}
// Display details of employees whose post is “clerk”
printf(“\nDetails of employees with post ‘clerk’:\n”);
for(int i = 0; i < 20; i++) {
if(strcmp(emp[i].Post, “clerk”) == 0) {
printf(“Employee ID: %d\n”, emp[i].Emp_id);
printf(“Name: %s\n”, emp[i].Name);
printf(“Post: %s\n”, emp[i].Post);
printf(“Salary: %.2f\n\n”, emp[i].Salary
}
}
return 0;
}
What is two-dimensional array? How it can be declared? Explain. Write a program to add two square matrices and display the result?
A two-dimensional array is an array of arrays. It’s like a table with rows and columns, where each element is referenced by two indices.
To declare a 2D array in most programming languages, you specify the number of rows and columns. For example, in Java:
int[][] matrix = new int[3][3];
This creates a 3×3 matrix with all elements initialized to 0. You can also initialize it with values:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
To add two square matrices, you need to iterate through each element of the matrices and add corresponding elements together. Here’s a Java program to do that:
public class MatrixAddition {
public static void main(String[] args) {
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] result = new int[3][3];
// Adding matrices
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Displaying the result
System.Out.Println(“Resultant Matrix:”);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.Out.Print(result[i][j] + ” “);
}
System.Out.Println(
}
}
}
What is function? Explain the component of user defined Function .Write a program to find sum of first n natural numbers using recursion.
A function is a block of organized, reusable code that performs a specific task. In programming, functions provide modularity and abstraction, allowing you to break down a program into smaller, manageable pieces.
Components of a user-defined function typically include:
1.Function name: It is the identifier for the function
2.Parameters: These are the inputs that the function takes. They are optional
3.Function body: This contains the code that defines what the function does
4.Return statement: It specifies the value that the function should return, if any
Here’s a Python program to find the sum of the first n natural numbers using recursion:
def sum_of_natural_numbers(n):
if n <= 0:
return 0
else:
return n + sum_of_natural_numbers(n – 1)
# Example usage
n = 5
print(“Sum of first”, n, “natural numbers:”, sum_of_natural_num
bers(n))
What is loop? Explain different types of loop with syntax and semantic Write a program to display first 10 terms of sequence 5, 3, 10, 5, 16, 8,4,…
A loop is a programming construct that allows you to repeat a block of code multiple times until a certain condition is met. There are several types of loops commonly used in programming languages:
1.For Loop: It iterates over a sequence (e.G., a range of numbers) and executes the code block for each iteration
Syntax:
for variable in sequence:
# code block
2.While Loop: It repeats a block of code as long as a specified condition is true
Syntax:
while condition:
# code block
3.Do-While Loop (not available in all programming languages): It is similar to the while loop but always executes the block of code at least once before checking the condition.
Syntax:
do {
# code block
} while (condition
Here’s a Python program to display the first 10 terms of the sequence 5, 3, 10, 5, 16, 8, 4:
# Initialize variables
sequence = [5] # Starting with 5
length = 10 # Total terms to display
# Generate the sequence
for i in range(1, length):
if sequence[i-1] % 2 == 0:
sequence.Append(sequence[i-1] // 2)
else:
sequence.Append(sequence[i-1] * 2)
# Display the sequence
for term in sequence:
print(term,
end=’ ‘)
Output
5 3 10 5 16 8 4 2 4 2
