C Question Bank

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

1. What is Computer? Discuss various types of Computer?

A computer is an electronic machine that accepts data and instructions and performs
computations on the data based on those instructions.
1) Super computers:
 Super computer is the fastest, most powerful, and most expensive computer.
 Super computers were first developed in the 1980s to process large amount of
data and to solve complex scientific problems.
 Super computers use parallel processing technology and can perform more than
one trillion calculations in a second.
 A single super computers can support thousands of users at the same time.
 Such computer are mainly used for weather forecasting, nuclear energy
research, aircraft design, automotive design, online banking, controlling
industrial units, etc.
 Some examples of super computers are CRAY-1, CRAY-2, Control Data CYBER
205, and ETA A-10.
2) Mainframe computers:
 Mainframe computers are large scale computers. But smaller than super
computers.
 These are very expensive and need a very large clean room with air conditioning.
 Thereby making them very costly to deploy.
 As with super computers, mainframes can also support multiple processors.
 For example IBM S/30 mainframe can support 50,000 users at the same time.
 Users can access mainframe by using terminals or via PCs.
 The two types of terminals that can be used with mainframe systems:
1. Dumb terminal:
 Dumb terminals consist of only a monitor and a keyboard (or mouse).
 They don’t have their own CPU and memory and use the mainframe
system’s CPU and storage devices.
2. Intelligent terminal:
 Intelligent terminals have their own processor and thus can perform
some processing operations.
 PCs are used as intelligent terminals to facilities data access and other
services from the mainframe system.
3) Mini computers:
 Minicomputer are smaller, cheaper, and slower than mainframe.
 They are called minicomputers because they were the smallest computer of
their times.
 Also known as midrange computers, the capabilities of minicomputers fall
between mainframe and personal computers.
 Minicomputers are widely used in business, education, hospitals,
Government organizations.
4) Microcomputers:
 Microcomputers commonly known as PCs, are very small and cheap.
 PCs and PC compatible computers commonly use the windows operating
system, while apple computers use the Macintosh operating system (Mac OS).
 PCs are classified into the following categories:
1. Desktop PCs 5. Handheld computers
2. Laptops 1)Smart phones
3. Workstations 2)Tablet PCs
4. Network computers
2. Discuss Generations of computer? Highlight features of each the generations.
1. First Generation (1940s-1950s):
 Technology: Vacuum tubes were the primary electronic components used in first-
generation computers. They were large, fragile, and generated a significant amount
of heat.
 Size and Reliability: These computers were enormous and often filled entire rooms.
They were also prone to frequent hardware failures due to the delicate nature of
vacuum tubes.
 Speed and Processing Power: They operated at relatively slow speeds compared to
modern standards.
 Input and Output: Input was typically done using punched cards or paper tape.
Output was usually in the form of printed results.

2. Second Generation (1950s-1960s):


 Technology: Transistors replaced vacuum tubes, leading to smaller, more reliable,
and more energy-efficient computers.
 Size and Reliability: Computers became smaller, more reliable, and required less
maintenance.
 Speed and Processing Power: They were faster and more powerful than first-
generation computers, enabling more complex calculations.
 Magnetic Core Memory: Second-generation computers introduced magnetic core
memory, a type of RAM that significantly improved data storage and retrieval.

3. Third Generation (1960s-1970s):


 Technology: Integrated circuits (ICs) were introduced, allowing multiple transistors
to be combined on a single semiconductor chip.
 Size and Reliability: Computers continued to shrink in size and become even more
reliable.
 Speed and Processing Power: Third-generation computers were faster and more
powerful than their predecessors.
 Operating Systems and Software: High-level programming languages and operating
systems became more prevalent, making it easier for programmers to write and
manage software.

4. Fourth Generation (1970s-1980s):


 Technology: Microprocessors, which contain the entire central processing unit (CPU)
on a single chip, were developed. This led to a dramatic reduction in the size of
computers.
 Size and Reliability: Computers became much smaller, leading to the development
of personal computers (PCs).
 Speed and Processing Power: They were significantly faster and more powerful than
previous generations.
 Graphical User Interfaces (GUIs): GUIs became common, allowing for more intuitive
interaction with the computer.

