0% found this document useful (0 votes)
7 views19 pages

C Programming Basics: Math Operations

Data

Uploaded by

pmanimegalai123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

C Programming Basics: Math Operations

Data

Uploaded by

pmanimegalai123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

1.

SUM OF N NATURAL NUMBERS


#include <stdio.h>
int main()
{
int n, i, sum = 0;
printf("Enter a Number: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
sum =sum+ i;
}
printf("Sum = %d", sum);
return 0;
}

OUTPUT

Enter a positive integer: 3


Sum = 6
[Link] FIND THE LARGEST OF GIVEN 3 NUMBERS

#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter a,b,c: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c)
{
printf("a is Greater than b and c");
}
else if (b > a && b > c)
{
printf("b is Greater than a and c");
}
else if (c > a && c > b)
{
printf("c is Greater than a and b");
}
else
{
printf("all are equal or any two values are equal")
}
return 0;
}

OUTPUT

Enter a,b,c: 10 5 7
a is Greater than b and c
[Link] SOLVE QUADRIC EQUATION

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

OUTPUT

Enter the values of a b c: 1 2 1


Roots are equal =-1.000000 -1.000000
[Link] FIND THE SIMPLE AND COMPOUND INTEREST

#include<stdio.h>
#include<math.h>
int main()
{
float p, r, t;
printf("Enter Principal Amount: ");
scanf("%f", &p);

printf("Enter Time Period: ");


scanf("%f", &t);

printf("Enter Rate of Interest: ");


scanf("%f", &r);

printf("Simple Interest = %f\n", (p*r*t)/100.0);


printf("Compound Interest = %f\n", p*pow(1+r/100, t) - p);
}

OUTPUT

Enter Principal Amount: 5000


Enter Time Period: 2
Enter Rate of Interest: 18
Simple Interest = 1800.000000
Compound Interest = 1962.000788
5. TO READS AN INTEGER N AND DETERMINE THE WHETHER N IS
PRIME OR NOT

#include <stdio.h>
int main()
{
int n;
printf("Enter the number: ");
scanf("%d",&n);
if(n == 1)
{
printf("1 is neither prime nor composite.");
return 0;
}
int count = 0;
for(int i = 2; i < n; i++)
{
if(n % i == 0)
count++;
}
if(count == 0)
{
printf("%d is a prime number.", n);
}
else
{
printf("%d is not a prime number.", n);
}
return 0;
}

OUTPUT

Enter the number: 5


5 is a prime number.

Enter the number: 9


9 is not a prime number.
6. TO ARRANGE THE NUMBER IN ASCENDING AND DESCENDING
ORDER

#include <stdio.h>
int main()
{
int a[100],n,i,j;
printf("Array size: ");
scanf("%d",&n);
printf("Elements: ");

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[j] > a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
printf("\n\nAscending : ");
for (int i = 0; i < n; i++)
{
printf(" %d ", a[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[j] < a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
printf("\n\nDescending : ");
for (int i = 0; i < n; i++)
{
printf(" %d ", a[i]);
}

return 0;
getch();
}

OUTPUT

Array size: 5
Elements: 3 6 2 8 9
Ascending : 2 3 6 8 9
Descending : 9 8 6 3 2
7. TO GENERATE THE FIBONACCI SEQUENCE

#include <stdio.h>
int main()
{
int n, num1 = 0, num2 = 1, nextNum;
printf("Enter the number of Elements: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (int i = 1; i <= n; ++i)
{
printf("%d, ", num1);
nextNum = num1 + num2;
num1 = num2;
num2 = nextNum;
}
return 0;
}

OUTPUT

Enter the number of Elements: 10


Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
8. TO FIND MEAN AND STANDARD DEVIATION

#include<math.h>
#include<stdio.h>
int main()
{
int i, n;
float num[10], deviation, sum, sumsqr, mean, variance, stddev;
sum = 0;
sumsqr =0;
n = 0;
printf("Enter number of elements:\n");
scanf("%d", &n);
printf("Input %d values \n", n);
for(i=0; i<n; i++)
{
scanf("%f", &num[i]);
sum += num[i];
}
mean = sum/(float)n;
printf("Mean is %f\n", mean);
for(i=0;i<n;i++)
{
deviation = num[i] - mean;
sumsqr += deviation * deviation;
}
variance = sumsqr/(float)n;
stddev = sqrt(variance);
printf("Standard Deviation is %f\n", stddev);
}
OUTPUT

Enter number of elements:


6
Input 6 values
5
2
3
6
9
8
Mean is 5.500000
Standard Deviation is 2.500000
9. TO FIND THE ADDITION AND SUBTARCTION OF TWO MATRIX

#include <stdio.h>
void addMatrix(int rows, int cols, int mat1[10][10], int mat2[10][10], int
result[10][10])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}

void subtractMatrix(int rows, int cols, int mat1[10][10], int mat2[10][10], int
result[10][10])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}

void displayMatrix(int rows, int cols, int mat[10][10])


{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n");
}
}
int main()
{
int rows, cols;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
int mat1[10][10], mat2[10][10], resultSum[10][10], resultDiff[10][10];
printf("Enter elements of matrix1:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
scanf("%d", &mat1[i][j]);
}
}
printf("Enter elements of matrix2:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
scanf("%d", &mat2[i][j]);
}
}
addMatrix(rows, cols, mat1, mat2, resultSum);
subtractMatrix(rows, cols, mat1, mat2, resultDiff);
printf("\nSum of matrices:\n");
displayMatrix(rows, cols, resultSum);
printf("\nDifference of matrices:\n");
displayMatrix(rows, cols, resultDiff);
return 0;
}
OUTPUT

