0% found this document useful (0 votes)
95 views

C Program To Find The Sum of First N Natural Numbers

This document contains code snippets for 3 different C programs: 1) A program to calculate the sum of the first n natural numbers using a for loop. 2) A program to find the largest of 3 numbers using if statements. 3) A program to solve a quadratic equation by calculating the discriminant and producing the roots.

Uploaded by

Akash
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

C Program To Find The Sum of First N Natural Numbers

This document contains code snippets for 3 different C programs: 1) A program to calculate the sum of the first n natural numbers using a for loop. 2) A program to find the largest of 3 numbers using if statements. 3) A program to solve a quadratic equation by calculating the discriminant and producing the roots.

Uploaded by

Akash
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

C Program to Find the Sum of First N Natural

Numbers

#include<stdio.h>
int main()
{
int i, num, sum = 0;
printf("Enter an integer number \n");
scanf ("%d", &num);
for (i = 1; i <= num; i++)
sum = sum + i;
printf ("Sum of first %d natural numbers =
%d\n", num, sum);
}
Using only if statements to find the largest
number..
#include <stdio.h>
int main()
{
int A, B, C;
printf("Enter the numbers A, B and C: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B && A >= C)
printf("%d is the largest number.", A);
if (B >= A && B >= C)
printf("%d is the largest number.", B);
if (C >= A && C >= B)
printf("%d is the largest number.", C);
return 0;
}
Quadratic equation
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2,
realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf",
root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 =
%.2f-%.2fi", realPart, imagPart, realPart,
imagPart);
}
return 0;
}

You might also like