KEMBAR78
Programming in C - QB M1 | PDF | Reserved Word | Computer Programming
0% found this document useful (0 votes)
14 views48 pages

Programming in C - QB M1

The document outlines key features of the C programming language, including simplicity, portability, and efficiency. It explains the differences between constants and variables, the use of keywords, and the importance of comments. Additionally, it covers fundamental data types, variable initialization, and provides examples of C programs for user input and calculations.

Uploaded by

Bhagya P S
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)
14 views48 pages

Programming in C - QB M1

The document outlines key features of the C programming language, including simplicity, portability, and efficiency. It explains the differences between constants and variables, the use of keywords, and the importance of comments. Additionally, it covers fundamental data types, variable initialization, and provides examples of C programs for user input and calculations.

Uploaded by

Bhagya P S
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/ 48

Programming in C​

9 marks questions

1A. Discuss the key features of C programming language (6 Marks)

The C programming language is a powerful and widely used


general-purpose programming language. Its key features include:

1.​ Simplicity:​
C has a small set of keywords and simple syntax, making it easy
to learn and understand.​

2.​ Portability:​
C programs can be compiled and run on different machines with
little or no modification, making them highly portable.​

3.​ Speed and Efficiency:​


C is a compiled language that offers fast execution and efficient
memory usage. It is suitable for system-level programming.​

4.​ Low-Level Access:​


C provides features like pointers and direct memory access,
allowing manipulation at the hardware level.​

5.​ Modularity:​
C supports modular programming by dividing the program into
functions, which improves readability and reuse.​

6.​ Rich Library Support:​


The C standard library provides a wide range of built-in functions
for performing I/O, string handling, memory allocation, etc.​

7.​ Structured Programming:​


C supports structured programming with decision-making, loops,
and functions, enabling better control over the flow of the program.​

8.​ Extensibility:​
Users can add their own functions to the standard library, making
the language more powerful for various applications.​

1B. How do constants differ from variables in C? (3 Marks)

Constants Variables
Constants are fixed values that do Variables are named memory
not change during program locations whose values can
execution. change during execution.

Declared using the const Declared with a data type.


keyword or #define. Example: int x = 10;
Example: const int x = 10;

Immutable – cannot be modified Mutable – can be updated at any


after definition. point.

Example:
const float PI = 3.14; // constant
int radius = 5; // variable

2. Can a keyword be used as an identifier? Justify your answer.


Also, list at least 5 C keywords and explain their purpose in C.

Can a keyword be used as an identifier?

No, a keyword cannot be used as an identifier in C.

Justification:

●​ Keywords are reserved words in C that have predefined


meanings and are part of the C syntax.​

●​ Using a keyword as an identifier (e.g., variable or function name)


will cause a compilation error, because the compiler will be
unable to distinguish between the intended identifier and the
reserved operation.​
Example:

int return = 5; // Invalid, because "return" is a keyword

Five C Keywords and Their Purposes:

1.​ int:​

○​ Used to declare a variable of integer type.​

○​ Example: int age = 25;​

2.​ if:​

○​ Used for decision-making. Executes a block of code if a


condition is true.​

○​ Example: if (a > b) { printf("A is greater");


}​

3.​ return:​

○​ Used to return a value from a function to the calling


function.​

○​ Example: return 0;​

4.​ while:​

○​ Used to create a loop that continues as long as the condition


is true.​

○​ Example: while (i < 10) { i++; }​


5.​ void:​

○​ Specifies that a function does not return a value.​

○​ Also used in pointer declarations.​

○​ Example: void display();​

3A. How can comments (remarks) be included within a C program?


Where can comments be placed? (6 Marks)

Including Comments in C:

C provides two ways to include comments:

1.​ Single-line Comment:​

○​ Uses //​

○​ Everything after // on that line is treated as a comment.​

○​ Example:

// This is a single-line comment


int a = 10; // Initializing variable a
2. Multi-line Comment:

●​ Enclosed between /* and */​

●​ Used for longer comments spanning multiple lines.​

●​ Example:​

/* This is a multi-line comment

It spans more than one line */

Where Can Comments Be Placed?


●​ Before a line of code – to explain what the code does.​

●​ After a line of code – for inline explanation.​

●​ At the beginning of a program – to describe the program, author,


date, etc.​

●​ Inside functions or loops – to explain logic or special conditions.​

Note: Comments are ignored by the compiler and do not affect program
execution.

3B. Name and describe the four basic types of constants in C. (3


Marks)

The four basic types of constants in C are:

1.​ Integer Constants:​

○​ Whole numbers without a fractional part.​

○​ Can be in decimal, octal, or hexadecimal.​

○​ Example: 100, 077 (octal), 0x1A (hexadecimal)​

2.​ Floating-point Constants:​

○​ Numbers with a fractional part or expressed in exponential


form.​

○​ Example: 3.14, 0.005, 2.5e3​

3.​ Character Constants:​

○​ A single character enclosed in single quotes.​


○​ Example: 'A', '9', '#'​

4.​ String Constants:​

○​ A sequence of characters enclosed in double quotes.​

○​ Stored as an array of characters ending with a null character


(\0).​

○​ Example: "Hello", "123"​

1A. Why is it important to initialize variables before using them in a


program? (3 Marks)

In C, uninitialized variables contain garbage values, i.e.,


unpredictable data left in memory from previous operations.

Reasons to initialize variables:

1.​ Avoid Garbage Values:​

○​ Using uninitialized variables can lead to unexpected results


or bugs, since their content is unknown.​

2.​ Ensures Correct Calculations:​

○​ Initialization ensures that arithmetic and logical operations


start with known and valid data.​

3.​ Improves Code Reliability:​

○​ Initialized variables make the program more predictable


and easier to debug.

Example:

int x; // uninitialized
int y = 5;

int z = x + y; // Error: x has garbage value

1B. Describe the fundamental data types in C. (6 Marks)

C provides several fundamental (or primary) data types, which are


used to declare variables.

1. int (Integer):

●​ Used to store whole numbers (positive or negative).​

●​ Example: int age = 25;​

2. float (Floating Point):

●​ Used to store real numbers (numbers with decimal points).​

●​ Example: float temperature = 36.5;​

3. double (Double Precision Floating Point):

●​ Stores larger and more precise floating-point numbers than


float.​

●​ Example: double pi = 3.1415926535;​

4. char (Character):

●​ Stores a single character enclosed in single quotes.​

●​ Internally stored as an integer using ASCII.​

●​ Example: char grade = 'A';​


5. void:

●​ Represents no value or no data type.​

●​ Used to define functions that do not return a value.​

●​ Example: void display();​

2A. What is the most suitable variable type to represent the area of
a circle in square inches, and why? (3 Marks)

The most suitable variable type is float or double.

Reason:

●​ The area of a circle involves π (pi = 3.1415...) and radius


squared.​

●​ This calculation can result in fractional values (e.g., 78.54), which


cannot be stored in an int.​

●​ float or double can represent both whole and decimal


numbers.​

Use double if:

●​ Higher precision is required.​

●​ Example: double area;​

2B. Write a C program that accepts the following inputs: a student's


name (string), age (integer), and GPA (float). Then, display the
student's details in a formatted output. What are the appropriate
data types for each input, and why? (6 Marks)
✅ Appropriate Data Types:
●​ Name: char name[50] → A string is stored as a character
array.​

●​ Age: int → Whole number, no decimals.​

●​ GPA: float → GPA can have decimal values (e.g., 8.5).

Program


#include <stdio.h>