5. Fifth Generation (1980s-Present):


 Technology: The fifth generation is characterized by advancements in parallel
processing, artificial intelligence, and the development of new computing paradigms
like quantum computing.
 Size and Reliability: Computers have continued to shrink in size, with a focus on
miniaturization and portability.
 Speed and Processing Power: They are incredibly powerful, with processors capable
of handling complex tasks at high speeds.
 Networking and Internet: The widespread adoption of the internet and networking
technologies has revolutionized communication and information access.

3. With a neat diagram explain the basic structure of a computer?


1) Input :
 This is the process of entering data and instructions into the computer system.
 The data and instructions can be entered by using different input devices such as
keyboard, mouse, scanner and trackball.
 That computers understands binary language, which consists of only two
symbols (0 and 1).
 So it is the responsibility of the input devices to convert the input data into
binary codes.
2) Storage:

 Storage is the process of saving data ad instructions permanently in the


computer so that they can be used for processing.
 A computer has two types of storage areas:
1. Primary storage
 Primary storage, also known as the main memory, is the storage
area that is directly accessible by the CPU at very high speeds.
 Primary storage space is very expensive and therefore limited in
capacity.
 The computer is switched off, the information stored gets erased.
 It cannot be used as a permanent storage of useful data and
programs for future use.
 Example: random access memory (RAM).

2. Secondary storage :
 Secondary storage, also known as auxiliary memory, this memory is
just the opposite of primary memory.
 It is cheaper, non-volatile, and used to permanently store data and
programs.
 Secondary memory supplements the limited storage capacity of the
primary memory.
 Example: magnetic disk used to store data, such as C and D drives.
3) Output:
 Output is the process of giving the result of data processing to the outside world.
 The results are given through output devices such as monitor, and printer.
 The output results give in only binary form the output devices convert the
results binary into readable language before displaying into the user.
4) Control:
 The control unit (CPU) is the central processing system of the entire computer
system.
 It manages and controls all the components of the computer system.
 The CPU is called as a brain of computer system because the entire processing of
data is done in the arithmetic and logical unit and control unit activates and
monitors the operations of other units of the computer system.
5) Processing:
 The process of performing operations on the data as per the instructions
specified by the user is called processing.
 When the processing completes, the final result is then transferred to the main
memory.
 Hence, the data may move from main memory to the arithmetic and logical unit
multiple times before the processing is over.

4. What are Input devices and Output devices Mention and explain any two input and output
devices.
Input Devices: Input devices is a piece of equipment used to provide data and control signals
to an information or processing system.
1) Keyboard:
 The keyboard is the main input device for computers.
 Using a keyboard, the user can type a document, use keystroke, access menus,
play games, and perform numerous other tasks.
 Most keyboards have between 80 -110 keys.
Advantages:
 The keyboard is easy to use and expensive.
Disadvantage:
 The keyboard cannot be used to draw figures.
 The process of moving the cursor to another position is very slow.

2) Mouse :

 The mouse is an input device that can be used to handle the pointer easily on
the screen perform various functions such as opening a program or file.
 The mouse contain two buttons and a scroll wheel. It can be held in the hand
easily moved.
Advantages:
 The mouse is easy to use and can be used to quickly place the cursor anywhere
on the screen.
 It also helps to quickly and easily draw figures.
 It is inexpensive.
 Its point and click capabilities make it unnecessary to remember and type in
commands.
Disadvantage:
 The mouse needs extra desk space to be placed and moved easily.
 The ball in the mechanical mouse must be cleaned to remove dust from it.
Output devices: any device that outputs/gives information from a computer can be called an output
devices.
1) Monitors:
 The monitor is a soft copy input device used to display video and graphics
information generated by the computer through video card.
 Computer monitors are similar to television screens but they display information
at much higher quality.
 Monitors come in three variants- cathode ray tube(CRT), liquid crystal
display(LCD), and plasma.
Advantages:
 CRT monitors provide images of good quality.
 LCD monitors are very compact and light weight.
 The technology used in plasma monitors allows producing a very wide screen
using extremely thin materials
Disadvantages:
 CRT monitors occupy a large space on the desk.
 LCD monitors are more expensive than CRTs.
 Plasma monitors have a high energy consumption.

