KEMBAR78
Pop Lab Manual | PDF | C (Programming Language) | Programming
0% found this document useful (0 votes)
18 views45 pages

Pop Lab Manual

The C programming language, developed by Dennis Ritchie in 1972, is a structured, middle-level language primarily used for system application development, including operating systems like UNIX and Windows. Its popularity stems from its reliability, simplicity, portability, and extensive use of function calls and operators. The document outlines the characteristics, uses, and basic elements of C, including data types, variables, expressions, and programming assignments.

Uploaded by

revanth148t
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)
18 views45 pages

Pop Lab Manual

The C programming language, developed by Dennis Ritchie in 1972, is a structured, middle-level language primarily used for system application development, including operating systems like UNIX and Windows. Its popularity stems from its reliability, simplicity, portability, and extensive use of function calls and operators. The document outlines the characteristics, uses, and basic elements of C, including data types, variables, expressions, and programming assignments.

Uploaded by

revanth148t
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/ 45

The C programming language

The C programming language is a structure oriented programming language, developed at Bell


Laboratories in 1972 by Dennis Ritchie. C programming language features were derived from an earlier
language called “B” (Basic Combined Programming Language – BCPL) . C language was invented for
implementing UNIX operating system.
WHY IS C POPULAR
It is reliable, simple and easy to use.
C is a small, block-structured programming language.
C is a portable language, which means that C programs written on one system can be run on other systems
with little or no modification.
C has one of the largest assortments of operators, such as those used for calculations and data comparisons.
Although the programmer has more freedom with data storage, the languages do not check data type
accuracy for the programmer.
CHARECTERESTICS OF A C PROGRAM
Middle level language. Don’t provide all the built-in functions found in high level languages. But provides
all building blocks that we need to produce the result we want .Small size – has only 32 keywords
Extensive use of function calls- enables the end user to add their own functions to the C library. Supports
loose typing – a character can be treated as an integer & vice versa.
Structured languag.
Extensive use of function calls- enables the end user to add their own functions to the C library. Low level
(Bit Wise) programming readily available Pointer implementation - extensive use of pointers for memory,
array, structures and functions.
It has high-level constructs.
It can handle low-level activities.
It produces efficient programs.
It can be compiled on a variety of computers.
USES
For developing system applications that forms a major portion of operating systems such as Windows,
UNIX and Linux.
Below are some examples of C being used:
a) Database systems
b) Graphics packages
c) Word processors
d) Spreadsheets
e) Operating system development
f) Compilers and Assemblers
g) Network drivers
h) Interpreters
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while writing
a C program. The general basic structure of C program is shown in the figure below.
Based on this structure, we can sketch a C program.
Example:
/* This program accepts a number & displays it to the user*/
#include <stdio.h>
void main(void)
{ int number;
printf( "Please enter a number: " );
scanf( "%d", &number );
printf( "You entered %d", number );
return 0;}

Stepwise explanation:
#include
The part of the compiler which actually gets your program from the source file is called the preprocessor.
#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is an instruction to
the compiler to make it do something. It tells the C compiler to include the contents of a file (in this case the
system file called stdio.h). The compiler knows it is a system file, and therefore must be looked for in a
special place, by the fact that the filename is enclosed in <> characters
<stdio.h>
stdio.h is the name of the standard library definition file for all STANDARD Input and Output functions.
The program will almost certainly want to send information to the screen and read things from the keyboard,
and stdio.h is the name of the file in which the functions that we want to use are defined. The function we
want to use is called printf. The actual code of printf will be tied in later by the linker. The ".h" portion of
the filename is the language extension, which denotes an include file.
VOID
This literally means that this means nothing. In this case, it is referring to the function whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error.
In this particular example, the only function in the program is called main.
A C program is typically made up of large number of functions. Each of these is given a name by the
programmer and they refer to each other as the program runs.
MAIN
C regards the name main as a special case and will run this function first i.e. the program execution starts
from main.
(void)
This is a pair of brackets enclosing the keyword void. It tells the compiler that the function main has
no parameters. A parameter to a function gives the function something to work on.
{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open
Brace there must be a matching close one. Braces allow us to group pieces of program together, often called
a block.
A block can contain the declaration of variable used within it, followed by a sequence of program
statements. In this case the braces enclose the working parts of the function main.
; (semicolon)
The semicolon marks the end of the list of variable names, and also the end of that declaration statement.
All statements in C programs are separated by ";" (semicolon) characters. The ";" character is actually very
important. It tells the compiler where a given statement ends. If the compiler does not find one of these
characters where it expects to see one, then it will produce an error.
SCANF
In other programming languages, the printing and reading functions are a part of the language.
In C this is not the case; instead they are defined as standard functions which are part of the language
specification, but are not a part of the language itself. The standard input/output library contains a number
of functions for formatted data transfer; the two we are going to use are scanf (scan formatted) and printf
(print formatted).
The printf function is the opposite of scanf.
It takes text and values from within the program and sends it out onto the screen. Just like scanf, it is
common to all versions of C and just like scanf, it is described in the system file stdio.h. The first parameter
to a printf is the format string, which contains text, value descriptions and formatting instructions.
FILES USED IN C
i) Source File-
j) Header File-
k) Object File-
l) Executable File
Source File- This file contains the source code of the program. The file extension of any c file is .c. The file
contains C source code that defines the main function & maybe other functions.
Header File- A header file is a file with extension .h which contains the C function declarations and macro
definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o, meaning relocatable format
machine code that is usually not directly executable. Object files are produced by an assembler, compiler, or
other language translator, and used as input to thelinker, which in turn typically generates an executable or
library by combining parts of object files. - The binary executable file is generated by the linker. The linker
links the various object files to produce a binary file that can be directly EXECUTE.

ELEMENTS OF C

Every language has some basic elements & grammatical rules. Before starting with programming, we should
be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In C, various
characters have been given to communicate.
Keywords are the words whose meaning has already been explained to the C compiler.

The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning
to the keyword, which is not allowed by the computer.

There are only 32 keywords available in C. Below figure gives a list of these keywords for your
ready

Identifier

In the programming language C, an identifier is a combination of alphanumeric characters, the first being a
letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit,
or the underline.
Two rules must be kept in mind when naming identifiers.
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the same as using
"index" and neither of them is the same as using "InDeX" for a variable. All three refer to different variables.
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler
Data type
In the C programming language, data types refer to a domain of allowed values & the operations that can be
performed on those values. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted. There are 4 fundamental data types in C, which are- char,int, float
&, double.
Char is used to store any single character;
int is used to store any integer value,
float is used to store any single precision floating point number &
double is used to store any double precision floating point number.
We can use 2 qualifiers with these basic types to get more types.
There are 2 types of qualifiers_x0002_
Sign qualifier- signed & unsigned
Size qualifier- short & long.

A constant is an entity that doesn’t change whereas a variable is an entity that may change.
C constants can be divided into two major categories:
Primary Constants
Secondary Constants
Here our only focus is on primary constant. For constructing these different types of constants certain rules
have been laid down.
Rules for Constructing Integer Constants:
An integer constant must have at least one digit.
a) It must not have a decimal point.
b) It can be either positive or negative.
c) If no sign precedes an integer constant it is assumed to be positive.
d) No commas or blanks are allowed within an integer constant.
e) The allowable range for integer constants is -32768to 32767.
Ex.: 426, +782,-8000, -7605

Rules for Constructing Real Constants:


