Pop Lab Manual
Pop Lab Manual
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
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
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:
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:
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?
5. Input Numbers
6. Is Choice = 1? (Add)
7. Is Choice = 2? (Subtract)
8. Is Choice = 3? (Multiply)
9. Is Choice = 4? (Divide)
10. Repeat or Exit: The loop repeats back to step 3 for another choice or exits if choice is 5
#include <stdio.h>
int main()
{
int choice;
float num1, num2, result;
return 0;
}
Sample Run:
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
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:
7. Complex Roots: If the discriminant is less than 0, the roots are complex:
Flowchart Structure:
1. Start
2. Input aaa, bbb, and ccc
3. Is a=0a = 0a=0?
6. Is D=0D = 0D=0?
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>
int main() {
float a, b, c;
return 0;
}
RESULT
Flowchart:
The flowchart for the electricity billing system can be outlined as follows:
1. Charge 90 paise/unit.
1. Charge Rs 1/unit.
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;
return 0;
}
Electricity Bill
Name: RAVI
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;}
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:
#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:
· 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.
· 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:
· 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.
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. If n≠pn \neq pn =p, output an error: "Multiplication not possible as n≠pn \neq pn =p" and
exit the program.
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.
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.
Flowchart Diagram:
1. Start
2. Input Matrix Dimensions (m, n) for Matrix A, (p, q) for Matrix B
3. Is n = p? (Check multiplication feasibility)
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
This C program computes the Taylor series approximation of tan(x) by utilizing the Taylor series
approximations of sin(x) and cos(x).
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. Initialize result = 0.
2. Loop from n=0n = 0n=0 to terms−1terms-1terms−1 (number of terms):
1. Initialize result = 0.
2. Loop from n=0n = 0n=0 to terms−1terms-1terms−1 (number of terms):
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):
8. Display result:
1. If the result is valid (not NAN), display the approximate value of tan(x)\tan(x)tan(x).
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. 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).
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:
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 0;
}
SAMPLE OUTPUT
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 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:
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 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:
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.
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. 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.
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.
#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
#include <stdio.h>
#include <string.h>
int main() {
char string1[20], stringcmp[6];
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:
3. Based on the user's choice, the corresponding function is called, and the result is printed.
#include <stdio.h>
#include <string.h>
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
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
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:
#include <stdio.h>
#include <string.h>
int main() {
int N; // Number of students
float sum = 0.0, average;
return 0;
}
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:
Declare variables:
Input:
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:
Reset the pointer: Point ptr back to the beginning of the array (array[0]).
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.
Output results:
#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;
}
Results:
Sum: 111.00
Mean: 37.00
Standard Deviation: 21.00
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:
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.
Read the input file name and target (output) file name from the user.
If successful, proceed. If not, display an error message and end the program.
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.
Inform the user that the file copy operation was successful.
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;
return 0;
}
SAMPLE RESULT
//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.
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.