2) Printers:
 A printer is a device that takes the text and graphics information obtained from a
computer and prints it on a paper.
 Printers are available in the market in various sizes, speeds, sophistication and
costs.
 The qualities of printers that are of interest of users.
Advantage:
 These printers enable the users to produce carbon copies.
 They are cheap.
Disadvantage:
 Impact printers are slow.
 They offer poor print quality, especially in the case of graphics.
 They can be extremely noisy.
 They can print only using the standard font.

5. Explain the basic structure of a C program with an example?


1. Preprocessor Directives: These are lines of code that begin with a `#` symbol. They are processed
by the preprocessor before the actual compilation of the program. Common directives include
`#include` (to include header files) and `#define` (to define constants).
2. Main Function: Every C program must have a ‘ main () ‘ function. It serves as the entry point of the
program, where the execution starts.
3. Local Declarations: This is where you declare any variables that you'll be using in the program. In
C, you need to declare variables before you use them.
4. Statements and Expressions: These are the actual instructions that the program will execute.
They can include assignments, calculations, function calls, loops, conditional statements, and more.
5. Return Statement: The `main()` function should return an integer value to indicate the status of
the program's execution to the operating system. A return value of `0` typically indicates a successful
execution, while a non-zero value indicates an error.

Here's an example of a simple C program that adds two numbers:


#include <stdio.h> // Include the standard input/output header file
int main() {
// Local Declarations
int num1, num2, sum;
// Input
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
// Calculation
sum = num1 + num2;
// Output
printf("Sum is: %d\n", sum);
// Return statement
return 0;
}
Explanation:
 The `#include <stdio.h>` directive is used to include the standard input/output header file,
which contains functions like `printf` and `scanf`.
 The `main()` function is the starting point of the program.
 `int num1, num2, sum;` declares three variables to hold the numbers and their sum.
 `scanf` is used to take input from the user, and `printf` is used to display output.
 `sum = num1 + num2;` calculates the sum of `num1` and `num2`.
 `return 0;` indicates that the program executed successfully.

When you compile and run this program, it will prompt the user to enter two numbers, add them
together, and then print out the result.
6. Discuss phases of Design and Implementation of Efficient programs?
1) Requirements Analysis:

 Understanding the problem: Clearly define the problem that the program is
intended to solve.
 Gather requirements: Engage with stakeholders to collect detailed
specifications, constraints, and expectations.

2) Design Phase:

 High-Level Design:
 Identify the overall structure and architecture of the program.
 Define major modules and their interactions.
 Choose appropriate algorithms and data structures.

 Detailed Design:

Elaborate on the high-level design by specifying individual components,


functions, and classes.
 Determine data formats, interfaces, and interactions between modules.
 Address error handling and edge cases.
3) Implementation:
 The designed algorithms are converted into program code using any of the high
level languages.
 All the modules are tested together to ensure that the overall system works well
as a whole product.

4) Testing :

 Develop test cases to verify that the program functions as intended.


 Execute the tests and address any issues or bugs that are discovered.
 Perform both unit testing (testing individual components) and integration testing
(testing the program as a whole).

5) Software Deployment, training and support:

 Prepare the program for deployment on the target environment.


 Monitor the program's performance and behaviour in production to identify and
address any runtime issues.

6) Maintenance :

 Periodically review and update the program to address any new requirements or
issues that arise.
 Maintain a version control system to track changes and manage updates.
7. Discuss the input and output statements in C with Examples?
In C, input and output operations are typically performed using the `scanf` and `printf`
functions for formatted input and output, respectively. These functions are part of the
standard input/output library `stdio.h`.

1) Input in C (Using `scanf`):

The `scanf` function is used to read input from the user or from a file. It allows you to specify
the format in which you expect the input.

Example 1: Reading an Integer


#include <stdio.h>
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d", num);
return 0;
}

In this example, the program prompts the user to enter an integer. The `scanf` function with
the format specifier `%d` reads an integer from the standard input (in this case, the
keyboard) and stores it in the variable `num`.

2) Output in C (Using `printf`):

The `printf` function is used to display output on the screen or write to a file. It allows you to
format the output according to your needs.

Example 2: Printing a String


#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
}