Real constants are often called Floating Point constants. The real constants could be written in
two forms—Fractional form and Exponential form.
Rules for constructing real constants expressed in fractional form:
a) A real constant must have at least one digit.
b) It must have a decimal point.
c) It could be either positive or negative.
d) Default sign is positive.
e) No commas or blanks are allowed within a real constant.
Ex. +325.34, 426.0, -32.76, -48.5792
Rules for constructing real constants expressed in exponential form:
a) The mantissa part and the exponential part should be separated by a letter e.
b) The mantissa part may have a positive or negative sign.
c) Default sign of mantissa part is positive.
d) The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
e) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5
Rules for Constructing Character Constants:
a) A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single inverted commas.
b) The maximum length of a character constant can be 1 character.
Ex.: ‘M’, ‘6’, ‘+’
VARIABLES
Variables are names that are used to store values. It can take different values but one at a time. A
data type is associated with each variable & it decides what values the variable can take. When
you decide your program needs another variable, you simply declare (or define) a new variable
and C makes sure you get it. You declare all C variables at the top of whatever blocks of code
need them. Variable declaration requires that you inform C of the variable's name and data type.
Syntax – datatype variablename;
Eg:int page_no;char grade;float salary;long y;
Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various
examples:
Suppose you had to keep track of a person's first, middle, and last initials. Because an initial is obviously a
character, it would be prudent to declare three character variables to hold the three initials. In C, you could
do that with the following statement:

1. main()
{
char first, middle, last;
// Rest of program follows
}
2. main()
{ char first;
char middle;
char last;
// Rest of program follows
}

Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If we want we
can assign some initial value to the variables during the declaration itself. This is called initialization of the
variable.
Eg- int pageno=10;
char grade=’A’;
float salary= 20000.50;

An expression consists of a combination of operators, operands, variables & function calls. An expression
can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation
a>b- relational operation
a== b - logical operation
func (a,b) – function call
4+21
a*(b + c/d)/20
q = 5*2 x =
++q % 3
q>3

As you can see, the operands can be constants, variables, or combinations of the two. Some expressions are
combinations of smaller expressions, called subexpressions. For example, c/d is a subexpression of the sixth
example. An important property of C is that every C expression has a value. To find the value, you perform
the operations in the order dictated by operator precedence.
Statements are the primary building blocks of a program. A program is a series of statements with
some necessary punctuation. A statement is a complete instruction to the computer. In C, statements are
indicated by a semicolon at the end. Thereforelegs = 4 is just an expression (which could be part of a larger
expression), butlegs = 4; is a statement. What makes a complete instruction? First, C considers any
expression to be a statement if you append a semicolon. (These are called expression statements.) Therefore,
C won't object to lines such as the following: 8; 3 + 4; However, these statements do nothing for your
program and can't really be considered sensible statements. More typically, statements change values and
call functions: x = 25; ++x; y = sqrt(x); Although a statement (or, at least, a sensible statement) is a complete
instruction, not all complete instructions are statements. Consider the following statement: x = 6 + (y = 5);
In it, the sub expression y = 5 is a complete instruction, but it is only part of the statement. Because a
complete instruction is not necessarily a statement, a semicolon is needed to identify instructions that truly
are statements.
Programming Assignments
1 Simulation of a Simple Calculator.
2 Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages.
3 An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paise
per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are charged a
minimum of Rs. 100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge
of 15% of total amount is charged. Write a program to read the name of the user, number of units consumed
and print out the charges.
4.Write a C Program to display the following by reading the number of rows as input,
1
121
12321
1 2 3 4 3 2 1 --------------------------- nth row

5 Implement Binary Search on Integers


6 Implement Matrix multiplication and validate the rules of multiplication.
7 Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the built-in library
function. Print both the results with appropriate inferences.
8 Sort the given set of N numbers using Bubble sort.
9 Write functions to implement string operations such as compare, concatenate, and find string length. Use
the parameter passing techniques.
10 Implement structures to read, write and compute average- marks of the students, list the students scoring
above and below the average marks for a class of N students.
11 Develop a program using pointers to compute the sum, mean and standard deviation of all elements
stored in an array of N real numbers.
12. Write a C program to copy a text file to another, read both the input file name and target file name.
Program 1.Simulation of a Simple Calculator.
Functions for Operations:

1. add(), subtract(), multiply(), and divide() are the functions to perform basic arithmetic
operations. They each take two numbers (a and b) as arguments and return the result.

Menu System:

1. The program provides a menu to the user to choose the operation they want to perform.
2. After the user chooses an option, they input two numbers, and the respective operation is
executed.

Input Handling:

1. The user is asked to enter two floating-point numbers. The program then calculates the result
based on the chosen operation.
2. The program continues to loop and allow for further operations until the user selects "Exit".

Error Handling:

1. If the user tries to divide by zero, an error message is displayed instead of performing the
operation.

Exit Option:

1. If the user selects option 5, the program prints a goodbye message and exits.

Flowchart Description:

1. Start: The program starts.


2. Display Menu: The program displays the calculator menu with options for addition, subtraction,
multiplication, division, and exit.
3. Input Choice: User inputs their choice (1-5).
4. Choice Decision:
1. If Choice = 5 (Exit):
1. Display "Exiting the program. Goodbye!"
2. Exit the loop and terminate the program.
2. If Choice = 1, 2, 3, or 4:

1. Proceed to input two numbers for the selected operation.

5. Input Numbers: The program prompts the user to enter two floating-point numbers.
6. Perform Operation: Depending on the choice, perform the corresponding operation:

1. Addition: Call add(a, b) and print the result.


2. Subtraction: Call subtract(a, b) and print the result.
3. Multiplication: Call multiply(a, b) and print the result.
4. Division: Call divide(a, b) and check if the divisor is zero. If it's zero, display an error;
otherwise, print the result.

7. Invalid Choice: If the choice is not between 1 and 5, display an error message.
8. Repeat or Exit: The program loops back to the menu until the user chooses to exit.
Flowchart:

1. Start
2. Display Menu
3. Input Choice
4. Is Choice = 5?

1. Yes → Exit the program


2. No → Continue to next step

5. Input Numbers
6. Is Choice = 1? (Add)

1. Yes → Call add() and display result


2. No → Continue to next step

7. Is Choice = 2? (Subtract)

1. Yes → Call subtract() and display result


2. No → Continue to next step

8. Is Choice = 3? (Multiply)

1. Yes → Call multiply() and display result


2. No → Continue to next step

9. Is Choice = 4? (Divide)

1. Yes → Check if the second number is 0

1. If 0 → Display error message for division by zero


2. If not 0 → Call divide() and display result

2. No → Invalid choice, display error message

10. Repeat or Exit: The loop repeats back to step 3 for another choice or exits if choice is 5

#include <stdio.h>

// Function to perform addition


float add(float a, float b) {
return a + b;
}

// Function to perform subtraction


float subtract(float a, float b) {
return a - b;
}

// Function to perform multiplication


float multiply(float a, float b)
{
return a * b;
}

// Function to perform division


float divide(float a, float b)
{
if (b != 0)
return a / b;
else {
printf("Error: Division by zero is not allowed.\n");
return 0;
}
}

int main()
{
int choice;
float num1, num2, result;

// Loop for continuous operation


do
{
// Displaying the calculator menu
printf("\nSimple Calculator\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("5. Exit\n");
printf("Enter your choice (1-5): ");
scanf("%d", &choice);

// If user chooses to exit


if (choice == 5)
{
printf("Exiting the program. Goodbye!\n");
break;
}

// Taking two numbers as input


printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);

// Performing operation based on the choice


switch(choice)
{
case 1:
result = add(num1, num2);
printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result);
break;
case 2:
result = subtract(num1, num2);
printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result);
break;
case 3:
result = multiply(num1, num2);
printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result);
break;
case 4:
result = divide(num1, num2);
if (num2 != 0)
printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result);
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (1); // Infinite loop until the user chooses to exit