int main() {

char name[50];

int age;

float gpa;

// Input

printf("Enter student's name: ");

scanf("%s", name); // reads string without spaces

printf("Enter age: ");

scanf("%d", &age);

printf("Enter GPA: ");

scanf("%f", &gpa);
// Output

printf("\n--- Student Details ---\n");

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

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

printf("GPA: %.2f\n", gpa);

return 0;

Q3. C Program to Calculate Area and Perimeter of a Rectangle

(Also checks if it is a square and explains appropriate data types)

✅ Appropriate Data Types:


●​ Length and Width: float​
→ May include decimal values (e.g., 10.5), so float is more
appropriate than int.​

●​ Area and Perimeter: float​


→ Results of multiplication and addition can also be fractional.​

Program

#include <stdio.h>

int main() {

float length, width, area, perimeter;


// Input

printf("Enter the length of the rectangle: ");

scanf("%f", &length);

printf("Enter the width of the rectangle: ");

scanf("%f", &width);

// Calculations

area = length * width;

perimeter = 2 * (length + width);

// Output

printf("\n--- Rectangle Properties ---\n");

printf("Length: %.2f\n", length);

printf("Width: %.2f\n", width);

printf("Area: %.2f square units\n", area);

printf("Perimeter: %.2f units\n", perimeter);

// Check for square

if (length == width) {

printf("This is a square.\n");

} else {

printf("This is not a square.\n");


}

return 0;

✅ Explanation of Data Types:


●​ float is used for all measurements because:​

○​ It allows decimal input (e.g., 7.5 cm),​

○​ Ensures precision in calculations like area and perimeter.​

●​ int would limit the input to whole numbers and is not suitable if
user inputs fractional dimensions.

1A. How can modulus and division operators be used to manipulate


numbers? (3 Marks)

1. Division Operator (/)

●​ Used to divide one number by another.​

●​ Returns the quotient (only the whole part for integers).​

●​ Example:​
int a = 17 / 5; // a = 3

2. Modulus Operator (%)

●​ Returns the remainder of an integer division.​

●​ Used to:​
○​ Check for even/odd: if (num % 2 == 0)​

○​ Extract digits: last_digit = num % 10​

○​ Repeat patterns (e.g., cycling values)​

●​ Example:

int b = 17 % 5; // b = 2

Together, they help:

●​ Break numbers into quotient and remainder​

●​ Build digit-based logic, e.g., reversing a number

1B. What is the result of the following C code? Explain your answer
based on operator precedence and the behavior of the increment
operators. (6 Marks)

Let’s assume the code is:

int a = 5, b;

b = a++ + ++a;

printf("a = %d, b = %d\n", a, b);

✅ Step-by-Step Execution:
●​ Initial: a = 5​

●​ Expression: b = a++ + ++a​

1. a++ (Post-increment):
●​ Returns current value of a, then increments.​

●​ So: a++ = 5, and a becomes 6​

2. ++a (Pre-increment):

●​ First increments, then returns new value.​

●​ So: ++a → a becomes 7 and returns 7​

Expression Becomes:

b = 5 + 7; // b = 12

Final Values:

●​ a = 7​

●​ b = 12

2. Describe the concept of operators in C and explain the various types


with examples. (9)
#include <stdio.h>

int main() {

int a = 5; // Binary: 0101

int b = 3; // Binary: 0011

int and_result = a & b; // 0101 & 0011 = 0001 (1)

int or_result = a | b; // 0101 | 0011 = 0111 (7)

int xor_result = a ^ b; // 0101 ^ 0011 = 0110 (6)

printf("a = %d, b = %d\n", a, b);

printf("Bitwise AND (a & b) = %d\n", and_result);

printf("Bitwise OR (a | b) = %d\n", or_result);

printf("Bitwise XOR (a ^ b) = %d\n", xor_result);

return 0;

Output

a = 5, b = 3

Bitwise AND (a & b) = 1

Bitwise OR (a | b) = 7

Bitwise XOR (a ^ b) = 6
🔍 Explanation:
Let’s break down a = 5 and b = 3 in binary:

●​ a = 0101​

●​ b = 0011​

Performing operations:

●​ a & b = 0001 → 1​

●​ a | b = 0111 → 7​

●​ a ^ b = 0110 → 6​

1A. Why is the main() function considered the entry point of a C


program? (3 Marks)

●​ In C, the main() function is mandatory. It serves as the starting


point of program execution.​

●​ When a C program is executed, the control is transferred to


main() by the operating system.​

●​ It tells the compiler where to begin the execution of instructions.​

●​ Even though other functions can exist in the program, main()


must be defined, otherwise the program won’t compile/run.​

📌 Summary:​
The main() function is the entry point where execution begins,
making it essential for every C program.
1B. C Program: Accept User's Name and Age and Print a Message (6
Marks)

#include <stdio.h>

int main() {

char name[50];

int age;

// Input

printf("Enter your name: ");

scanf("%s", name); // Accepts name without spaces

printf("Enter your age: ");

scanf("%d", &age);

// Output

printf("Hello %s, you are %d years old.\n", name, age);

return 0;

Explanation:
●​ char name[50] → to store a string (name)​

●​ int age → to store the integer value for age​

●​ scanf("%s", name) → reads the name (up to first space)​

●​ printf(...) → formats and displays the message

2. Explain the formatted and unformatted I/O functions of the C


language. (9 Marks)

1. Formatted I/O Functions

These functions handle input and output with format specifiers to read
or print data in a structured way. They allow converting data to and from
human-readable form.

●​ printf()​

○​ Used to display formatted output on the screen.​

○​ Uses format specifiers like %d, %f, %c, %s to print variables


of different data types.​

○​ Example:

int a = 10;

printf("Value of a is %d\n", a);

●​ scanf()
○​ Used to accept formatted input from the user via the
keyboard.​

○​ Uses the same format specifiers as printf() to store input


into variables.​

○​ Example:

int a;

scanf("%d", &a);

Advantages:

●​ Easy to read/write various data types.​

●​ Provides control over the output format (width, precision).​

2. Unformatted I/O Functions

These functions deal with input and output without any format
specifiers, working mainly with raw data like characters or strings. They
are faster but less flexible.

●​ getchar()​

○​ Reads a single character from standard input (keyboard).​

○​ Returns the ASCII value of the character.​

○​ Example:

char ch;

ch = getchar();
●​ putchar()
○​ Prints a single character to standard output (screen).​

○​ Example:

putchar('A');

●​ gets() (Note: unsafe, deprecated in modern C)​

○​ Reads a string (line) from input until newline is encountered.​

○​ No format specifier needed, but no buffer overflow


protection.

puts()​

●​ Prints a string followed by a newline.​

●​ Example:

puts("Hello World");

Conclusion:

●​ Formatted I/O functions provide flexibility and control over how


data is input or displayed, suitable for various data types.​

●​ Unformatted I/O functions are simpler and faster, working directly


with characters or strings without formatting.

3. C Program to Compute and Display Factorial of a Number (9


Marks)
✅ Factorial Definition:
●​ Factorial of a non-negative integer n is the product of all positive
integers less than or equal to n.​

●​ Denoted as n!​

●​ Example:​
5! = 5 × 4 × 3 × 2 × 1 = 120

Program

#include <stdio.h>

int main() {

int n, i;

unsigned long long factorial = 1; // Use unsigned long long for large
factorials

// Input

printf("Enter a positive integer: ");

scanf("%d", &n);

// Check if number is negative

if (n < 0) {

printf("Factorial is not defined for negative numbers.\n");

} else {

// Calculate factorial
for (i = 1; i <= n; ++i) {

factorial *= i;

// Output

printf("Factorial of %d = %llu\n", n, factorial);

return 0;

1a. Program to Check if Entered Number is Less Than 10 and Display


"OK" (5 Marks)

#include <stdio.h>

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (num < 10) {

printf("OK.\n");

}
return 0;

1b. What is a Simple if Statement? Explain Its Importance with an


Example. (4 Marks)

Simple if Statement:

●​ A simple if statement is a decision-making construct that


executes a block of code only if a specified condition is true.​

●​ Syntax:

if (condition) {

// code to execute if condition is true

●​ It helps programs make decisions and control the flow based on


conditions.​

Importance:

●​ Enables conditional execution of code.​

●​ Helps in implementing logic like validation, decision making, and


branching.​
●​ Essential for controlling program behavior dynamically.​

Example ​
int age = 18

if (age >= 18) {

printf("You are eligible to vote.\n");

2a. Program to Check if Candidate’s Age is Greater Than 17 and Display


"Eligible to Vote" (5 Marks)

#include <stdio.h>

int main() {

int age;

printf("Enter your age: ");

scanf("%d", &age);

if (age > 17) {

printf("Eligible to Vote.\n");

return 0;

}
2b. Program Demonstrating Use of if and if-else Statements (4 Marks)

#include <stdio.h>

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

// Using if statement

if (num > 0) {

printf("The number is positive.\n");

// Using if-else statement

if (num % 2 == 0) {

printf("The number is even.\n");

} else {

printf("The number is odd.\n");

return 0;
}

3a. What are Nested if Statements? Explain Their Importance with


an Example. (4 Marks)

Nested if statements are if statements placed inside another if


statement. This allows checking multiple conditions in a hierarchical
manner.

Importance:

●​ Enables complex decision making by testing multiple conditions


step-by-step.​

●​ Allows more precise control over program flow.​

●​ Useful when a condition depends on another condition.​

Example:

int num = 10;

if (num > 0) {

if (num % 2 == 0) {

printf("Number is positive and even.\n");

} else {

printf("Number is positive and odd.\n");


}

} else {

printf("Number is not positive.\n");

●​ First checks if number is positive.​

●​ If true, checks if it is even or odd inside the nested if.​

●​ If false, prints the number is not positive.​

3b. Write a Program to Check Whether a Number is Even or Odd. (5


Marks)

#include <stdio.h>

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (num % 2 == 0) {

printf("The number %d is even.\n", num);

} else {
printf("The number %d is odd.\n", num);

return 0;

2. Write a C program to check whether a given number is an


Armstrong number. (L3)

Armstrong number (also called Narcissistic number) of 3 digits: Sum of


cubes of digits = number itself.

Example: 153 = 1³ + 5³ + 3³ = 153

#include <stdio.h>

#include <math.h>

int main() {

int num, originalNum, remainder, result = 0, n = 0;

printf("Enter an integer: ");

scanf("%d", &num);

originalNum = num;

// Count number of digits


while (originalNum != 0) {

originalNum /= 10;

++n;

originalNum = num;

// Calculate sum of digits raised to power n

while (originalNum != 0) {

remainder = originalNum % 10;

result += pow(remainder, n);

originalNum /= 10;

if (result == num)

printf("%d is an Armstrong number.\n", num);

else

printf("%d is not an Armstrong number.\n", num);

return 0;

}
1. Menu-driven Program for Addition, Subtraction, Multiplication, and
Division (L3)

#include <stdio.h>

int main() {

int choice;

float num1, num2, result;

do {

printf("\nMenu:\n");

printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5.


Exit\n");

printf("Enter your choice (1-5): ");

scanf("%d", &choice);

if (choice >= 1 && choice <= 4) {

printf("Enter two numbers: ");

scanf("%f %f", &num1, &num2);

switch (choice) {

case 1:

result = num1 + num2;

printf("Result: %.2f\n", result);


break;

case 2:

result = num1 - num2;

printf("Result: %.2f\n", result);

break;

case 3:

result = num1 * num2;

printf("Result: %.2f\n", result);

break;

case 4:

if (num2 != 0) {

result = num1 / num2;

printf("Result: %.2f\n", result);

} else {

printf("Error: Division by zero not allowed.\n");

break;

case 5:

printf("Exiting program.\n");

break;

default:

printf("Invalid choice! Please enter a valid option.\n");

}
} while (choice != 5);

return 0;

2. Program to Check Whether a Given Number is an Armstrong


Number (L3)

An Armstrong number of three digits is a number such that the sum of


the cubes of its digits is equal to the number itself.

Example: 153 → 1³ + 5³ + 3³ = 153

#include <stdio.h>

#include <math.h>

int main() {

int num, originalNum, remainder, n = 0;

double sum = 0.0;

printf("Enter an integer: ");

scanf("%d", &num);

originalNum = num;

// Count number of digits

while (originalNum != 0) {
originalNum /= 10;

++n;

originalNum = num;

// Calculate sum of digits raised to the power n

while (originalNum != 0) {

remainder = originalNum % 10;

sum += pow(remainder, n);

originalNum /= 10;

// Check if sum equals the original number

if ((int)sum == num)

printf("%d is an Armstrong number.\n", num);

else

printf("%d is not an Armstrong number.\n", num);

return 0;

}
3. Program to Check Whether the Year is a Leap Year & Explanation
of Logical Operators (L3)

Leap Year Rules:

●​ A year is a leap year if:​

○​ It is divisible by 400 OR​

○​ It is divisible by 4 AND NOT divisible by 100​

Logical Operators used:

●​ && (AND): Both conditions must be true​

●​ || (OR): At least one condition must be true​

●​ ! (NOT): Negates the condition

#include <stdio.h>

int main() {

int year;

printf("Enter a year: ");

scanf("%d", &year);

if ((year % 400 == 0) || ((year % 4 == 0) && !(year % 100 == 0))) {

printf("%d is a leap year.\n", year);

} else {
printf("%d is not a leap year.\n", year);

return 0;

Explanation of Logical Operators in Leap Year Condition:

●​ (year % 400 == 0) checks if year is divisible by 400 — if true,


it is a leap year.​

●​ (year % 4 == 0) checks if divisible by 4.​

●​ (year % 100 == 0) checks if divisible by 100.​

●​ !(year % 100 == 0) means the year should not be divisible by


100.​

●​ Using && and ||, the expression combines conditions to ensure


leap year criteria.​

4. Role and Functionality of the switch Statement in C with Example


(L2)

Role:

●​ The switch statement provides a way to execute different parts of


code based on the value of an expression.​
●​ It is an alternative to multiple if-else statements when you want
to compare the same variable with many constants.​

●​ It improves readability and can be more efficient.​

Syntax:

switch(expression) {

case constant1:

// statements

break;

case constant2:

// statements

break;

...

default:

// statements

●​ expression is evaluated once.​

●​ Control jumps to the matching case.​

●​ break is used to exit the switch to avoid falling through to other


cases.​
●​ default executes if no case matches.​

Example:

#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;

default:

printf("Invalid day\n");

}
return 0;

1. Program to Find the Sum of Digits of a Given Number (9 Marks)


#include <stdio.h>

int main() {

int num, sum = 0, remainder;

printf("Enter a number: ");

scanf("%d", &num);

while (num != 0) {

remainder = num % 10; // Extract last digit

sum += remainder; // Add to sum

num /= 10; // Remove last digit

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

return 0;

}
2a. Program to Display the Fibonacci Series Up to a Given Number of
Terms (7 Marks) (L3)

#include <stdio.h>

int main() {

int n, first = 0, second = 1, next, i;

printf("Enter the number of terms: ");

scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 0; i < n; i++) {

if (i <= 1) {

next = i; // First two terms are 0 and 1

} else {

next = first + second;

first = second;

second = next;

printf("%d ", next);

}
printf("\n");

return 0;

2b. Why is a Loop Necessary for Generating the Fibonacci Sequence in a


Program? (2 Marks)

●​ A loop is necessary because the Fibonacci sequence is generated


by repeatedly adding the two preceding numbers to get the
next number.​

●​ The number of terms can vary, so a loop efficiently calculates and


prints the sequence dynamically without manually coding each
term.

3 .Write a program to generate the following pattern: 1 1 2 1 2 3 1 2 3 4


(7 marks)

#include <stdio.h>

int main() {

int i, j, rows = 4;

for (i = 1; i <= rows; i++) {

for (j = 1; j <= i; j++) {

printf("%d ", j);

printf("\n");
}

return 0;

This program uses nested loops:

●​ Outer loop (i) controls the number of rows.​

●​ Inner loop (j) prints numbers from 1 to the current row number.

Star output program​


#include <stdio.h>

int main() {

int i, j;

int rows = 4;

for (i = 1; i <= rows; i++) {

for (j = 1; j <= i; j++) {

printf("*");

printf("\n");

return 0;

}
1. Write a program to input marks for three subjects, calculate the total
percentage, and display grades according to the following criteria:-

Percentage >= 90: A grade

Percentage >= 80: B grade

Percentage >= 70: C grade

Percentage < 70: Fail. (7)

Program

#include <stdio.h>

int main() {

float marks1, marks2, marks3, total, percentage;

// Input marks for three subjects

printf("Enter marks for subject 1: ");

scanf("%f", &marks1);

printf("Enter marks for subject 2: ");

scanf("%f", &marks2);

printf("Enter marks for subject 3: ");

scanf("%f", &marks3);

// Calculate total and percentage

total = marks1 + marks2 + marks3;

percentage = (total / 300) * 100; // assuming each subject is out of


100
// Display percentage

printf("Percentage: %.2f%%\n", percentage);

// Determine and display grade

if (percentage >= 90)

printf("Grade: A\n");

else if (percentage >= 80)

printf("Grade: B\n");

else if (percentage >= 70)

printf("Grade: C\n");

else

printf("Grade: Fail\n");

return 0;

2. Write a C program to check whether a number is a palindrome.


(L3)

#include <stdio.h>

int main() {

int num, originalNum, reversedNum = 0, remainder;


printf("Enter a number: ");

scanf("%d", &num);

originalNum = num;

// Reverse the number

while (num != 0) {

remainder = num % 10; // Get last digit

reversedNum = reversedNum * 10 + remainder; // Build reversed


number

num /= 10; // Remove last digit

// Check palindrome condition

if (originalNum == reversedNum) {

printf("%d is a palindrome.\n", originalNum);

} else {

printf("%d is not a palindrome.\n", originalNum);

return 0;

}
3a. Write a C Program to Display the Corresponding Day of the Week
Using Switch Statement (7) (L3)

#include <stdio.h>

int main() {

int day;

printf("Enter day number (1-7): ");

scanf("%d", &day);

switch (day) {

case 1:

printf("Sunday\n");

break;

case 2:

printf("Monday\n");

break;

case 3:

printf("Tuesday\n");

break;

case 4:

printf("Wednesday\n");
break;

case 5:

printf("Thursday\n");

break;

case 6:

printf("Friday\n");

break;

case 7:

printf("Saturday\n");

break;

default:

printf("Invalid day number.\n");

return 0;

3b. Explain How the Break Statement Works in a Switch Statement (2)
(L2)

●​ The break statement exits the switch block immediately after


executing the matched case.​

●​ Without break, the program continues executing the next cases


(called "fall-through"), which usually is undesirable.

4. Write a C Program to Find the Factorial of a Number (9)


#include <stdio.h>

int main() {

int num, i;

unsigned long long factorial = 1; // Use unsigned long long for large
factorials

printf("Enter a positive integer: ");

scanf("%d", &num);

if (num < 0) {

printf("Factorial is not defined for negative numbers.\n");

} else {

for (i = 1; i <= num; ++i) {

factorial *= i;

printf("Factorial of %d = %llu\n", num, factorial);

return 0;

}

You might also like