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

Problem Statements C programming

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

Problem Statements C programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Problem Statement -1

Title: Transpose of a 2D Matrix

Objective:
Design and implement a C program that accepts a 2D matrix of integers, computes its transpose,
and displays both the original and transposed matrices. Transposing a matrix involves swapping
its rows and columns, such that the element at position [i][j] in the original matrix is moved to
position [j][i] in the transposed matrix.

Problem Description:

1. Input Requirements:
o The program should prompt the user to input the dimensions of the matrix
(number of rows and columns), both of which must be positive integers within a
predefined range.
o The user should provide integer values to populate the matrix elements.
2. Processing Requirements:
o The program should compute the transpose of the input matrix.
o During transposition, the program swaps rows and columns of the matrix.
Specifically, the element at position [i][j] in the input matrix should be placed
at position [j][i] in the transposed matrix.
3. Output Requirements:
o Display the original matrix in its entered format.
o Display the transposed matrix after processing, ensuring it adheres to the correct
transposed structure.

Functional Requirements:

• Input Validation:
o The number of rows and columns must be within the range 1 to 10.
o The program should gracefully handle any invalid input values (e.g., non-integer
or out-of-range dimensions).
• Matrix Transposition:
o If the input matrix has m rows and n columns, the resulting transposed matrix will
have n rows and m columns.

Constraints:
1. The matrix dimensions (number of rows and columns) must be integers between 1 and
10.
2. The elements of the matrix must be integers.
3. The maximum size of the matrix is limited to 10x10 to ensure efficient processing and
avoid excessive memory usage.

Test Cases:

Test Input Expected Output Explanation


Case
1 Rows: 2, Original Matrix: Transposing a 2x3 matrix results in a
Columns: 3, 1 2 3, 3x2 matrix.
Matrix: 4 5 6
1 2 3, Transposed Matrix:
4 5 6 1 4,
2 5,
3 6
2 Rows: 3, Original Matrix: Transposing a 3x2 matrix results in a
Columns: 2, 1 2, 2x3 matrix.
Matrix: 3 4,
1 2, 5 6
3 4, Transposed Matrix:
5 6 1 3 5,
2 4 6
3 Rows: 1, Original Matrix: 7 8 Transposing a 1x3 matrix results in a
Columns: 3, 9 Transposed Matrix: 3x1 matrix.
Matrix: 7, 8, 9
7 8 9
4 Rows: 1, Original Matrix: 10 A single element matrix remains
Columns: 1, Transposed Matrix: unchanged when transposed.
Matrix: 10 10
5 Rows: 2, Original Matrix: Transposing a square matrix swaps
Columns: 2, 1 2, rows with columns but dimensions
Matrix: 3 4 remain unchanged.
1 2, Transposed Matrix:
3 4 1 3,
2 4

Expected Solution:

• The program should correctly read the matrix dimensions and elements, process the
transposition, and output both the original and transposed matrices.
• The implementation should be efficient and modular, with clear separation of input
handling, transposition logic, and output formatting.
• Edge cases such as a single row/column matrix or a square matrix should be handled
appropriately.

Solution:
#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to transpose a matrix


void transpose(int arr[MAX_ROWS][MAX_COLS], int rows, int cols) {
int i, j, transposed[MAX_COLS][MAX_ROWS]; // Transposed matrix

// Perform transposition
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
transposed[j][i] = arr[i][j]; // Swap rows and columns
}
}

// Print the transposed matrix


printf("\nTransposed Matrix:\n");
for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
printf("%d ", transposed[i][j]);
}
printf("\n");
}
}

int main() {
int arr[MAX_ROWS][MAX_COLS];
int i, j, rows, cols;
clrscr();
// Input number of rows and columns
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

// Input matrix elements


printf("Enter elements of the matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &arr[i][j]);
}
}

// Print the original matrix