return 0;
}

Sample Run:

Simple Calculator1. Add2. Subtract3. Multiply4. Divide5. Exit


Enter your choice (1-5): 1
Enter two numbers: 12.5 7.5
Result: 12.50 + 7.50 = 20.00

Simple Calculator1. Add2. Subtract3. Multiply4. Divide5. Exit


Enter your choice (1-5): 4
Enter two numbers: 10 0
Error: Division by zero is not allowed.

Simple Calculator1. Add2. Subtract3. Multiply4. Divide5. Exit


Enter your choice (1-5): 5
Exiting the program. Goodbye!

Simple Calculator
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice (1-5): 4
Enter two numbers: 567
23
Result: 567.00 / 23.00 = 24.65

2 Compute the roots of a quadratic equation by accepting the coefficients. Print


appropriate messages.

To compute the roots of a quadratic equation, we can use the quadratic formula:
x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac​ ​
Where:
aaa, bbb, and ccc are the coefficients of the quadratic equation ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0.
The discriminant is Δ=b2−4ac\Delta = b^2 - 4acΔ=b2−4ac.
Based on the value of the discriminant Δ\DeltaΔ, we can determine the nature of the roots:
If Δ>0\Delta > 0Δ>0, there are two distinct real roots.
If Δ=0\Delta = 0Δ=0, there is exactly one real root (repeated root).
If Δ<0\Delta < 0Δ<0, the roots are complex (not real).

Flowchart Steps:

1. Start: The program starts.


2. Input Coefficients: The user is prompted to input the values for the coefficients aaa, bbb, and ccc of
the quadratic equation ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0.
3. Is a=0a = 0a=0?:
1. Yes: Display an error message: "Error: 'a' cannot be zero in a quadratic equation."
2. No: Proceed to the next step.
4. Calculate Discriminant: Calculate the discriminant D=b2−4acD = b^2 - 4acD=b2−4ac.
5. Is Discriminant > 0? (Check if the roots are real and distinct):

1. Yes: Calculate the two real roots: root1=−b+D2a,root2=−b−D2a\text{root1} = \frac{-b +


\sqrt{D}}{2a}, \quad \text{root2} = \frac{-b -
\sqrt{D}}{2a}root1=2a−b+D​ ​ ,root2=2a−b−D​ ​ Display the roots: "The equation has
two real and distinct roots: root1 and root2."
2. No: Proceed to the next step.

6. Is Discriminant = 0? (Check if the root is real and repeated):

1. Yes: Calculate the single real root: root=−b2a\text{root} = \frac{-b}{2a}root=2a−b​


Display the root: "The equation has one real root (repeated root): root."
2. No: Proceed to the next step.

7. Complex Roots: If the discriminant is less than 0, the roots are complex:

1. Calculate the real and imaginary parts: realPart=−b2a,imaginaryPart=−D2a\text{realPart} =


\frac{-b}{2a}, \quad \text{imaginaryPart} = \frac{\sqrt{-
D}}{2a}realPart=2a−b​ ,imaginaryPart=2a−D​ ​ Display the complex roots: "The
equation has complex roots: realPart + imaginaryPart * i and realPart - imaginaryPart * i."

8. End: The program finishes after displaying the roots.

Flowchart Structure:

1. Start
2. Input aaa, bbb, and ccc
3. Is a=0a = 0a=0?

1. Yes → Display error: "Error: 'a' cannot be zero"


2. No → Proceed

4. Calculate Discriminant: D=b2−4acD = b^2 - 4acD=b2−4ac


5. Is D>0D > 0D>0?
1. Yes → Calculate and display two real roots: root1=−b+D2a,root2=−b−D2a\text{root1} =
\frac{-b + \sqrt{D}}{2a}, \quad \text{root2} = \frac{-b -
\sqrt{D}}{2a}root1=2a−b+D​ ​ ,root2=2a−b−D​ ​
2. No → Proceed

6. Is D=0D = 0D=0?

1. Yes → Calculate and display one real root: root=−b2a\text{root} = \frac{-


b}{2a}root=2a−b​
2. No → Proceed

7. Complex Roots: If D<0D < 0D<0, calculate and display complex roots:
realPart=−b2a,imaginaryPart=−D2a\text{realPart} = \frac{-b}{2a}, \quad \text{imaginaryPart} =
\frac{\sqrt{-D}}{2a}realPart=2a−b​ ,imaginaryPart=2a−D​ ​
8. End

#include <stdio.h>
#include <math.h>

// Function to compute the roots of a quadratic equation


void find_roots(float a, float b, float c) {
float discriminant = b * b - 4 * a * c; // Calculate the discriminant

// Check the nature of the roots


if (discriminant > 0) {
// Two distinct real roots
float root1 = (-b + sqrt(discriminant)) / (2 * a);
float root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("The equation has two real and distinct roots: %.2f and %.2f\n", root1, root2);
}
else if (discriminant == 0) {
// One real root (repeated root)
float root = -b / (2 * a);
printf("The equation has one real root (repeated root): %.2f\n", root);
}
else {
// Complex roots
float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("The equation has complex roots: %.2f + %.2fi and %.2f - %.2fi\n", realPart, imaginaryPart,
realPart, imaginaryPart);
}
}

int main() {
float a, b, c;

// Input the coefficients of the quadratic equation


printf("Enter the coefficients of the quadratic equation (ax^2 + bx + c = 0):\n");
printf("Enter a: ");
scanf("%f", &a);
printf("Enter b: ");
scanf("%f", &b);
printf("Enter c: ");
scanf("%f", &c);

// If a is 0, it is not a quadratic equation


if (a == 0) {
printf("Error: 'a' cannot be zero in a quadratic equation.\n");
} else {
// Find and print the roots
find_roots(a, b, c);
}

return 0;
}

RESULT

Enter the coefficients of the quadratic equation (ax^2 + bx + c = 0):


Enter a: 3
Enter b: 2
Enter c: 4
The equation has complex roots: -0.33 + 1.11i and -0.33 - 1.11i

Process returned 0 (0x0) execution time : 17.709 s


Press any key to continue.
Program 3: Electricity Bill calculation
An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paise per
unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are charged a
minimum of Rs. 100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge
of 15% of total amount is charged. Write a program to read the name of the user, number of units consumed
and print out the charges.

Flowchart:

The flowchart for the electricity billing system can be outlined as follows:

1. Start: The program starts.


2. Input User Details: Read the name of the user and the number of units consumed.
3. Calculate the Total Amount:
1. Initialize the total amount as Rs 100 (minimum meter charge).
2. For the first 200 units:
1. Charge 80 paise/unit.
3. For the next 100 units:

1. Charge 90 paise/unit.

4. For units beyond 300:

1. Charge Rs 1/unit.

4. Check if Total > Rs 400:

1. If Yes: Apply an additional surcharge of 15% on the total.


2. If No: No surcharge.

5. Print the Bill: Display the user's name, units consumed, total amount, and surcharge (if applicable).
6. End: The program finishes.

#include <stdio.h>