In this example, the program uses `printf` to print the string "Hello, World!" to the standard
output (which is usually the console). The `\n` is an escape sequence that represents a
newline character, causing the output to go to the next line.

Example 3: Formatting Output

#include <stdio.h>
int main()
{
int num = 42;
float pi = 3.1415926;
char letter = 'A';
printf("Integer: %d\n", num);
printf("Float: %f\n", pi);
printf("Character: %c\n", letter);

return 0;
}

In this example, `printf` is used to print an integer (`%d`), a float (`%f`), and a character
(`%c`). The format specifiers are used to specify how the variables should be formatted in
the output.

8. What is Variable? Discuss rules to construct Variables:


A variable in a C program is a named location in the computer's memory where data can be stored
and manipulated. Each variable has a specific data type (such as integer, floating-point, character,
etc.) that determines the type of data it can hold.

Here are the rules to construct variables in a C program:


1. Naming Conventions:
 Variable names should be meaningful and descriptive, reflecting the purpose of the data
they hold.
 Use lowercase letters for variable names (e.g., `my_variable`).
 If a name consists of multiple words, use underscores to separate them (e.g.,
`total_count`).

2. Starting with a Letter or Underscore:


 Variable names must start with a letter (a-z, A-Z) or an underscore `_`.
 They cannot start with a number or any other special character.

3. Alphanumeric Characters and Underscores Only:


 Variable names can contain letters (both uppercase and lowercase), numbers (0-9), and
underscores (`_`).
 They cannot contain spaces, punctuation, or special symbols (except for underscores).

4. Case Sensitivity:

 C is case-sensitive, which means that `myVariable` and `MyVariable` would be considered


as two different variables.
 Be consistent with capitalization throughout your code.

5. Reserved Keywords:

 Avoid using reserved keywords or words that have special meaning in the C language (e.g.,
`int`, `for`, `if`, etc.) as variable names.
6. Length of Variable Names:
 The C standard does not specify a maximum length for variable names, but it's good
practice to keep names reasonably short and meaningful for readability.

Examples of valid variable names in C:


1) int age;
2) float temperature;
3) char student_name;
4) int num1, num2; // Multiple variables declared in one statement
5) int _my_variable; // Starting with an underscore is allowed
Examples of invalid variable names in C:
1) int 1stNumber; // Cannot start with a number
2) float my-temperature; // Hyphens are not allowed
3) char my_name; // Spaces are not allowed
4) int for; // Using a reserved keyword

9. Discuss Steps for Compiling and executing the Programs?


1) Write your code:
 Use a text editor or an integrated development environment to write your c
code.
2) Save your c code:
 Save your c code with a .c file extension. For example, you might save it as
‘your_program.c’.
3) Open a terminal or command prompt:
 Open a terminal or command prompt on your computer. This is the interface
were you’ll type commands to compile and run your program.
4) Navigate to the file location:
 Use the ‘cd’ command to navigate to the directory where your c file is saved. For
example: cd path/to/your/directory
5) Compile the c code:
 Use a c compiler, such as ‘gcc’, to compile your c code. The basic syntax is: gcc
your_program.c –o output_executable
6) Check for compilation:
 If there are errors in your code, the compiler will display eror messages. Reciew
and fix any issues in your code.

7) Execute the compiled program:


 after a successful compilation you can run the compiled executable.
8) View program output:
 if your program ;produce output, you should see it in the terminal after
executing the compiled program.
10. Classify the following as valid/invalid Identifiers and Justify for invalidity i) num2 ii) Snuml
iii)+add iv) a 2 v) 199 space vi) apple?
1) Num2:-
Validity:- valid
2) Snum1:-
Validity:- valid
3) +add:-
Validity:- invalid
Justification:- identifiers cannot contain special characters like ‘+’. They must start with a
letter or an underscore.
4) A 2:-
Validity:-invalid
Justification:-identifiers cannot spaces. The space between ‘a’ and ‘2’ makes it an invalid
identifier.
5) 199 space:-
Validity- invalid
Justification:-identifiers cannot start with a number. In this case, ‘199 space’ starts with
a number, making it invalid.
6) Apple:-
Validity:- valid