printf("\nOriginal Matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

// Call the transpose function


transpose(arr, rows, cols);

return 0;
}

Problem Statement-2

Title: Check if a Given Integer Number is a Palindrome

Objective:
Develop a C program to check whether a given unsigned integer number is a palindrome. A
palindrome number is one that reads the same backward as forward. The program should include
input validation, ensuring the entered number falls within a specified range and displays
appropriate error messages for invalid inputs.

Problem Description

1. Input Requirements:
o The program should prompt the user to input an unsigned integer number.
o The input number must lie within the range 0 to 1,000,000,000 (inclusive).
2. Processing Requirements:
o The program should reverse the given number and compare it to the original
number.
o If the reversed number matches the original number, the input is a palindrome.
o Input validation must ensure that:
▪ The input is a valid unsigned integer.
▪ The number is within the specified range.
3. Output Requirements:
o If the input is invalid (non-integer or out of range), display an appropriate error
message.
o If the input is valid:
▪ Print whether the number is a palindrome or not.

Functional Requirements
1. Input Validation:
o Ensure that the input is an unsigned integer.
o Check if the input is within the range [0, 1,000,000,000].
o If the input fails validation, provide an error message and terminate the program.
2. Palindrome Check:
o Reverse the digits of the given number.
o Compare the reversed number with the original number.
o Return a result indicating whether the number is a palindrome.
3. Error Handling:
o Display appropriate error messages for:
▪ Non-integer inputs.
▪ Numbers outside the valid range.

Constraints

1. The input number must be an unsigned integer.


2. The range of valid inputs is 0 to 1,000,000,000.
3. The program must handle inputs efficiently without unnecessary computation.
4. The program should use modular design, implementing the palindrome check as a
separate function.

Test Cases

Test Input Expected Output Explanation


Case
1 121 121 is a palindrome. The reversed number is the
same as the original number.
2 123 123 is not a palindrome. The reversed number (321) is
not the same as the original
number.
3 0 0 is a palindrome. A single-digit number is
always a palindrome.
4 1000000000 1000000000 is not a palindrome. The reversed number is 1,
which is not the same as the
original.
5 -121 Error: Invalid input. Please Negative numbers are not
enter a valid integer.
valid for this program.
6 abcd Error: Invalid input. Please The input is non-numeric.
enter a valid integer.
7 1000000001 Error: Number out of range. The input exceeds the valid
Please enter a number between 0
range.
and 1000000000.
Expected Behavior

• For valid inputs, the program will determine if the number is a palindrome and display
the result.
• For invalid inputs, appropriate error messages will guide the user to enter valid data.

Justification

This program ensures robust handling of user input and adheres to constraints, making it suitable
for checking palindrome numbers in real-world applications. The use of modular programming
promotes readability and maintainability.

Solution:
#include <stdio.h>
// Function to check if a number is a palindrome
int isPalindrome(unsigned long number) {
unsigned long reversed = 0, original = number, remainder;

// Reverse the number


while (number != 0) {
remainder = number % 10;
reversed = reversed * 10 + remainder;
number /= 10;
}

// Check if original number equals reversed number


if(original == reversed)
return 1;
else
return 0;
}

int main() {
unsigned long number;
const long MIN_RANGE = 0; // Minimum valid input
const long MAX_RANGE = 1000000000; // Maximum valid input (10
digits)
// Prompt user for input
printf("Enter a number between %ld and %ld: ", MIN_RANGE,
MAX_RANGE);

// Input validation: Check if input is an integer


if (scanf("%lu", &number) != 1) {
printf("Error: Invalid input. Please enter a valid integer.\n");
return 1;
}
// Check if number is within the specified range
if (number < MIN_RANGE || number > MAX_RANGE) {
printf("Error: Number out of range. Please enter a number between
%lld and %lld.\n", MIN_RANGE, MAX_RANGE);
return 1;
}

// Check if the number is a palindrome


if (isPalindrome(number)) {
printf("%lu is a palindrome.\n", number);
} else {
printf("%lu is not a palindrome.\n", number);
}
return 0;
}