Enter the number of rows: 3


Enter the number of columns: 3
Enter elements of matrix1:
111
222
333
Enter elements of matrix2:
444
555
666
Sum of matrices:
5 5 5
7 7 7
9 9 9

Difference of matrices:
-3 -3 -3
-3 -3 -3
-3 -3 -3
10. TO FIND THE MULTIPLICATION OF TWO MATRICES

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("Enter the number of row=");
scanf("%d",&r);
printf("Enter the number of column=");
scanf("%d",&c);
printf("Enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("Multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
# for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

OUTPUT

Enter the number of row=3


Enter the number of column=3
Enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18
CONTENTS

PAGE STAFF
SNO DATE PROGRAM NAME
NO SIGNATURE

1
SUM OF N NUMBERS

2 LARGEST NUMBER

3 QUADRATIC EQUATIONS
SIMPLE AND COMPOUND
INTEREST
4

FIND THE PRIME


5 NUMBER

ASCENDING AND
6 DESCENDING ORDER OF
NUMBERS

7 FIBONACCI SEQUENCE

8 MEAN AND STANDARD


DEVIATION

ADDITION AND
9
SUBTRACTION OF TWO
MATRICES

MULTIPLICATION OF
10
TWO MATRICES
C
PROGRAMMING
LAB

Common questions

Powered by AI

Limiting the array size to 10 elements simplifies memory management within the program and ensures that it operates within predictable constraints, facilitating testing and debugging. This limitation helps to avoid issues related to dynamic memory allocation or overflows in systems with constrained resources or in educational contexts where simplicity is prioritized over performance. Moreover, this bounds the potential input size, reducing complexity while still serving as a valid demonstration of calculating mean and standard deviation on small datasets .

Handling input directly in the main function for matrix operations complicates the function's responsibilities, reducing code modularity and clarity by mixing input processing with computation logic. This approach can lead to difficulties in debugging, testing, and reusability. Improving this would involve delegating input handling to a separate function dedicated to obtaining matrix data, allowing the main function to focus on organizing the overall workflow while isolating input errors and logic for cleaner, more maintainable code .

The logic errors in the sorting algorithms arise from nested loops iterating over the array elements. The code lacks an explicit condition governing the inner loop termination, typically leading to unnecessary iterations once the target value is sorted. Moreover, the synchronous application of the exact swap logic for both ascending and descending order suggests re-iterating an already sorted array, rather than adapting to each respective case's unique requirements within its own procedure, demonstrating inefficiency and potential misordering when the basic logic isn't distinguished for sort direction .

Ignoring negative interest rates in the calculation program could lead to incorrect assessments for scenarios involving penalties or deflation where negative growth is relevant. The calculations as provided assume positive rates, rendering financial representations inaccurate in contexts where negative rates apply, potentially misleading stakeholders about financial outcomes. Implementing checks and handling logic for such cases would account for non-standard financial environments, enhancing the program's robustness and applicability in real-world financial simulations .

Using a naive sorting algorithm like bubble sort, characterized by two nested loops iterating over each pair of elements, results in a time complexity of O(n^2). This quadratic growth in computational steps makes it inefficient for larger datasets compared to more advanced algorithms like quicksort or mergesort, which generally offer O(n log n) performance. The naïve implementation leads to excessive swapping operations and higher processing costs with increased input size, which can significantly degrade performance in time-critical applications .

The program correctly implements the logic for determining when a quadratic equation has equal roots by checking if the discriminant `d` equals zero. If `d == 0`, the formula simplifies to a single root calculated as `r1 = -b/(2*a)`, with `r2` mirroring the same value, indicating real and equal roots. This condition accurately reflects the mathematical definition where the parabola vertex touches the x-axis, leading to one repeated solution instead of two distinct solutions .

The program correctly applies the power function `pow()` for calculating compound interest, expressed as `p * pow(1 + r/100, t) - p`, which accurately models how interest compounds over discrete periods. The use of the `pow()` function enables calculation of `(1 + r/100)^t`, representing the compound growth factor, crucial for reflecting the exponential increase in account balance over time, capturing the essence of compounding which incorporates interest on interest in addition to principal .

The formula for the real roots calculation should apply the square root operation and division correctly. In the given program, for `r1 = -b+sqrt(d) / (2*a);`, the division is applied to `sqrt(d)` but not to the entire numerator `-b + sqrt(d)`. Due to C's precedence rules, `sqrt(d) / (2*a)` evaluates the division before addition to `-b`, leading to incorrect roots unless the expression is properly parenthesized like `(-b + sqrt(d)) / (2*a)`. Incorrect order can lead to subtle bugs, rendering the wrong roots and causing logical inconsistencies in real-world applications .

Using separate functions for matrix addition and subtraction highlights the principles of modular programming. Benefits include enhanced readability and maintainability of the code as each function handles a single operation, making it easier to debug or update without affecting unrelated parts of the code. It also facilitates code reuse, as these operations can be invoked multiple times with different data sets without rewriting logic. Modular design allows for isolated testing of each operational component, contributing to more reliable software .

The program specifically checks if the number `n` is 1, and immediately returns with the output "1 is neither prime nor composite." This check is crucial because 1 is a special case; it is neither considered a prime number (which is defined as having exactly two distinct positive divisors) nor a composite number (which has more than two). Hence, it must be excluded from further checks for divisibility in later code sections .

You might also like