11. Design and Develop a C program to find area of triangle with given sides?
#inlcude <stdio.h>
#include <math.h>
{
float a,b,c,s,area;
printf(“Enter the side A:”);
scanf(“%f”,&a);
printf(“Enter the side B:”);
scanf(“%f”,&b);
printf(“Enter the side C:”);
scanf(“%f”,&c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(“The area of the triangle is:%.2f”,area;
return 0;
}
12. Distinguish between an algorithm and pseudocode. Give examples for Both.
Algorithm :-
 An algorithm is step by step procedure or a set of rules for solving specific
problem.
 Formal, precise, and typically represented in a structured manner.
 It can be written in a variety of ways, including natural language, flowcharts, or
as pseudocode.
 Independent of any programming language.
Example: for interchanging/swapping two values.

Step1: Input first number as A


Step2: Input second number as B
Step3: Set temp =A
Step4: Set A= B
Step5: Set B =temp
Step6: Print A, B
Step7: End
Pseudocode:
 Pseudcode is an informal, high level description of the steps in an algorithm.
 Informal, high level, and uses natural language with some programming like
syntax.
 Specifically written using a combination of natural language and programming
like constructs.
 Independent of specific syntax but may resemble a particular programming
language’s structure.
Example: for calculating the price of a product after the sales tax to its original
price.
1. Read the price of the product
2. Read the sales tax rate
3. Calculate sales tax = price of the item x;
Sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the item, sales tax rate, sales tax, total price.

13. Discuss the followings


1. Keywords 2. Identifiers 3.Constants
1. Keywords:

Keywords in a programming language are reserved words that have a predefined meaning and
cannot be used as identifiers (names for variables, functions, etc.). These words are part of the
language's syntax and have specific roles in the program structure. Keywords often include
fundamental constructs such as control flow statements, data types, and other essential elements.
Examples of Keywords in C:
`if`, `else`, `while`, `for`: Control flow statements
`int`, `float`, `char`: Data types
`return`: Used to return a value from a function
`break`, `continue`: Used in loop control

2. Identifiers:

Identifiers are names given to various program elements such as variables, functions, arrays, etc.
They are user-defined and help in distinguishing one entity from another in a program. Identifiers
follow certain rules, depending on the programming language, such as starting with a letter, being
case-sensitive, and not conflicting with keywords.

Examples of Identifiers:
`variableName`, `totalAmount`, `calculateArea`: Variable names
`calculateTotal`, `displayMessage`: Function names
`userInput`, `dataArray`: Array names

3. Constants:

Constants are values that remain unchanged during the execution of a program. They can be of
different types, such as integer constants, floating-point constants, character constants, and string
constants. Constants are used to represent fixed values that are not supposed to be modified.

Examples of Constants:
`42`, `-3`, `0`: Integer constants
`3.14`, `-0.01`: Floating-point constants
`'A'`, `'5'`, `'\n'`: Character constants
`"Hello, World!"`, `"123"`: String constants
Summary:
Keywords: Reserved words with predefined meanings in the programming language.
Identifiers: User-defined names for variables, functions, and other entities.
Constants: Fixed values that do not change during program execution.
14. Write a C Program Fahrenheit to Celsius temperature
#inlcude <stdio.h>
Int main()
{
float f,c;
printf(“Enter temperature in fahrenheit: “);
scanf(“%f”,&f);
c=(f-32)*5/9;
printf(“%.2f Fahrenheit is equal to %.2f Celsius\n”,f,c);
retrun 0;
}
15. Write an algorithm for student mark list processing with the below Input student name,
student id and course marks for five subjects, Calculato total and average and print the
grade for
Marks Grade
Above 75. S
60-75. A
50-60. B
40-50. C
Lesser than 40. D
Algorithm: Student Mark List Processing

1. Start
2. Initialize variables:
- studentName (string)
- studentID (integer)
- marks (array of integers, size 5)
- total (integer)
- average (float)
- grade (character)
3. Input studentName, studentID, and marks for five subjects.
4. Calculate total marks:
total = sum of marks[0] to marks[4]
5. Calculate average:
average = total / 5
6. Determine the grade based on the following criteria:
- If average is above 75:
grade = 'S'
- Else if average is between 60 and 75:
grade = 'A'
- Else if average is between 50 and 60:
grade = 'B'
- Else if average is between 40 and 50:
grade = 'C'
- Else:
grade = 'D'
7. Display the student details:
- Student Name: studentName
- Student ID: studentID
- Marks in five subjects: marks[0], marks[1], marks[2], marks[3], marks[4]
8. Display the calculated values:
- Total Marks: total
- Average: average
- Grade: grade
9. End

16. List all Decision Making Statements used in C? discuss any two statements with syntax and
example
1. if statement
2. if else statement
3. if else if statement
4. switch case

1) if statement:
Syntax:
if (condition)
{
//code to be executed if the condition is true
}
Example:
#include <stdio.h>
Int main()
{
Int number;
printf(“Enter a number : “);
scanf(“%d”,&number);

if (number > 0) {
printf(“The number is positive.\n”);
}
Return 0;
}
2) Switch statement:
Syntax :
switch (expression) {
case constant1:
//code to be executed if expression matches constant1
Break;
case constant2:
//cod to be executed if 3expression matches constant2
Break;
//….
default:
//code to be executed if expression doesn’t match any case
}
Example:
#include <stdio.h>
int main() {
char grade;
printf("Enter your grade (A, B, C, D, or F): ");
scanf(" %c", &grade);
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good!\n");
break;
case 'C':
printf("Satisfactory.\n");
break;
case 'D':
printf("Needs improvement.\n");
break;
case 'F':
printf("Fail.\n");
break;
default:
printf("Invalid grade.\n");
}
return 0;
}