Problem Statement-3

Title: Simple Calculator with Integer and Float Data Type Selection

Objective:

Design and implement a C program that functions as a simple calculator to perform arithmetic
operations on integer or float numbers. The program should allow users to choose the data type
(integer or float) and input two numbers along with an operator. It then computes the result
based on the specified operation and displays it, while also handling errors such as invalid inputs
and division/modulo by zero.

Problem Description:

1. Input Requirements:
o The user is prompted to select the data type:
▪ i for integer calculations.
▪ f for float calculations.
o Depending on the selected data type:
▪ For integers, the program accepts two integers and an arithmetic operator.
▪ For floats, the program accepts two floating-point numbers and an
arithmetic operator.
2. Processing Requirements:
o Perform the specified arithmetic operation (+, -, *, /, %):
▪ % (modulus) is only valid for integers.
o Validate the inputs and handle errors:
▪Check for valid operator symbols.
▪Ensure the second operand is non-zero for division or modulus operations.
3. Output Requirements:
o Display the computed result formatted according to the selected data type.
o Display error messages for:
▪ Invalid operator.
▪ Division or modulus by zero.
▪ Invalid data type selection.

Functional Requirements:

1. Data Type Selection:


o The program must clearly prompt the user to choose between integer (i) and float
(f) operations.
o Any invalid data type input should result in an error message.
2. Arithmetic Operations:
o Supported operations:
▪ Addition (+)
▪ Subtraction (-)
▪ Multiplication (*)
▪ Division (/)
▪ Modulus (%) (for integers only).
o The program must execute the chosen operation and display the result.
3. Error Handling:
o Handle division or modulus by zero with appropriate error messages.
o Display an error message if the user enters an invalid operator.
o Validate that numeric inputs correspond to the selected data type.

Constraints:

1. The program should handle input values within the range of integers and float numbers
supported by the system.
2. For floats, results should be displayed up to two decimal places.
3. Modulus operation (%) should only be allowed when integers are selected.
4. Input validation should ensure proper functioning of the program for all valid cases.

Test Cases:

Test Input Expected Output Explanation


Case
1 Data Type: i, Result: 8 Valid integer addition.
Input: 5 + 3
2 Data Type: i, Error: Division by zero is Handles division by zero error for
Input: 7 / 0 not allowed. integers.
3 Data Type: i, Error: Modulo by zero is Handles modulus by zero error for
Input: 10 % 0 not allowed. integers.
4 Data Type: f, Result: 3.30 Valid floating-point subtraction.
Input: 4.5 -
1.2
5 Data Type: f, Error: Division by zero is Handles division by zero error for
Input: 9.2 / not allowed. floats.
0
6 Data Type: x Error: Invalid data type Invalid data type selection.
selected.
7 Data Type: i, Error: Invalid operator. Handles invalid operator for integer
Input: 4 & 2 calculations.
8 Data Type: f, Result: 23.10 Valid floating-point multiplication.
Input: 10.5 *
2.2

Expected Behavior:

• The program correctly performs arithmetic operations based on the selected data type.
• Proper error messages guide users in cases of invalid input or errors.
• Supports modular design for maintainability and clarity.

