Decision making statements in C
C program calculate roots (both real and imaginary) of a quadratic equation.
#include <stdio.h>
#include <math.h>
main() {
float a, b, c, root1, root2, rp, ip;
printf("Enter the coefficients: \n");
printf("a: ");
scanf("%f",&a);
printf("b: ");
scanf("%f",&b);
printf("c: ");
scanf("%f",&c);
if(b*b-4*a*c>0){
root1=(-b+sqrt((b*b)-(4*a*c)));
root2=(-b-sqrt(b*b-4*a*c));
printf("x1 = %0.2f \nx2 = %0.2f",root1, root2);
}else if(b*b-4*a*c==0){
root1=root2=-b/(2*a);
printf("x1 = x2 = %0.2f",root1);
}else{
rp=-b/(2*a);
ip=sqrt(4*a*c-b*b);
printf("x1 = %0.2f+%0.2fi \nx2= %0.1f-%0.1fi",rp,ip,rp,ip);
}
return 0;
}
C program calculate largest number among three entered by user.
// Using if else statements
#include <stdio.h>
main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %d %d",&a, &b, &c);
if(a>b){
if(a>c){
printf("Largest: %d",a);
}else{
printf("Largest; %d",c);
}
}else{
if(b>c){
printf("Largest; %d",b);
}else{
printf("Largest; %d",c);
}
}
return 0;
}
// Using conditional operator (single line code)
#include <stdio.h>
main(){
int a, b, c, largest;
printf("Enter three numbers: ");
scanf("%d %d %d",&a, &b, &c);
largest = (a>b?a:b)>c?(a>b?a:b):c;
printf("Largest = %d",largest);
return 0;
}