17. List all looping constructs in C and Discuss with Synatx and Examples?
1. While loop:
Syntax :
While (condition) {
//code to be executed repeatedly as long as the condition is true
}

Example:
#include <stdio.h>
Int main() {
//print umbers from1 to 5 using a while loop
int i =1;
while (I <= 5) {
printf(“%d”,i);
i++;
}
Return 0;
}

2. Do while loop:
Syntax:
do {
//code to be executed repeatedly at least once
} while (condition);
Example:
#inlcude <stdio.h>
int main() {
//print numbers from 1 to 5 using a do-while loop
int i=1;
do {
printf(“%d”,i);
++i;
} while (i <= 5);
return 0;
}

3. For loop:
Syntax :
for (initialization; condition; update) {
//code to be executed repeatedly as long as the condition is true
}

Example:
#include <stdio.h>
int main() {
//print numbers from 1 to 5 using a for loop
for(int i=1; i<=5; ++i) {
printf(“%d”,i);
}
retrun 0;
}

18. Write a C program to illustrate all arithmetic operator using switch Statement?
#include <stdio.h>

int main() {
float operand1, operand2, result;
char operator;

// Input two operands and an operator


printf("Enter first operand: ");
scanf("%f", &operand1);

printf("Enter an operator (+, -, *, /): ");


scanf(" %c", &operator); // Note the space before %c to consume the newline character.

printf("Enter second operand: ");


scanf("%f", &operand2);

// Perform arithmetic operation based on the operator using a switch statement


switch (operator) {
case '+':
result = operand1 + operand2;
printf("Sum: %.2f\n", result);
break;
case '-':
result = operand1 - operand2;
printf("Difference: %.2f\n", result);
break;
case '*':
result = operand1 * operand2;
printf("Product: %.2f\n", result);
break;
case '/':
// Check for division by zero
if (operand2 != 0) {
result = operand1 / operand2;
printf("Quotient: %.2f\n", result);
} else {
printf("Error: Division by zero is undefined.\n");
}
break;
default:
printf("Error: Invalid operator entered.\n");
}

return 0;
}

19. Write a C program: to find the roots of quadratic equation?


# include<stdio.h>
# include<math.h>
void main ()
{
float a, b, c, r1, r2, d;
printf ("Enter the values of a b c:");
scanf ("%f %f %f", &a, &b, &c);
d = b * b - 4 * a * c;
if (d > 0)
{
r1 = -b + sqrt (d) / (2*a);
r2 = -b - sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d == 0)
{
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("roots are equal =%f %f", r1, r2);
}
else printf("Roots are imaginary");
return;
}

20. Discuss followings


1. Relational Operators
Relational operators are used to compare values. They return either true (1) or false (0) based on the
comparison. In C, the common relational operators are:

 Equal to(==): returns true if the operands are equal.


