1. (a) Write an algorithm and draw a
corresponding flow chart to check whether
the given year is a leap year or not.
Answer :
1. Start
2. Input the year (Y)
3. If (Y is divisible by 4 and not divisible by 100) or (Y is divisible by 400), then
4. Display "Leap year"
5. Else
6. Display "Not a leap year"
7. End
(b) Write a C function isodd(num) that
accepts an integer argument and returns 1
if the argument is odd and 0 otherwise.
here's a simple C function isodd that checks if an integer is odd or not:
#include <stdio.h>
int isodd(int num) {
if (num % 2 != 0)
return 1; // odd
else
return 0; // even
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (isodd(num))
printf("%d is odd.\n", num);
else
printf("%d is even.\n", num);
return 0;
}
This function isodd takes an integer num as input and returns 1 if it's odd and 0 if it's even. The % operator is used to find the remainder of num divided by 2, if it's not zero, then the number is odd, otherwise, it's even.
(c) Write a C program that invokes this
function to generate numbers between the
given range.
Certainly! Below is a simple C program that invokes a function to generate random numbers within a given range using the rand() function from the standard C library:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to generate random numbers within a given range
int generateRandomNumber(int min, int max) {
return min + rand() % (max - min + 1);
}
int main() {
int minRange, maxRange, numOfNumbers;
// Seed the random number generator with current time
srand(time(NULL));
// Input the range
printf("Enter the minimum and maximum of the range (space separated): ");
scanf("%d %d", &minRange, &maxRange);
// Input the number of random numbers to generate
printf("Enter the number of random numbers to generate: ");
scanf("%d", &numOfNumbers);
// Generate and print the random numbers
printf("Generated random numbers:\n");
for (int i = 0; i < numOfNumbers; i++) {
printf("%d\n", generateRandomNumber(minRange, maxRange));
}
return 0;
}
In this program:
- We include necessary header files for standard input/output operations (stdio.h), memory allocation (stdlib.h), and time functions (time.h).
- The function generateRandomNumber() takes two parameters: min and max, representing the range within which random numbers should be generated.
- In the main() function, we seed the random number generator with the current time using srand(time(NULL)) to ensure different sequences of random numbers on each program execution.
- We prompt the user to input the minimum and maximum values of the range, as well as the number of random numbers to generate.
- Using a for loop, we generate the specified number of random numbers within the given range using generateRandomNumber() function and print them to the console.
(d) Define an Array. How do we declare and
initialize a single-dimensional array and a
2-dimensional array ? Explain with an
example for each.
In C, an array is a collection of elements of the same data type, stored in contiguous memory locations. Each element in an array is accessed by its index.
Declaring and Initializing a Single-Dimensional Array:
To declare and initialize a single-dimensional array in C, you specify the data type of the elements followed by the array name and its size within square brackets []. Here's an example:
#include <stdio.h>
int main() {
// Declare and initialize a single-dimensional array of integers
int numbers[5] = {10, 20, 30, 40, 50};
// Access and print elements of the array
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
In this example, we declare an array named numbers of size 5 to store integers. We initialize it with values {10, 20, 30, 40, 50}. Then, we loop through the array and print each element.
Declaring and Initializing a 2-Dimensional Array:
To declare and initialize a 2-dimensional array in C, you specify the data type of the elements followed by the array name and its dimensions within square brackets [][]. Here's an example:
#include <stdio.h>
int main() {
// Declare and initialize a 2-dimensional array of integers
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access and print elements of the array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
In this example, we declare a 2-dimensional array named matrix with dimensions 3x3 to store integers. We initialize it with values { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }. Then, we loop through the array and print each element. The nested loop structure is used to traverse through rows and columns of the 2-dimensional array.
(e) Write a C program to implement STRING
COPY operation that copies a string ‘‘str1’’
to another string ‘‘str2’’ without using
library function.
Sure, here's a simple C program to implement the string copy operation without using library functions:
#include <stdio.h>
// Function to copy a string from source to destination
void stringCopy(char *source, char *destination) {
// Loop through each character of source string until null character is encountered
int i = 0;
while (source[i] != '\0') {
// Copy each character from source to destination
destination[i] = source[i];
i++;
}
// Add null character at the end of destination to terminate the string
destination[i] = '\0';
}
int main() {
char str1[100], str2[100];
printf("Enter a string: ");
scanf("%s", str1);
// Call stringCopy function to copy str1 to str2
stringCopy(str1, str2);
// Print the copied string
printf("Copied string: %s\n", str2);
return 0;
}
In this program, the stringCopy function copies each character from the source string to the destination string until it encounters the null character ('\0'), which marks the end of the string. Finally, it adds a null character at the end of the destination string to terminate it properly.
(f) Write a C program to mantain a record of
‘‘n’’ student details using an array of
structures with structure-variables
(Rollnumber, Name, Marks1, Marks2,
Marks3, Marks4 and Grade). Define each
field of the structure with appropriate
datatype. Print the marks of the student of
given Rollnumber as input.
Here's a simple C program that maintains records of 'n' student details using an array of structures and allows the user to input a roll number to print the marks of the corresponding student:
#include <stdio.h>
#define MAX_STUDENTS 100
// Structure to hold student details
struct Student {
int rollNumber;
char name[50];
float marks[4];
char grade;
};
// Function to print marks of a student based on roll number
void printMarks(struct Student students[], int n, int roll) {
int i;
for (i = 0; i < n; i++) {
if (students[i].rollNumber == roll) {
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Name: %s\n", students[i].name);
printf("Marks:\n");
printf("Subject 1: %.2f\n", students[i].marks[0]);
printf("Subject 2: %.2f\n", students[i].marks[1]);
printf("Subject 3: %.2f\n", students[i].marks[2]);
printf("Subject 4: %.2f\n", students[i].marks[3]);
return;
}
}
printf("Student with Roll Number %d not found.\n", roll);
}
int main() {
int n, i, roll;
// Input the number of students
printf("Enter the number of students: ");
scanf("%d", &n);
// Array of structures to hold student details
struct Student students[MAX_STUDENTS];
// Input student details
for (i = 0; i < n; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Name: ");
scanf("%s", students[i].name);
printf("Marks for Subject 1: ");
scanf("%f", &students[i].marks[0]);
printf("Marks for Subject 2: ");
scanf("%f", &students[i].marks[1]);
printf("Marks for Subject 3: ");
scanf("%f", &students[i].marks[2]);
printf("Marks for Subject 4: ");
scanf("%f", &students[i].marks[3]);
}
// Input roll number to print marks
printf("\nEnter Roll Number to print marks: ");
scanf("%d", &roll);
// Print marks of the student with given roll number
printMarks(students, n, roll);
return 0;
}
This program prompts the user to input the number of students, then takes details for each student including roll number, name, and marks for four subjects. Finally, it prompts the user to input a roll number and prints the marks of the corresponding student if found, otherwise, it displays a message indicating that the student was not found.
2(a) Discuss dynamic memory allocation in C. Write and explain dynamic allocation functions in C.
(b) Write and explain any two pre-processor directives in C.
(c) Write a C program to find the sum of diagonal elements of a 3 * 3 matrix.
(a) Dynamic Memory Allocation in C:
Dynamic memory allocation in C allows the programmer to allocate memory at runtime, rather than at compile time. This is useful when you don't know the size of memory needed until the program is running. C provides several functions for dynamic memory allocation:
malloc(): This function allocates a block of memory of the specified size in bytes and returns a pointer of type void which can be cast into a pointer of any form.
calloc(): This function also allocates memory like malloc but initializes the allocated memory block with zero.
realloc(): This function changes the size of the previously allocated memory block. It may move the existing block to a new location, potentially copying its contents.
free(): This function deallocates the previously allocated memory block.
Here's a simple example demonstrating the use of these functions:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
// allocating memory using malloc
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed");
return 1;
}
// using the allocated memory
for (int i = 0; i < n; i++) {
ptr[i] = i + 1;
}
// printing the values
for (int i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
// deallocating memory
free(ptr);
return 0;
}
(b) Pre-processor Directives in C:
Two commonly used preprocessor directives in C are:
#include: This directive is used to include the contents of a file in the source file. It's typically used to include header files that contain declarations of functions or constants needed in the program.
#define: This directive is used to define macros. Macros are a way to specify constant values or short functions that will be replaced directly by the preprocessor before the compilation process.
(c) C program to find the sum of diagonal elements of a 3 * 3 matrix:
#include <stdio.h>
int main() {
int matrix[3][3];
int sum = 0;
printf("Enter elements of the matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("The entered matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
if (i == j) {
sum += matrix[i][j];
}
}
printf("\n");
}
printf("Sum of diagonal elements: %d\n", sum);
return 0;
}
This program first takes input for a 3x3 matrix, then prints the matrix, and finally calculates and prints the sum of the diagonal elements.
3. (a) Write a C program to create a file of numbers given by the user and copy odd numbers to odd.dat file and even numbers to even.dat file. 10
#include <stdio.h>
int main() {
FILE *inputFile, *oddFile, *evenFile;
int num;
// Open input file for reading
inputFile = fopen("numbers.txt", "r");
if (inputFile == NULL) {
printf("Error opening file.\n");
return 1;
}
// Open files for writing
oddFile = fopen("odd.dat", "w");
evenFile = fopen("even.dat", "w");
if (oddFile == NULL || evenFile == NULL) {
printf("Error creating files.\n");
return 1;
}
// Read numbers from input file and copy to appropriate files
while (fscanf(inputFile, "%d", &num) != EOF) {
if (num % 2 == 0) {
fprintf(evenFile, "%d\n", num);
} else {
fprintf(oddFile, "%d\n", num);
}
}
// Close all files
fclose(inputFile);
fclose(oddFile);
fclose(evenFile);
printf("Numbers copied to odd.dat and even.dat successfully.\n");
return 0;
}
To use this program, you need to create a text file named numbers.txt in the same directory as the program, and input the numbers separated by spaces or newlines. Then compile and run the program. After execution, you'll find odd.dat and even.dat files containing the odd and even numbers respectively.
(b) Using recursion, write a C program to find the factorial of a given number. 10
#include <stdio.h>
// Function to find factorial recursively
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0)
return 1;
// Recursive case: factorial of n is n times factorial of n-1
else
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
4. (a) Write a function to print the sum of the following series :
1 +` 2^2` + `3^3` + ... +` n^n` where ‘‘n’’ is passed as an argument to the function. 8
#include <stdio.h>
// Function to calculate the power of a number
int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
// Function to calculate the sum of the series
int sumOfSeries(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += power(i, i); // Add i^i to the sum
}
return sum;
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
// Check if n is valid
if (n < 1) {
printf("Please enter a positive integer greater than zero.\n");
return 1; // Exit with error
}
// Calculate and print the sum of the series
int result = sumOfSeries(n);
printf("Sum of the series = %d\n", result);
return 0;
}
(b) Write a program to calculate the number of vowels (a, e, i, o, u) separately in the entered string and display their individual count. 12
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100];
int vowels[5] = {0}; // to store counts of each vowel separately: a, e, i, o, u
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Convert the string to lowercase to simplify comparison
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
// Count the vowels
for (int i = 0; str[i]; i++) {
if (str[i] == 'a') {
vowels[0]++;
} else if (str[i] == 'e') {
vowels[1]++;
} else if (str[i] == 'i') {
vowels[2]++;
} else if (str[i] == 'o') {
vowels[3]++;
} else if (str[i] == 'u') {
vowels[4]++;
}
}
// Display the counts
printf("Count of 'a': %d\n", vowels[0]);
printf("Count of 'e': %d\n", vowels[1]);
printf("Count of 'i': %d\n", vowels[2]);
printf("Count of 'o': %d\n", vowels[3]);
printf("Count of 'u': %d\n", vowels[4]);
return 0;
}
Comments
Post a Comment