int main() {
char name[100];
float units, totalAmount = 100; // Minimum charge of Rs. 100
float surcharge = 0.0;

// Input user name and number of units consumed


printf("Enter the name of the user: ");
fgets(name, sizeof(name), stdin); // To handle spaces in the name

printf("Enter the number of units consumed: ");


scanf("%f", &units);

// Calculate the total amount based on units consumed


if (units <= 200) {
totalAmount += units * 0.80; // 80 paise/unit for first 200 units
} else if (units <= 300) {
totalAmount += 200 * 0.80 + (units - 200) * 0.90; // 90 paise/unit for next 100 units
} else {
totalAmount += 200 * 0.80 + 100 * 0.90 + (units - 300) * 1.00; // Rs 1/unit for units beyond 300
}

// If total amount exceeds Rs 400, apply a 15% surcharge


if (totalAmount > 400) {
surcharge = totalAmount * 0.15;
totalAmount += surcharge; // Add surcharge to total amount
}

// Print the bill


printf("\nElectricity Bill\n");
printf("Name: %s", name);
printf("Units Consumed: %.2f\n", units);
printf("Total Amount: Rs %.2f\n", totalAmount);
if (surcharge > 0) {
printf("Surcharge: Rs %.2f (15%% surcharge applied)\n", surcharge);
}

return 0;
}

Enter the name of the user: RAVI

Enter the number of units consumed: 456

Electricity Bill

Name: RAVI

Units Consumed: 456.00

Total Amount: Rs 581.90

Surcharge: Rs 75.90 (15% surcharge applied)

Process returned 0 (0x0) execution time : 21.409 s

Press any key to continue.

Explanation:

1. Input: The program first takes the user's name and the number of units consumed as input.
2. Calculation of Total Amount:
1. For the first 200 units, the rate is 80 paise per unit.
2. For the next 100 units (from 201 to 300), the rate is 90 paise per unit.
3. For units beyond 300, the rate is Rs 1 per unit.
4. The total amount is calculated step by step according to the number of units consumed.
3. Surcharge: If the total amount exceeds Rs 400, a surcharge of 15% is added to the total.
4. Output: The program prints the user's name, the number of units consumed, the total amount, and
the surcharge (if any).
Program 4. :Write a C Program to display the following by reading the number of rows
as input.

Flowchart Steps:

1. Start
2. Input: number of rows (rows)
3. Initialize loop variable i (i = 1)
4. For each row (i <= rows):
1. Inner loop 1 (to print spaces):
Loop variable j starts from i and runs until j < rows, printing spaces.
2. Inner loop 2 (to print numbers):
Loop variable number starts from 1 and prints numbers incrementing up to i.
3. Move to the next line after each row.
5. Repeat the loops until i > rows.
6. End

#include <stdio.h>
int main()
{ int rows, i, j, number;// Get the number of rows from the user
printf("Enter the number of rows: ");
scanf("%d", &rows); // Loop through each row
for(i = 1; i <= rows; i++)
{ // Print spaces for the left padding
for(j = i; j < rows; j++)
{ printf(" "); }
// Print numbers in increasing order
for(number = 1; number <= i; number++)
{ printf("%d ", number); } // Move to the next line
printf("\n"); }
return 0;}

Enter the number of rows: 4


1
12
123
1234

Process returned 0 (0x0) execution time : 3.706 s


Press any key to c
PROGRAM 5 Implement Binary Search on Integers

Steps for Binary Search:

Initial Setup: We need a sorted array of integers and a target integer that we want to find.
Binary Search Algorithm:
Start with two pointers: low (beginning of the array) and high (end of the array).
Find the middle element using: mid = low + (high - low) / 2.
If the target element matches the middle element, return the index.
If the target element is smaller than the middle element, move the high pointer to mid - 1 (search the left
half).
If the target element is greater than the middle element, move the low pointer to mid + 1 (search the right
half).
Repeat: Continue narrowing the search range until the target is found or the range is invalid (low > high).

Flowchart Explanation:

1. Start: Beginning of the flowchart.


2. Initialize variables: Set up the necessary variables including the sorted array of integers, the target
value to search for, and initialize pointers left and right to the start and end of the array respectively.
3. While loop: Continue looping while the left pointer is less than or equal to the right pointer.
4. Calculate mid: Compute the middle index mid as (left + right) / 2.
5. Check conditions:
1. If array[mid] equals target, the search is successful, and mid is returned as the index of the
target.
2. If array[mid] is less than target, update left to mid + 1 to search the right half of the array.
3. Otherwise, update right to mid - 1 to search the left half of the array.
6. Target not found: If the while loop exits (i.e., left > right), the target integer is not present in the
array.
7. End: End of the flowchart.

#include<stdio.h>
#include<conio.h>
void main()
{ int n,a[100],i,key,high,low,mid,loc=-1;
printf("enter array size\n"); scanf("%d",&n);
printf("enter array elements in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter key element to be searched\n");
scanf("%d",&key); low=0; high=n-1;
while(low<=high)
{ mid=(low+high)/2; if(key==a[mid])
{ loc=mid+1; break;
} else
{ if(key<a[mid]) high=mid-1;
else low=mid+1; }
} if(loc>0)
printf("\nThe array element %d is found at%d",key,loc);
else printf("\nThe search is unsuccessful");
getch();
}

Sample result:

enter array size


3
enter array elements in sorted order
23
12
56
enter key element to be searched
56

The array element 56 is found at: 3


PROGRAM 6 Implement Matrix multiplication and validate the rules of
Multiplication.

· Input Matrices:

 · We first input the dimensions of matrix AAA (size m×nm \times nm×n) and matrix BBB (size
n×pn \times pn×p).
 Then, we input the elements of the matrices.

· Matrix Multiplication Function:

 · The function multiply_matrices() computes the product of matrix AAA and matrix BBB and stores
the result in matrix CCC.
 It uses three nested loops:

o The outer two loops iterate over the rows of AAA and columns of BBB.
o The inner loop performs the dot product between the iii-th row of AAA and the jjj-th column
of BBB.

· Matrix Printing:

 · The print_matrix() function is used to display any matrix.

· Validation:

 · The multiplication is only valid if the number of columns in matrix AAA is equal to the number of
rows in matrix BBB, which is checked by the user input dimensions. If m×nm \times nm×n is
multiplied by n×pn \times pn×p, the result will be a m×pm \times pm×p matrix.

Flowchart for Matrix Multiplication Program

The provided C program performs matrix multiplication, where the number of columns in matrix AAA (n)
must equal the number of rows in matrix BBB (p) for the multiplication to be valid. Here's the breakdown of
the flowchart steps based on the provided code:

Flowchart Steps:

1. Start: The program begins.


2. Input Matrix Dimensions:
1. Input m, n: The dimensions of matrix AAA (m x n).
2. Input p, q: The dimensions of matrix BBB (p x q).
3. Check Multiplication Feasibility:

1. If n≠pn \neq pn =p, output an error: "Multiplication not possible as n≠pn \neq pn =p" and
exit the program.

4. Input Elements of Matrix A:

1. Loop through the rows and columns of matrix AAA and input the values.

5. Display Matrix A:
1. Loop through the rows and columns of matrix AAA and print each element.

6. Input Elements of Matrix B:

1. Loop through the rows and columns of matrix BBB and input the values.

7. Display Matrix B:

1. Loop through the rows and columns of matrix BBB and print each element.

8. Matrix Multiplication Logic:

1. Initialize matrix CCC with zeros.


2. Perform the multiplication by iterating over each element of matrix CCC using a nested loop
for iii, jjj, and kkk.
3. For each element C[i][j]C[i][j]C[i][j], calculate the sum of the products
A[i][k]∗ B[k][j]A[i][k] * B[k][j]A[i][k]∗ B[k][j] for all values of kkk.

9. Display Matrix C (Product Matrix):

1. Loop through matrix CCC and print each element.

10. End: The program finishes.

Flowchart Diagram:

Here is the step-by-step flowchart structure:

1. Start
2. Input Matrix Dimensions (m, n) for Matrix A, (p, q) for Matrix B
3. Is n = p? (Check multiplication feasibility)

1. No: Output error: "Multiplication not possible as n ≠ p", then Exit.


2. Yes: Proceed to next step.

4. Input Matrix A: Loop through rows and columns to input elements.


5. Display Matrix A: Loop through rows and columns to display the elements.
6. Input Matrix B: Loop through rows and columns to input elements.
7. Display Matrix B: Loop through rows and columns to display the elements.
8. Matrix Multiplication:

1. Initialize matrix CCC with zeros.


2. Loop for row (i): For each row of AAA.

1. Loop for column (j): For each column of BBB.


1. Initialize C[i][j]=0C[i][j] = 0C[i][j]=0.
2. Loop for k: For each element of row iii of AAA and column jjj of BBB.
1. Compute C[i][j]+=A[i][k]∗ B[k][j]C[i][j] += A[i][k] *
B[k][j]C[i][j]+=A[i][k]∗ B[k][j].

9. Display Matrix C: Loop through matrix CCC and print elements.


10. End
#include <stdio.h>
#include <stdlib.h>
int main() {
int m, n, p, q, row, col, k;
int a[3][3], b[3][3], c[3][3];
printf("Enter size of matrix A (m x n):\n");
scanf("%d%d", &m, &n);
printf("Enter size of matrix B (p x q):\n");
scanf("%d%d", &p, &q);
if (n != p)
{ printf("Multiplication not possible as n not = to p\n");
exit(0); }
printf("Enter elements of matrix A:\n");
for (row = 0; row < m; row++)
{ for (col = 0; col < n; col++)
{ scanf("%d", &a[row][col]); } }
printf("Display elements of matrix A:\n");
for (row = 0; row < m; row++)
{ for (col = 0; col < n; col++)
{ printf("%3d ", a[row][col]); }
printf("\n"); }
printf("Enter elements of matrix B:\n");
for (row = 0; row < p; row++)
{ for (col = 0; col < q; col++)
{ scanf("%d", &b[row][col]);} }
printf("Display elements of matrix B:\n");
for (row = 0; row < p; row++)
{ for (col = 0; col < q; col++)
{ printf("%3d", b[row][col]); }
printf("\n"); }
// Matrix multiplication logic
for (row = 0; row < m; row++)
{ for (col = 0; col < q; col++)
{ c[row][col] = 0; // Initialize the result matrix element
for (k = 0; k < n; k++)
{ c[row][col] += a[row][k] * b[k][col];} } }
// Display the result (product matrix C)
printf("Display elements of product matrix C (Result):\n");
for (row = 0; row < m; row++) {
for (col = 0; col < q; col++) {
printf("%3d ", c[row][col]); }
printf("\n"); }
return 0;}

SAMPLE RESULT
Enter size of matrix A (m x n):
2
3
Enter size of matrix B (p x q):
3
3
Enter elements of matrix A:
1
2
3
4
5
6
Display elements of matrix A:
1 2 3
4 5 6
Enter elements of matrix B:
6
7
8
9
5
4
3
2
1
Display elements of matrix B:
6 7 8
9 5 4
3 2 1
Display elements of product matrix C (Result):
33 23 19
87 65 58
Process returned 0 (0x0) execution time : 69.786 s
Press any key to continue.
PROGRAM 7: Compute sin(x)/cos(x) using Taylor series approximation. Compare
your result with the built-in library function. Print both the results with appropriate
inferences.
EXPLANATION

To compute sin⁡(x)cos⁡(x)\frac{\sin(x)}{\cos(x)}cos(x)sin(x)​ using the Taylor series approximation,


we can break the expression down into two parts: the Taylor series for sin⁡(x)\sin(x)sin(x) and the Taylor
series for cos⁡(x)\cos(x)cos(x).

Taylor Series for sin⁡(x)\sin(x)sin(x):

The Taylor series expansion of sin⁡(x)\sin(x)sin(x) around x=0x = 0x=0 is:

sin⁡(x)=x−x33!+x55!−x77!+⋯ \sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} +


\cdotssin(x)=x−3!x3​ +5!x5​ −7!x7​ +⋯

In general, for sin⁡(x)\sin(x)sin(x), the n-th term is:

sin⁡(x)=∑n=0∞(−1)nx2n+1(2n+1)!\sin(x) = \sum_{n=0}^{\infty} (-1)^n


\frac{x^{2n+1}}{(2n+1)!}sin(x)=n=0∑∞​ (−1)n(2n+1)!x2n+1​

Taylor Series for cos⁡(x)\cos(x)cos(x):

The Taylor series expansion of cos⁡(x)\cos(x)cos(x) around x=0x = 0x=0 is:

cos⁡(x)=1−x22!+x44!−x66!+⋯ \cos(x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} +


\cdotscos(x)=1−2!x2​ +4!x4​ −6!x6​ +⋯

In general, for cos⁡(x)\cos(x)cos(x), the nnn-th term is:

cos⁡(x)=∑n=0∞(−1)nx2n(2n)!\cos(x) = \sum_{n=0}^{\infty} (-1)^n


\frac{x^{2n}}{(2n)!}cos(x)=n=0∑∞​ (−1)n(2n)!x2n​

sin⁡(x)cos⁡(x)\frac{\sin(x)}{\cos(x)}cos(x)sin(x)​ Using Taylor Series:

To approximate sin⁡(x)cos⁡(x)\frac{\sin(x)}{\cos(x)}cos(x)sin(x)​ , we can simply compute the


individual Taylor series for sin⁡(x)\sin(x)sin(x) and cos⁡(x)\cos(x)cos(x) up to a specified number of
terms and then divide the two results.

Here’s the C code that implements this approximation:

Flowchart for the C Program to Compute Taylor Series Approximation of tan(x)

This C program computes the Taylor series approximation of tan(x) by utilizing the Taylor series
approximations of sin(x) and cos(x).

Here is the flowchart structure for the given C program:

Flowchart Steps:
1. Start: The program starts.
2. Input x and terms:
1. Input: Read the value of xxx (angle in radians).
2. Input: Read the number of terms in the Taylor series approximation.
3. Call tan_taylor(x, terms):

1. The tan_taylor() function is called to compute tan⁡(x)\tan(x)tan(x).


2. Inside tan_taylor(), the program calls sin_taylor(x, terms) and cos_taylor(x, terms) functions.

4. Call sin_taylor(x, terms):

1. Initialize result = 0.
2. Loop from n=0n = 0n=0 to terms−1terms-1terms−1 (number of terms):

1. Calculate each term of the Taylor series for sine:


term=(−1)n×x2n+1(2n+1)!\text{term} = (-1)^n \times
\frac{x^{2n+1}}{(2n+1)!}term=(−1)n×(2n+1)!x2n+1​
2. Add each term to the result.

3. Return the sine value.

5. Call cos_taylor(x, terms):

1. Initialize result = 0.
2. Loop from n=0n = 0n=0 to terms−1terms-1terms−1 (number of terms):

1. Calculate each term of the Taylor series for cosine: term=(−1)n×x2n(2n)!\text{term}


= (-1)^n \times \frac{x^{2n}}{(2n)!}term=(−1)n×(2n)!x2n​
2. Add each term to the result.

3. Return the cosine value.

6. Check for division by zero:

1. Check if the cosine value is 0. If it is, print an error message ("Error: cos(x) is zero, tan(x) is
undefined.") and return NAN.

7. Calculate tan⁡(x)\tan(x)tan(x):

1. If cosine is not zero, compute tan⁡(x)=sin⁡(x)cos⁡(x)\tan(x) =


\frac{\sin(x)}{\cos(x)}tan(x)=cos(x)sin(x)​ .

8. Display result:

1. If the result is valid (not NAN), display the approximate value of tan⁡(x)\tan(x)tan(x).

9. End: The program finishes.

Flowchart Diagram Representation:

1. Start
2. Input x and terms: Prompt user for angle xxx and number of terms.
3. Call tan_taylor(x, terms):
1. Inside tan_taylor(x, terms):

1. Call sin_taylor(x, terms):

1. Initialize result to 0.
2. Loop through terms (n = 0 to terms-1):
1. Calculate each term and add to the result.
3. Return the result (sine of x).

2. Call cos_taylor(x, terms):

4. Initialize result to 0.
5. Loop through terms (n = 0 to terms-1):
1. Calculate each term and add to the result.
6. Return the result (cosine of x).

3. Check if cos(x) = 0:

7. Yes → Print "Error: cos(x) is zero, tan(x) is undefined." and exit.


8. No → Continue to next step.

4. Calculate tan(x) = sin(x) / cos(x)

4. Display result: Show the computed value of tan⁡(x)\tan(x)tan(x).


5. End

C Code:

#include <stdio.h>
#include <math.h>
// Function to compute the Taylor series of sin(x)double sin_taylor(double x, int terms) {
double result = 0.0;
double term;
for (int n = 0; n < terms; n++)
{
term = pow(-1, n) * pow(x, 2 * n + 1) / tgamma(2 * n + 2); // (2n+1)!
result += term;
}
return result;
}
// Function to compute the Taylor series of cos(x)double cos_taylor(double x, int terms) {
double result = 0.0;
double term;
for (int n = 0; n < terms; n++) {
term = pow(-1, n) * pow(x, 2 * n) / tgamma(2 * n + 1); // (2n)!
result += term;
}
return result;
}
// Function to compute tan(x) = sin(x) / cos(x) using Taylor seriesdouble tan_taylor(double x, int terms)
{
double sin_x = sin_taylor(x, terms);
double cos_x = cos_taylor(x, terms);
// Avoid division by zero for cos(x) close to 0
if (cos_x == 0) {
printf("Error: cos(x) is zero, tan(x) is undefined.\n");
return NAN;
}

return sin_x / cos_x;


}
int main() {
double x;
int terms;

// Input: Angle in radians and number of terms in the series


printf("Enter the value of x (in radians): ");
scanf("%lf", &x);
printf("Enter the number of terms for the Taylor series approximation: ");
scanf("%d", &terms);

// Compute tan(x) using Taylor series approximation


double result = tan_taylor(x, terms);

// Output the result


if (!isnan(result)) {
printf("The approximate value of tan(x) using Taylor series is: %.6f\n", result);
}

return 0;
}

SAMPLE OUTPUT

Enter the value of x (in radians): 1


Enter the number of terms for the Taylor series approximation: 10
The approximate value of tan(x) using Taylor series is: 1.557408

Explanation of Output:

 The program approximates tan⁡(x)\tan(x)tan(x) using the Taylor series for sin⁡(x)\sin(x)sin(x) and
cos⁡(x)\cos(x)cos(x).
 The result will become more accurate with more terms in the series.
 The Taylor series approximation of tan⁡(x)\tan(x)tan(x) converges as more terms are added.

Time Complexity:

The time complexity of the program is O(terms)O(\text{terms})O(terms) for each series (for both
sin⁡(x)\sin(x)sin(x) and cos⁡(x)\cos(x)cos(x)) since we iterate through a number of terms for the Taylor
series expansion. Thus, the total complexity is linear in terms of the number of terms used for approximation.

Precision:

The more terms you include in the Taylor series, the more accurate the result will be, but there is a limit to
floating-point precision, so increasing terms beyond a certain point may not improve accuracy.

#include<stdio.H>
#include<math.h>
int main()
{
int i;float x,t,sum,sum1,y;
printf("enter angle\n");
scanf("%f",&x);
y=x;x=3.1428*(x/180.0);
sum=x;t=x;i=1;
do
{
i=i+2;
t=(-t*x*x)/((i-1)*i);
sum=sum+t;
}
while(fabs(t)>0.00005);
printf("sin(%f)using taylor series=%f\n",y,sum);
sum1=sin(x);
printf("using inbuilt function sin(%f)=%f",y,sum1);
getch();
}

SAMPLE RESULT

Enter angle
34
sin(34.000000)using taylor series=0.559382
using inbuilt function sin(34.000000)=0.559382
PROGRAM 8. Sort the given set of N numbers using Bubble sort.

Bubble Sort Algorithm:

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements,
and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Steps:

1. Compare each pair of adjacent elements in the list.


2. Swap them if they are in the wrong order.
3. Repeat the process until the list is sorted.
4. After each pass, the largest element in the unsorted portion is "bubbled" to the end of the list.

Time Complexity:

 Worst and Average case: O(N2)O(N^2)O(N2), where NNN is the number of elements in the list.
 Best case: O(N)O(N)O(N) when the list is already sorted.

Bubble Sort Algorithm:

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements,
and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Steps:

1. Compare each pair of adjacent elements in the list.


2. Swap them if they are in the wrong order.
3. Repeat the process until the list is sorted.
4. After each pass, the largest element in the unsorted portion is "bubbled" to the end of the list.

Time Complexity:

 Worst and Average case: O(N2)O(N^2)O(N2), where NNN is the number of elements in the list.
 Best case: O(N)O(N)O(N) when the list is already sorted.

Flowchart for Bubble Sort Program

The provided C program implements a Bubble Sort algorithm to sort a given set of numbers in ascending
order. Here is the flowchart for the C program:

Flowchart Steps:

1. Start: The program begins.


2. Input the number of elements (n): The user is prompted to input the number of elements they want
to sort.
3. Input the elements: The program reads the input numbers and stores them in the array x[].
4. Outer loop (i): The outer loop runs from 0 to n−1n-1n−1, controlling the number of passes over the
array.
1. For each iteration (i), the program executes the inner loop.
5. Inner loop (j): The inner loop runs from 0 to n−1−in-1-in−1−i. For each iteration:

1. Compare adjacent elements: Check if the element at position j is greater than the element at
position j+1.
1. If true: Swap the two elements (i.e., x[j] and x[j+1]).
2. Else: No change is made.
6. Repeat until sorted: The outer loop and inner loop continue until the entire array is sorted.
7. Display sorted array: After the loops are complete, the program prints the sorted array.
8. End: The program terminates.

Flowchart Diagram Structure:

1. Start
2. Input number of elements (n): Prompt the user to enter the number of elements to be sorted.
3. Input array elements: The program prompts the user to enter n numbers, storing them in the array
x[].
4. Outer loop (i = 0 to n-1): Start the outer loop for i.

1. Inner loop (j = 0 to n-1-i): Start the inner loop for j.

1. If x[j] > x[j+1]: Compare adjacent elements.

1. Yes: Swap x[j] and x[j+1].


2. No: Move to the next pair.

5. End inner loop: Complete the iteration of the inner loop.


6. End outer loop: Complete the iteration of the outer loop after all passes.
7. Display sorted array: Print the sorted array.
8. End

#include<stdio.h>
int main() {
int i,n,j,x[20],temp;
printf("how many numbers to be sorted\n");
scanf("%d",&n);
printf("enter numbers to be sorted\n");
for(i=0;i<n;i++)
{ scanf("%d",&x[i]);}
for(i=0;i<n;i++)
{ for(j=0;j<(n-1-i);j++)
{ if(x[j]>x[j+1])
{temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;}
}}
printf("sorted\n");
for(i=0;i<n;i++)
{printf("%d\n",x[i]);}
}