Solution:
#include <stdio.h>
void calculator()
{
char operator;
char data_type;
printf("Choose the data type (i for integer, f for float): ");
scanf(" %c", &data_type); // Notice the space before %c to ignore
newline
if (data_type == 'i') {
int num1, num2, result;
printf("Enter an integer expression (e.g., 5 + 3): ");
scanf("%d %c %d", &num1, &operator, &num2);

switch (operator)
{
case '+':
result = num1 + num2;
printf("Result: %d\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %d\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %d\n", result);
break;
case '/':
if (num2 != 0)
{
printf("Result: %d\n", num1 / num2);
}
else
{
printf("Error: Division by zero is not allowed.\n");
}
break;
case '%':
if (num2 != 0)
{
printf("Result: %d\n", num1 % num2);
} else
{
printf("Error: Modulo by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator.\n");
}
}
else
if (data_type == 'f')
{
float num1, num2, result;
printf("Enter a float expression (e.g., 5.5 + 3.2): ");
scanf("%f %c %f", &num1, &operator, &num2);
switch (operator)
{
case '+':
result = num1 + num2;
printf("Result: %.2f\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2f\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2f\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2f\n", result);
}
else
{
printf("Error: Division by zero is not allowed.\n");
}
break;
default: printf("Error: Invalid operator.\n");
}
} else
{
printf("Error: Invalid data type selected.\n");
}
}

int main()
{
calculator();
return 0;
}

Problem Statement-4

Title: Determining Whether a Given Year is a Leap Year

Objective:

Create a C program to determine whether a given year is a leap year or not. The program should
accept an integer input representing a year, validate the input, and use logical conditions to verify
the leap year status. Appropriate messages should be displayed for invalid inputs and the result
of the calculation.

Problem Description:

1. Input Requirements:
o The user must input an integer representing the year.
o Input validation must ensure that the entered value is an integer.
2. Processing Requirements:
o A year is considered a leap year if:
▪ It is divisible by 4 but not divisible by 100, OR
▪ It is divisible by 400.
o The program must verify the leap year status using these conditions.
3. Output Requirements:
o If the year is a leap year, display:
"<year> is a leap year."
o If the year is not a leap year, display:
"<year> is not a leap year."
o For invalid inputs (non-integer values), display an appropriate error message.

Functional Requirements:

1. Input Validation:
o Check if the entered value is an integer.
o For invalid inputs, display an error message and terminate the program.
2. Leap Year Check:
o Implement a function isLeapYear(int year) to determine if the year satisfies
leap year conditions.
o Use the function in the main program for modularity and clarity.
3. Error Handling:
o Ensure non-integer inputs are identified and handled gracefully.

Constraints:

1. The input must be a valid integer.


2. The program should handle both positive and negative year inputs to account for
historical and future dates.
3. Ensure modular design with the use of functions for better readability and
maintainability.

Test Cases:

Test Input Expected Output Explanation


Case
1 2024 2024 is a leap year. 2024 is divisible by 4 and not
divisible by 100.
2 1900 1900 is not a leap year. 1900 is divisible by 100 but not
divisible by 400.
3 2000 2000 is a leap year. 2000 is divisible by 400, making
it a leap year.
4 2023 2023 is not a leap year. 2023 is not divisible by 4.
5 abcd Error: Invalid input. Please Handles invalid non-numeric
enter an integer year.
input gracefully.
6 -400 -400 is a leap year. Historical year handling: -400 is
divisible by 400.

Expected Behavior:

• The program should accurately identify leap years based on the specified conditions.
• Non-integer inputs should trigger an appropriate error message.
• Modular design ensures the separation of input validation, leap year computation, and
result display.