int a = 5, b = 7;
if (a == b) {
// Code if a is equal to b
}

 Not equl to (!=):returns true if the operands are not equal.


int a = 5, b = 7;
if (a != b) {
// Code if a is not equal to b
}

 Greater than(>): returns true if the left operand is greater than the right
operand.
int a = 5, b = 7;
if (a > b) {
// Code if a is greater than b
}

 Less than(<):returns true if the left operand is less than right operand.
int a = 5, b = 7;
if (a < b) {
// Code if a is less than b
}
 Greater than equal(>=):returns true if the left operand is greater than or equal
to the right operaned.
int a = 5, b = 7;
if (a >= b) {
// Code if a is greater than or equal to b
}
 Less than or equal to(<=):returns true if the left operand is less than or equal to
the right operand.
int a = 5, b = 7;
if (a <= b) {
// Code if a is less than or equal to b
}

2. Logical Operators
Logical operators are used to perform logical operations on boolean values. The common logical
operators in C are:

 Logical AND (&&):Returns true if both operands are true.


int x = 5, y = 7;
if (x > 0 && y > 0) {
// Code if both x and y are greater than 0

 Logical OR (||): Returns true if at least one of the operands is true.


int x = 5, y = -3;
if (x > 0 || y > 0) {
// Code if either x or y is greater than 0
}

 Logical NOT (!): Returns true if the operand is false and vice versa.
int x = 5;
if (!(x == 0)) {
// Code if x is not equal to 0
}

3. Increment and Decrement operators

 Increment (++):Increases the value of a variable by 1.


int a = 5;
a++; // Now a is 6
 Decrement (--):Decreases the value of a variable by 1.
int b = 7;
b--; // Now b is 6
4. Conditional Operator
The conditional operator (? :) is a ternary operator that evaluates a condition and returns
one of two values based on whether the condition is true or false.
Syntax:
condition ? expression_if_true : expression_if_false;
Example:
int x = 5, y = 7;
int max = (x > y) ? x : y; // max is assigned the larger of x and y

5. Bitwise Operators
Bitwise operators perform operations on individual bits of integers.

Bitwise AND (&): Performs a bitwise AND operation.

Bitwise OR (|): Performs a bitwise OR operation.

Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.

Bitwise NOT (~): Inverts the bits.

Left Shift (<<): Shifts the bits to the left.

Right Shift (>>): Shifts the bits to the right.

Example:-

unsigned int a = 5, b = 3;

unsigned int result_and = a & b; // Bitwise AND

unsigned int result_or = a | b; // Bitwise OR

unsigned int result_xor = a ^ b; // Bitwise XOR

unsigned int result_not = ~a; // Bitwise NOT

unsigned int result_left_shift = a << 1; // Left shift by 1

unsigned int result_right_shift = a >> 1; // Right shift by 1

21. Design and Develop the program to check whether the number is palindrome or not.
def is_palindrome(number):
original_number = number
reversed_number = 0

while number > 0:


digit = number % 10
reversed_number = reversed_number * 10 + digit
number = number // 10

return original_number == reversed_number


# Example usage
user_input = int(input("Enter a number: "))

if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")

22. Differentiate between Break and Continue statements with examples.


Break statement:
 The break statement is used to exit the loop prematurely, regardless of the loop
condition.
 It is commonly used when a specific condition is met, and you want to exit the
loop immediately.

example:

#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++ ) {
if(i==5) {
printf(“Breaking the loop at i=%d\n”, i);
break;
}
printf(“%d\n”,i);
}
return 0;
}
Continue statement:

 The continue statement is used to skip the rest of the code inside a loop for the
current iteration and move to the next iteration.
 It is useful when you want to skip certain iteration based on a condition.

Example:
#include <stdio.h>
int main(){
int i;
for (i = 0; i<10; i++) {
if (i%2==0) {
continue;
}
printf(“%d\n”,i);
}
return 0;
}
23. evaluate the expression
1.2*((a%5) (4+(b- 3)/(-2)))
Where a=8,b-15,c-4
Ans:-
#inlcude <stdio.h>
int main() {
int a=8;
int b=15;
int c=4;

double result =1.2 *((a%5) * (4+(b -3) /(-2)));


printf(“Result: %f\n”,result);
return 0;
}
Output:-Result:21.600000