SAMPLE RESULT

how many numbers to be sorted


4
enter numbers to be sorted
223
21
45
400
sorted
21
45
223
400

Process returned 0 (0x0) execution time : 15.859 s


Press any key to continue.
PROGRAM 9: Write functions to implement string operations such as compare, concatenate, and
find string length. Use the parameter passing techniques.

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

int main() {
char string1[20], stringcmp[6];

// Get the input for both strings


printf("Enter input string1:");
scanf("%s", string1);

printf("Enter input stringcmp:");


scanf("%s", stringcmp);

// Compare the strings using strcmp function


if (strcmp(string1, stringcmp) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}

Explanation:

string_length():

1. This function calculates the length of a string by iterating over each character until it reaches
the null terminator (\0), which signifies the end of the string. It returns the number of
characters before the null terminator.
2. Parameter Passing: It uses pass-by-reference to access the input string as a pointer (const
char *str), so no copying of the string is required.

string_compare():

1. This function compares two strings character by character. If at any point the characters are
different, it Returns the difference in their ASCII values. If one string ends before the other, it
returns a difference based on the null character.
2. Parameter Passing: Like the previous function, it uses pass-by-reference (const char *).

string_concatenate():

1. This function appends the second string (str2) to the end of the first string (str1). It first
moves to the end of str1 and then copies each character of str2 until the null character is
encountered. The result is null-terminated.
2. Parameter Passing: It uses pass-by-reference for str1 (so we can modify the string in place),
and pass-by-reference for str2 (since we don't need to modify str2).

Main Function:

1. The program prompts the user to input two strings.


2. The user can choose to perform one of the following operations:

1. Find the length of the strings.


2. Compare the two strings.
3. Concatenate the second string to the first string.

3. Based on the user's choice, the corresponding function is called, and the result is printed.

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

// Function to find the length of a string


int string_length(const char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}

// Function to compare two strings


// Returns 0 if strings are equal, a positive number if str1 > str2, and negative if str1 < str2
int string_compare(const char *str1, const char *str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 != *str2) {
return *str1 - *str2; // Difference between ASCII values of characters
}
str1++;
str2++;
}
return *str1 - *str2; // If one string ends before the other
}

// Function to concatenate two strings


void string_concatenate(char *str1, const char *str2) {
// Move to the end of the first string
while (*str1 != '\0') {
str1++;
}

// Copy characters from str2 to the end of str1


while (*str2 != '\0') {
*str1 = *str2;
str1++;
str2++;
}

// Null-terminate the concatenated string


*str1 = '\0';
}

int main() {
char str1[100], str2[100];
int choice;
// Input strings
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strlen(str1) - 1] = '\0'; // Remove the newline character if present

printf("Enter second string: ");


fgets(str2, sizeof(str2), stdin);
str2[strlen(str2) - 1] = '\0'; // Remove the newline character if present

// Menu for string operations


printf("Choose an operation:\n");
printf("1. Find length of strings\n");
printf("2. Compare strings\n");
printf("3. Concatenate strings\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Length of first string: %d\n", string_length(str1));
printf("Length of second string: %d\n", string_length(str2));
break;

case 2:
if (string_compare(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
break;

case 3:
string_concatenate(str1, str2);
printf("Concatenated string: %s\n", str1);
break;

default:
printf("Invalid choice.\n");
}

return 0;
}

SAMPLE RESULT

Enter first string: Hello


Enter second string: World
Choose an operation:
1. Find length of strings
2. Compare strings
3. Concatenate strings
Enter your choice: 1
Length of first string: 5
Length of second string: 5
Enter first string: Hello
Enter second string: World
Choose an operation:
1. Find length of strings
2. Compare strings
3. Concatenate strings
Enter your choice: 2
Strings are not equal.

Enter first string: Hello


Enter second string: World
Choose an operation:
1. Find length of strings
2. Compare strings
3. Concatenate strings
Enter your choice: 3
Concatenated string: HelloWorld
PROGRAM10: Implement structures to read, write and compute average- marks of the students, list
the students scoring above and below the average marks for a class of N students.

Explanation:

Structure Definition:

1. We define a structure Student to hold information about each student, such as their name
(string) and marks (floating-point number).

Functions:

1. compute_average(): This function calculates the average marks of all students by summing
up the marks and dividing by the total number of students.
2. list_above_average(): This function prints the names and marks of students whose marks are
above the average.
3. list_below_average(): This function prints the names and marks of students whose marks are
below the average.

Main Function:

1. First, the program asks for the number of students (n).


2. Then, it reads the names and marks of each student. The fgets() function is used to read the
name because scanf() cannot handle spaces in strings.
3. After collecting the student data, the program calculates the average marks and displays it.
4. Finally, the program calls the functions to list students who scored above and below the
average.

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

// Define a structure for a student


struct Student {
char name[50];
float marks;
};

int main() {
int N; // Number of students
float sum = 0.0, average;

// Ask the user to input the number of students


printf("Enter the number of students: ");
scanf("%d", &N);

// Create an array of N students


struct Student students[N];

// Read student names and marks


for (int i = 0; i < N; i++) {
printf("Enter name of student %d: ", i + 1);
getchar(); // To consume any leftover newline character
fgets(students[i].name, sizeof(students[i].name), stdin); // Read name
students[i].name[strcspn(students[i].name, "\n")] = 0; // Remove newline at the end

printf("Enter marks of student %d: ", i + 1);


scanf("%f", &students[i].marks);
sum += students[i].marks;
}

// Calculate average marks


average = sum / N;
printf("\nAverage marks: %.2f\n", average);

// List students who scored above and below average


printf("\nStudents who scored above average:\n");
int foundAbove = 0;
for (int i = 0; i < N; i++) {
if (students[i].marks > average) {
printf("%s with marks %.2f\n", students[i].name, students[i].marks);
foundAbove = 1;
}
}
if (!foundAbove) {
printf("No students scored above average.\n");
}

printf("\nStudents who scored below average:\n");


int foundBelow = 0;
for (int i = 0; i < N; i++) {
if (students[i].marks < average) {
printf("%s with marks %.2f\n", students[i].name, students[i].marks);
foundBelow = 1;
}
}
if (!foundBelow) {
printf("No students scored below average.\n");
}

return 0;
}

Enter the number of students: 5


Enter name of student 1: John
Enter marks of student 1: 85

Enter name of student 2: Alice


Enter marks of student 2: 92

Enter name of student 3: Bob


Enter marks of student 3: 78

Enter name of student 4: Eve


Enter marks of student 4: 88

Enter name of student 5: Charlie


Enter marks of student 5: 91
The average marks of the class are: 86.80

Students scoring above the average (86.80):


Alice: 92.00
Eve: 88.00
Charlie: 91.00

Students scoring below the average (86.80):


John: 85.00
Bob: 78.00
PROGRAM 11: Develop a program using pointers to compute the sum, mean and standard
deviation of all elements stored in an array of N real numbers.

Explanation:

compute_sum(): This function calculates the sum of the elements in the array using pointer
arithmetic. It iterates over the array using the pointer arr + i to access the values.

compute_mean(): The mean is computed as the sum of the array divided by the number of elements
(n).

compute_standard_deviation(): This function first computes the mean and then calculates the
standard deviation by summing the squared differences between each element and the mean, then
dividing by n (for population standard deviation) and taking the square root.

Main Function: The program asks the user to input the number of elements (N) and then the real
numbers. It then calls the functions to calculate the sum, mean, and standard deviation, and finally
prints the results.

Flowchart Explanation:

Start: The program starts execution.