Solution:
#include <stdio.h>
// Function to determine if a year is a leap year
int isLeapYear(int year) {
// Leap year conditions
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1; // Leap year
}
return 0; // Not a leap year
}
int main() {
int year;

// Prompt user for input


printf("Enter a year: ");
if (scanf("%d", &year) != 1) {
printf("Error: Invalid input. Please enter an integer
year.\n");
return 1; // Exit program on invalid input
}
// Check and display if the year is a leap year
if (isLeapYear(year)) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}

Problem Statement-5

Title: Calculate the Factorial of a Given Integer using Call by Value and Call by Reference

Objective:
Design and implement a C program to calculate the factorial of a positive integer using two
approaches: Call by Value and Call by Reference. The program should validate user input,
compute the factorial using both methods, and display the results.

Problem Description:

1. Input Requirements:
o The user must input a positive integer (n) for which the factorial is to be
calculated.
o Input validation must ensure that the entered value is a positive integer (including
zero).
2. Processing Requirements:
o Implement two separate functions:
1. Call by Value: A function that takes the input number and returns its
factorial without modifying the original variable.
2. Call by Reference: A function that takes the input number and a pointer
to store the result, directly modifying the variable passed by the caller.
o The factorial calculation should be performed iteratively in both methods.
3. Output Requirements:
o Display the calculated factorial using both Call by Value and Call by Reference
methods.
o If the input is invalid (negative or non-integer), display an appropriate error
message.

Functional Requirements:

1. Input Validation:
o Accept input using scanf and validate whether it is a positive integer.
o Handle invalid inputs gracefully by displaying an error message and terminating
the program.
2. Factorial Calculation:
o Call by Value: Return the factorial value computed within the function.
o Call by Reference: Modify the value at the memory location of the provided
pointer.
3. Output Formatting:
o Clearly distinguish between results computed using the two methods.
o Use descriptive and user-friendly messages to display results.

Constraints:
1. Input must be a positive integer (n >= 0).
2. Ensure the program handles large inputs within the range of the data type int in C.
3. Modular design with separate functions for each calculation approach is required.

Test Cases:

Test Input Expected Output Explanation


Case
1 5 Factorial of 5 using Call by Value: Factorial of 5 is
120Factorial of 5 using Call by
calculated correctly
Reference: 120
using both methods.
2 0 Factorial of 0 using Call by Value: Factorial of 0 is defined
1Factorial of 0 using Call by Reference:
1
as 1.
3 -3 Error: Please enter a valid positive Negative inputs are
integer.
invalid.
4 abcd Error: Please enter a valid positive Non-integer input is
integer.
invalid.
5 12 Factorial of 12 using Call by Value: Factorial of a larger
479001600Factorial of 12 using Call by
number is calculated
Reference: 479001600
correctly.

Expected Behavior:

• The program computes the factorial using two methods: Call by Value and Call by
Reference.
• Input validation ensures only valid positive integers are processed.
• Modular design separates input validation, factorial computation, and result display for
better readability and maintainability.

Solution:
#include <stdio.h>

// Function to calculate factorial (Call by Value)


unsigned long factorialByValue(int n) {
unsigned long result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= i;
}
return result;
}

// Function to calculate factorial (Call by Reference)


void factorialByReference(int n, unsigned long *result) {
int i;
*result = 1;
for (i = 1; i <= n; i++) {
*result *= i;
}
}

int main() {
int number;
unsigned long factValue, factRef;

// Input number for factorial calculation


printf("Enter a positive integer: ");
if (scanf("%d", &number) != 1 || number < 0) {
printf("Error: Please enter a valid positive integer.\n");
return 1;
}

// Factorial using Call by Value


factValue = factorialByValue(number);
printf("Factorial of %d using Call by Value: %lu\n", number,
factValue);

// Factorial using Call by Reference


factorialByReference(number, &factRef);
printf("Factorial of %d using Call by Reference: %lu\n", number,
factRef);

return 0;
}

Problem Statement: 6

Title: Password Validation Program in C

Objective:

To design a C program that validates user-entered passwords based on a set of predefined


security criteria. The program provides targeted feedback for invalid passwords, guiding the user
to create a secure and valid password.

Problem Description:

The program accepts a password as input and validates it based on the following rules:

1. Length: The password must be exactly 8 characters long.


2. Character Requirements:
o At least one uppercase letter.
o At least one lowercase letter.
o At least one numeric digit.
o At least one special character from the set: @, #, $, %, ^, &, *, !, ?.

The program:

1. Accepts a password input from the user.


2. Validates the password against the specified criteria.
3. Displays specific error messages for unmet conditions.
4. Indicates whether the password is valid or invalid.