24. Design and Develop the program to find largest of three number using Nested if
Statement.
#include <stdio.h>

int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

if (num1 >= num2) {


if (num1 >= num3) {
printf("The largest number is: %d\n", num1);
} else {
printf("The largest number is: %d\n", num3);
}
} else {
if (num2 >= num3) {
printf("The largest number is: %d\n", num2);
} else {
printf("The largest number is: %d\n", num3);
}
}

return 0;
}
25. if His basic salary is less than Rs1500, then HRA-10% of basic salary and DA-90% of basic
salary. If his salary is either equal to or above Rs1500, then HRA R$500 and DA-98% of
Basic salary. If the employee's salary is input through the keyboard Design and Develop a
program to find his gross salary.
#include <stdio.h>

int main() {
float basicSalary, hra, da, grossSalary;

printf("Enter the basic salary: ");


scanf("%f", &basicSalary);

if (basicSalary < 1500) {


hra = 0.1 * basicSalary;
da = 0.9 * basicSalary;
} else {
hra = 500;
da = 0.98 * basicSalary;
}

grossSalary = basicSalary + hra + da;

printf("Basic Salary: Rs. %.2f\n", basicSalary);


printf("HRA: Rs. %.2f\n", hra);
printf("DA: Rs. %.2f\n", da);
printf("Gross Salary: Rs. %.2f\n", grossSalary);
return 0;
}
26. Design and Develop a program to find largest of three numbers using else if Ladder.
#include <stdio.h>

int main() {
int num1, num2, num3;

printf("Enter three numbers: ");


scanf("%d %d %d", &num1, &num2, &num3);

if (num1 >= num2 && num1 >= num3) {


printf("The largest number is: %d\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("The largest number is: %d\n", num2);
} else {
printf("The largest number is: %d\n", num3);
}

return 0;
}

27. Design and Development a program to check number +ve, -ve and Zero Number using else
if ladder.
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);

if (number > 0) {
printf("The entered number is positive.\n");
} else if (number < 0) {
printf("The entered number is negative.\n");
} else {
printf("The entered number is zero.\n");
}
return 0;
}
28. Write a C program to find factorial of a number using for loop construct.
#include <stdio.h>

int main() {
// Given number
int number;

// Input number from the user


printf("Enter a number: ");
scanf("%d", &number);

// Initialize result to 1
long long factorial = 1;

// Calculate factorial using a for loop


for (int i = 1; i <= number; ++i) {
factorial *= i;
}

// Display the result


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

return 0;
}
29. Explain the different elements of user defined functions in detail
30. Explain Categories of functions with example.

1. Built in function:
 These are functions that come pre defined in programming languages and are
available for use without the need for additional declaration or definitions.
Example:-
#include<stdio.h>
int main() {
printf(“Hello, World!\n);
return 0;
}
//in this example printf is built in function for printing to the console.

2. User defined functions:


 Functions that are defined by the programmer to perform specific tasks. They
offer modularity and allow the code to be organized into manageable and
reusable units.
Example:
#include <stdio.h>
int add(int a, int b) {
return a +b;
}
int main() {
int result =add(3,4);
printf(“Result: %d\n”, result);
return 0;
}
//in this example add is a user defined function to add two numbers.

3. Recursive functions:
 Functions that call themselves either directly or indirectly to solve a problem.
Example:
#include <stdio.h>
int factorial (int n) {
if (n ==0 || n==1) {
return 1;
} else {
return n* factorial(n-1);
}
}
int main() {
int result = factorial(5);
printf(“Factorial: %d\n”, result);
return 0;
}
//in this example factorial is recursive function to calculate the factorial of a
number.
4. Library function:
 Functions that are passed as arguments to other functions. These are commonly
used in callback mechanisms and event handling.
Example:
#include <stdio.h>
void applyoperation(int a, int b, int(*operation)(int, int)) {
int result =operation(a,b);
printf(‘Result: %d\n”, result);
}
int add (int a, intb) {
return a+b;
}
int main() {
applyoperation(3,4,add);
return 0;
}
//in this example applyoperation is a function that takes another function (add in
this case) as a parameter.

You might also like