Declare variables:

1. Define the array of N real numbers.


2. Declare pointer *ptr to traverse through the array.
3. Initialize variables sum = 0, mean, stdDev, and N.

Input:

1. Read the value of N (size of the array).


2. Input the array elements and store them using the pointer.

Initialize the pointer: Set the pointer ptr to point to the first element of the array (array[0])

Compute sum:

1. Loop through the array using the pointer. Add the dereferenced value *ptr to sum and
increment the pointer to the next element (ptr++).
2. Continue until the pointer reaches the end of the array.

Compute mean:

1. Calculate the mean using the formula:


mean=sumN\text{mean} = \frac{\text{sum}}{N}mean=Nsum​

Reset the pointer: Point ptr back to the beginning of the array (array[0]).

Compute standard deviation:

1. Loop through the array again using the pointer, and for each element, compute the squared
difference from the mean ((*ptr - mean)^2). Add this value to stdDev.
2. After the loop, divide stdDev by N to get the variance.

Calculate standard deviation:

1. Calculate the square root of stdDev to get the standard deviation:


stdDev=∑(xi−mean)2N\text{stdDev} = \sqrt{\frac{\sum{(x_i -
\text{mean})^2}}{N}}stdDev=N∑(xi​ −mean)2​ ​

Output results:

1. Print the sum, mean, and stdDev to the user.

End: The program finishes execution.

#include <stdio.h>
#include <math.h> // Function to calculate the sum of the array double
compute_sum(double *arr, int n)
{
double sum = 0.0;
for (int i = 0; i < n; i++)
{ sum += *(arr + i);
} return sum;
} // Function to calculate the mean of the array double
compute_mean(double *arr, int n)
{
double sum = compute_sum(arr, n);
return sum / n;
} // Function to calculate the standard deviation of the array double
compute_standard_deviation(double *arr, int n)
{ double mean = compute_mean(arr, n);
double sum_squared_diff = 0.0;
for (int i = 0; i < n; i++)
{ sum_squared_diff += pow(*(arr + i) - mean, 2);
}
return sqrt(sum_squared_diff / n);
}
int main()
{
int N; // Read the number of elements
printf("Enter the number of elements: ");
scanf("%d", &N); // Create an array to store the numbers
double arr[N]; // Input elements into the array
printf("Enter the elements:\n");
for (int i = 0; i < N; i++)
{ scanf("%lf", &arr[i]);
} // Calculate sum, mean, and standard deviation
double sum = compute_sum(arr, N);
double mean = compute_mean(arr, N);
double std_dev = compute_standard_deviation(arr, N); // Output results
printf("\nResults:\n");
printf("Sum: %.2f\n", sum);
printf("Mean: %.2f\n", mean);
printf("Standard Deviation: %.2f\n", std_dev);
return 0;
}

Enter the number of elements: 5


Enter the elements: 10 20 30 40 50
Results:
Sum: 150.00
Mean: 30.00
Standard Deviation: 14.14

Enter the number of elements: 3


Enter the elements:
12
34
65

Results:
Sum: 111.00
Mean: 37.00
Standard Deviation: 21.00

Process returned 0 (0x0) execution time : 10.101 s


Press any key to continue.
PROGRAM 12. Write a C program to copy a text file to another, read both the input file name and
target file name.

Explanation:

File Handling:

1. We use fopen() to open the source file in "r" (read) mode and the target file in "w" (write)
mode.
2. If either file cannot be opened, the program prints an error message and exits with a non-zero
status.

File Copying:

1. We use fgetc() to read one character at a time from the source file.
2. fputc() is used to write each character to the target file.
3. This continues until the end of the source file (EOF) is reached.

Error Handling:The program checks if the files were opened successfully. If any file cannot be
opened (due to reasons like the file not existing, permission issues, etc.), it prints an error message
and terminates.

Closing Files:Both the source and target files are closed using fclose() to free up resources.

Flowchart Explanation:

Start: Begin the program.

Declare variables:

Declare character arrays to store the file names (inputFileName and outputFileName).

Declare FILE *inputFile and FILE *outputFile to hold references to the files.

Input file names:

Read the input file name and target (output) file name from the user.

Open input file for reading:

Attempt to open the input file in "read" mode (fopen(inputFileName, "r")).

Check if input file is opened successfully:

If successful, proceed. If not, display an error message and end the program.

Open output file for writing:

Attempt to open the output file in "write" mode (fopen(outputFileName, "w")).

Check if output file is opened successfully:

If successful, proceed. If not, display an error message and end the program.Read and copy
contents:
While there are characters to read from the input file, read one character at a time from the input
file and write it to the output file.

Close files:

After all data has been copied, close both the input and output files.

Display success message:

Inform the user that the file copy operation was successful.

End: Program ends.

This program provides a simple way to copy the contents of one text file to another in C, handling file
operations efficiently.

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

int main() {
FILE *source, *target;
char sourceFileName[100], targetFileName[100];
char ch;

// Input source and target file names


printf("Enter the name of the source file: ");
scanf("%s", sourceFileName);

printf("Enter the name of the target file: ");


scanf("%s", targetFileName);

// Open the source file in read mode


source = fopen(sourceFileName, "r");
if (source == NULL) {
printf("Error: Could not open source file %s.\n", sourceFileName);
return 1; // Exit with an error code
}

// Open the target file in write mode


target = fopen(targetFileName, "w");
if (target == NULL) {
printf("Error: Could not open target file %s.\n", targetFileName);
fclose(source); // Close the source file before exiting
return 1; // Exit with an error code
}

// Read from source file and write to target file


while ((ch = fgetc(source)) != EOF) {
fputc(ch, target);
}

printf("File copied successfully from %s to %s.\n", sourceFileName, targetFileName);

// Close both files


fclose(source);
fclose(target);

return 0;
}

SAMPLE RESULT

Enter the name of the source file: source.txt


Enter the name of the target file: target.txt
File copied successfully from source.txt to target.txt.

Enter the name of the source file: ER.C


Enter the name of the target file: QW.C
File copied successfully from ER.C to QW.C.

Process returned 0 (0x0) execution time : 6.175 s


Press any key to c

//Explanation:
//The program asks the user for the names of the input and output files.
//t opens the input file in read mode ("r") and checks if the file opened successfully.
//It opens the output file in write mode ("w") and checks if the file opened successfully.
//The program reads the input file character by character using fgetc(), and writes each character to the
output file using fputc().
//After the copying process is complete, both the input and output files are closed using fclose().
//Example:
//bash
///Copy code
//Enter the name of the input file: create a new file in working directory with .c extension.name that file
//write some thing in that file and save.in program execution time give the name along with proper file
location.
//Enter the name of the output file: create new file in working directory with .c extensiion. give name for file
and save it.
//In program execution give name with proper file location . example D:\foldername\ filename.c etc.
//File copied successfully.

Sample Output:

Enter the name of the source file: source.txt. Enter the name of the target file: target.tx tFile copied
successfully from source.txt to target.txt.

Edge Cases to Consider:

1. Non-existent Source File: If the source file doesn't exist, the program will output an error message
and stop.
2. Permission Issues: If the user does not have permission to read or write to the specified files, the
program will handle it by showing an appropriate error message.
3. Large Files: The program works for large files as it reads and writes one character at a time.
Time Complexity:

 Time Complexity: O(n)O(n)O(n), where nnn is the number of characters in the source file. We read
each character from the source and write it to the target.

Space Complexity:

 Space Complexity: O(1)O(1)O(1), since the program uses a constant amount of space (for the
character buffer and file pointers). It doesn't store the entire file content in memory at once.

You might also like