Constraints:

1. The password must be exactly 8 characters long.


2. Spaces are not considered valid characters in the password.

Expected Outcomes:

1. A valid password will display: "Password is valid."


2. Invalid passwords will generate specific error messages for each unmet condition.

Test Cases for Password Validation

Test Input Password Expected Output Validation


Case Outcome
No.
1 Pass123! "Password is valid." Valid
2 short "Error: Password must be exactly 8 characters Invalid
long."
3 lowercase1! "Error: Password must contain at least one Invalid
uppercase letter."
4 UPPERCASE1! "Error: Password must contain at least one Invalid
lowercase letter."
5 Password123 "Error: Password must contain at least one Invalid
special character (@#$%^&*!?)."
6 12345678 "Error: Password must contain at least one Invalid
uppercase letter."Error: Password must
contain at least one lowercase letter."Error:
Password must contain at least one special
character (@#$%^&*!?).
7 Pass@! "Error: Password must be exactly 8 characters Invalid
long."
8 1234$abc "Password is valid." Valid
9 nospecial123 "Error: Password must contain at least one Invalid
special character (@#$%^&*!?)."
10 A1b@Xyz! "Password is valid." Valid

Applications:

1. Password validation for secure login systems.


2. Educational tool to promote secure password practices.
3. Real-world applications for improving user authentication and reducing weak passwords.

This problem statement and the corresponding test cases define the program’s requirements and
ensure that the validation is strictly according to the rules for password strength.

Solution:

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

// Function to validate the password


int validatePassword(const char *password) {
int i;
int length = strlen(password);
int hasUpper = 0, hasLower = 0, hasDigit = 0, hasSpecial = 0;

// Check length
if (length < 8) {
printf("Error: Password must be at least 8 characters long.\n");
return 0;
}

// Check character types


for (i = 0; i < length; i++) {
if (isupper(password[i]))
hasUpper = 1;
else if (islower(password[i]))
hasLower = 1;
else if (isdigit(password[i]))
hasDigit = 1;
else if (strchr("@#$%^&*!?", password[i]))
hasSpecial = 1;
}

// Display specific error messages


if (!hasUpper)
printf("Error: Password must contain at least one uppercase
letter.\n");
if (!hasLower)
printf("Error: Password must contain at least one lowercase
letter.\n");
if (!hasDigit)
printf("Error: Password must contain at least one digit.\n");
if (!hasSpecial)
printf("Error: Password must contain at least one special
character (@#$%^&*!?).\n");

// Return 1 if all conditions are met


return hasUpper && hasLower && hasDigit && hasSpecial;
}

int main() {
char password[100];

// Input password
printf("Enter your password: ");
scanf("%s", password);

// Validate the password


if (validatePassword(password)) {
printf("Password is valid.\n");
} else {
printf("Password is invalid.\n");
}

return 0;
}

Problem Statement -7

Title: Demonstration of Structure for Storing and Displaying Student Records


Objective:

The objective of this program is to demonstrate the usage of structures in C for storing and
displaying student records, including personal information such as name, roll number, date of
birth, and division.

Problem Description:

You are tasked with writing a C program that stores and displays the details of a student using
structures. The program should define a struct for the student's date of birth and another
struct for storing the student's details, including the student's name, roll number, date of birth,
and division. The program should allow the user to input these details and then display them
back.

1. Input Details:
o The user is prompted to input the following details for the student:
▪ Student's name (string up to 50 characters)
▪ Student's roll number (integer)
▪ Student's date of birth:
▪ Day (integer between 1 and 31)
▪ Month (integer between 1 and 12)
▪ Year (integer)
▪ Student's division (string of length up to 5 characters)
2. Output:
o The program should display the following information about the student:
▪ Student's name
▪ Student's roll number
▪ Student's date of birth in the format DD/MM/YYYY
▪ Student's division
3. Constraints:
o The date should be entered as day, month, and year as integers.
o All inputs must be validated to ensure that they are within the correct ranges (for
example, valid days and months).
o The program should handle memory for strings and manage input using the fgets()
function to avoid overflow.

Functionality:

1. Structure Definition:
o A structure Date to store the day, month, and year of the student's date of birth.
o A structure Student that includes the student's name, roll number, a Date structure
for the date of birth, and division.
2. Input:
o The program should read and store the student's details using a function
inputStudentDetails(), which accepts a pointer to a Student structure.
3. Output:
o The program should display the student details using the function
displayStudentDetails().

Example:
Sample Input:
Enter student name: John Doe
Enter roll number: 123
Enter day of birth (1-31): 15
Enter month of birth (1-12): 5
Enter year of birth: 2000
Enter division: A
Sample Output:
Student Information:
Name: John Doe
Roll Number: 123
Date of Birth: 15/5/2000
Division: A
Expected Outcomes:

1. The program should correctly read and store the student's information.
2. The program should display the student's information correctly, ensuring proper formatting for
the date of birth.
3. The program should manage input and output cleanly without any issues of buffer overflow or
incorrect data display.

This problem statement outlines the requirements for a student record system that demonstrates
the use of structures in C programming for organizing and managing student-related data.

Solution:

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

// Define a structure to store date information (day, month, year)


struct Date {
int day;
int month;
int year;
};

// Define a structure to store student details


struct Student {
char name[50]; // Student Name
int rollNumber; // Roll Number
struct Date dob; // Date of Birth (using Date structure)
char division[5]; // Division
};

// Function to input student details


void inputStudentDetails(struct Student *student) {
// Prompt and read student details
printf("Enter student name: ");
fgets(student->name, sizeof(student->name), stdin);
student->name[strcspn(student->name, "\n")] = 0; // Remove
newline character

printf("Enter roll number: ");


scanf("%d", &student->rollNumber);
getchar(); // To clear newline character left by scanf

// Input for Date of Birth


printf("Enter day of birth (1-31): ");
scanf("%d", &student->dob.day);
printf("Enter month of birth (1-12): ");
scanf("%d", &student->dob.month);
printf("Enter year of birth: ");
scanf("%d", &student->dob.year);
getchar(); // To clear newline character left by scanf

// Input for division


printf("Enter division: ");
fgets(student->division, sizeof(student->division), stdin);
student->division[strcspn(student->division, "\n")] = 0; //
Remove newline character
}

// Function to display student details


void displayStudentDetails(struct Student *student) {
// Display stored student details
printf("\nStudent Information:\n");
printf("Name: %s\n", student->name);
printf("Roll Number: %d\n", student->rollNumber);
printf("Date of Birth: %d/%d/%d\n", student->dob.day, student-
>dob.month, student->dob.year);
printf("Division: %s\n", student->division);
}

int main() {
// Declare a structure variable to store student details
struct Student student1;

// Input student details


inputStudentDetails(&student1);

// Display the stored student information


displayStudentDetails(&student1);

return 0;
}

Problem Statement – 8

Title: Simple Notepad Application with File Handling

Objective:

Create a simple Notepad-like application in C that allows users to perform basic text editing
operations. The program should support writing text to a file, reading text from a file, and
displaying a menu interface for user interaction.
Features:

1. Write Text to File: The program should allow users to type text, which will be saved to a file
(notepad.txt). If the file already exists, it should be overwritten with the new text. The text
input should support multiple lines, and the user should be able to press Enter to finish the
input.
2. Read Text from File: The program should allow users to view the contents of the file
(notepad.txt). If the file exists, it should read and display the text stored in it.
3. Exit the Program: The program should provide an option for the user to exit the application.

Functional Requirements:

1. Menu System: The program should display a menu with three options:
o Option 1: Write text to a file
o Option 2: Read text from a file
o Option 3: Exit the program
2. Text Input Handling: The program should read text from the user and handle it efficiently using
fgets for multi-line input.
3. File Handling:
o The program should create or open the file notepad.txt for both reading and writing.
o If the user chooses to write text, the file should be opened in write mode (w), and any
existing content should be replaced with the new text.
o If the user chooses to read from the file, the program should open the file in read mode
(r) and display the contents on the screen.
4. Error Handling: If the file cannot be opened (e.g., due to permission issues or if the file does not
exist), the program should display an error message.
5. Continuous Operation: The program should run in a loop, allowing the user to choose multiple
options until they decide to exit.

Inputs:

• User inputs text to be saved in the file when selecting the "Write text to file" option.
• The user selects one of the menu options (1, 2, or 3).

Outputs:

• The program will print messages to the console indicating the result of each operation:
o Confirmation that text has been successfully saved to notepad.txt.
o The contents of the notepad.txt file when read.
o Error messages if the file cannot be opened or found.
o A menu prompt to guide the user through operations.

Example Interaction:

1. Menu Display:

Simple Notepad - Menu


1. Write text to file
2. Read text from file
3. Exit
Choose an option: 1

2. Writing Text to File:

Enter text to save to file (Press Enter to finish):


Hello, this is my notepad application.
I can write multiple lines of text here.

o The program saves the text to notepad.txt.


3. Reading Text from File:

Simple Notepad - Menu


1. Write text to file
2. Read text from file
3. Exit
Choose an option: 2

Reading from 'notepad.txt':


Hello, this is my notepad application.
I can write multiple lines of text here.

4. Exiting the Program:

Simple Notepad - Menu


1. Write text to file
2. Read text from file
3. Exit
Choose an option: 3
Exiting the notepad...
Constraints:

• The text input should not exceed MAX_TEXT_SIZE (1000 characters) to avoid buffer overflow.
• The file to be read (notepad.txt) should exist and contain readable text for the "Read text
from file" option to function correctly.

Additional Features (Optional):

• Allow users to append text to an existing file instead of overwriting.


• Add functionality to edit or delete text in the file.

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

#define MAX_TEXT_SIZE 1000 // Maximum size for the text input

// Function to display the menu options


void displayMenu() {
printf("\nSimple Notepad - Menu\n");
printf("1. Write text to file\n");
printf("2. Read text from file\n");
printf("3. Exit\n");
printf("Choose an option: ");
}

// Function to write text to a file


void writeToFile() {
FILE *file;
char text[MAX_TEXT_SIZE];
printf("\nEnter text to save to file (Press Enter to finish):\n");

// Read user input using fgets to allow multi-line input


getchar(); // To clear the newline character left by previous input
fgets(text, sizeof(text), stdin);

// Open file for writing (creates a new file or overwrites existing)


file = fopen("notepad.txt", "w");
if (file == NULL) {
printf("Error: Unable to open file for writing.\n");
return;
}

// Write the text to the file


fprintf(file, "%s", text);
fclose(file); // Close the file
printf("Text has been successfully saved to 'notepad.txt'.\n");
}

// Function to read text from a file


void readFromFile() {
FILE *file;
char ch;

// Open file for reading


file = fopen("notepad.txt", "r");
if (file == NULL) {
printf("Error: File 'notepad.txt' not found.\n");
return;
}

// Read and display the contents of the file


printf("\nReading from 'notepad.txt':\n");
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Output each character read from the file
}
fclose(file); // Close the file
}

int main() {
int choice;
while (1) {
displayMenu(); // Display menu options
scanf("%d", &choice); // Get user input for menu option

switch (choice) {
case 1:
writeToFile();//Call the function to write text to file
break;
case 2:
readFromFile();//Call the function to read text from file
break;
case 3:
printf("Exiting the notepad...\n");
return 0; // Exit the program
default:
printf("Invalid option! Please select a valid menu
option.\n");
}
}

return 0;
}

You might also like