Thursday, July 17, 2008

input real numbers and find the mean, variance and standard deviation

/* Write a C program to input real numbers and find the *
* mean, variance and standard deviation */

#include stdio.h
#include conio.h
#include math.h
#define MAXSIZE 10

void main()
{
float x[MAXSIZE];
int i, n;
float avrg, var, SD, sum=0, sum1=0;

clrscr();

printf("Enter the value of N\n");
scanf("%d", &n);

printf("Enter %d real numbers\n",n);
for(i=0; i

This program is straight forward calculation of mean, variance and standard deviation from its formulae directly. It uses mathematical functions for simplicity. Hence reduce the execution length.


/* Write a C program to sort N numbers in ascending order *
* using Bubble sort and print both the given and the sorted *
* array with suitable headings */

#include stdio.h
#include conio.h
#define MAXSIZE 10

void main()
{
int array[MAXSIZE];
int i, j, N, temp;

clrscr();

printf("Enter the value of N\n");
scanf("%d",&N);

printf("Enter the elements one by one\n");
for(i=0; i< j="0;"> array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
printf("Sorted array is...\n");
for(i=0; i

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.


The logic contains inportant concepts to note. Lets see at the nested for loop where all the execution is done. The outer for(i Based) keeps track of the number of times the loop is looked after arranging successive elements. From the above, by the algorithm of Bubble sort, the program has go through the loop N number of times to sort N numbers. This is not an advisible algorithm for large data set as the program exexution time becomes extremly high.


The inner For (j based) keeps track of the element that is swapped now. It keeps increasing untill the Limit of N-i-1 is reached. The inside of this For loop is a simple swap program. So our necessary job is done


Tuesday, July 15, 2008

linear search

/* Write a C program to input N numbers (integers or reals) *
* and store them in an array. Conduct a linear search for a *
* given key number and report success or failure in the form *
* of a suitable message */

#include stdio.h
#include conio.h

void main()
{
int array[10];
int i, N, keynum, found=0;

clrscr();

printf("Enter the value of N\n");
scanf("%d",&N);

printf("Enter the elements one by one\n");
for(i=0; i {
scanf("%d",&array[i]);
}
printf("Input array is\n");
for(i=0; i {
printf("%d\n",array[i]);
}
printf("Enter the element to be searched\n");
scanf("%d", &keynum);

/* Linear search begins */
for ( i=0; i < N ; i++)
{
if( keynum == array[i] )
{
found = 1;
break;
}
}
if ( found == 1)
printf("SUCCESSFUL SEARCH\n");
else
printf("Search is FAILED\n");

} /* End of main */
/*------------------------------------
Output
RUN 1
Enter the value of N
5
Enter the elements one by one
23
12
56
43
89
Input array is
23
12
56
43
89
Enter the element to be searched
56
SUCCESSFUL SEARCH

RUN 2
Enter the value of N
3
Enter the elements one by one
456
213
879
Input array is
456
213
879
Entee the element to be searched
1000
Search is FAILED
--------------------------------------*/


The following program is also based on array concept. We input the data into an array and then print it using a for loop. Then we take the input of necessary number to search. Now we rotate a loop to compare out KEYNUM with each element of an array. If there is a match then the variable FOUND is assiged an identifier. We use a break statemennt so that as soon as the number is assigned we jump out of loop and print the value. We use this as we didnt use an else statement. So if we are not using a BREAK statement, then the program runs into an infinite loop. The output is printed using an IF statement using the identifier we assing above.


program to read N integers (zero, +ve and -ve) into an Array

/* Write a C program to read N integers (zero, +ve and -ve) *
* into an array A and to *
* a) Find the sum of negative numbers *
* b) Find the sum of positive numbers and *
* c) Find the average of all input numbers *
* Output the various results computed with proper headings */

#include stdio.h
#include conio.h
#define MAXSIZE 10

void main()
{
int array[MAXSIZE];
int i, N, negsum=0, posum=0;
float total=0.0, averg;

clrscr();

printf ("Enter the value of N\n");
scanf("%d", &N);

printf("Enter %d numbers (-ve, +ve and zero)\n", N);
for(i=0; i< N ; i++)
{
scanf("%d",&array[i]);
fflush(stdin);
}

printf("Input array elements\n");
for(i=0; i< N ; i++)
{
printf("%+3d\n",array[i]);
}

/* Summing begins */
for(i=0; i< N ; i++)
{

if(array[i] < 0)
{
negsum = negsum + array[i];
}
else if(array[i] > 0)
{
posum = posum + array[i];
}
else if( array[i] == 0)
{
;
}
total = total + array[i] ;
}

averg = total / N;
printf("\nSum of all negative numbers = %d\n",negsum);
printf("Sum of all positive numbers = %d\n", posum);
printf("\nAverage of all input numbers = %.2f\n", averg);

} /*End of main()*/
/*-------------------------------------
Output
Enter the value of N
5
Enter 5 numbers (-ve, +ve and zero)
5
-3
0
-7
6
Input array elements
+5
-3
+0
-7
+6

Sum of all negative numbers = -10
Sum of all positive numbers = 11

Average of all input numbers = 0.20
--------------------------------------*/


This program is a intro for Array elements. It is a good example for array inputs and execution. The beauty of C language lies in Arrays and pointers. So i stress the readers to concentrate more on programs from here as all are in the order of increasing complexity


The first thing to note is the usage of Symbolic constant MAXSIZE to specify the size of array. If you want to know more about array size and different ways of its specification, Use the search box.


In this program we are initializing all the values to a preset value. By doing so we are manually flusing all the variables. There is a chance that these variables might be assigned some value at some time of execution of other programs. Those will be cleared.


Now we are using a for loop to input the array elements. Here the point to note is the usage of fflush() function, which clears all the input buffers after taking the input. It is advisory that we keep clearing both input and output buffers periodically to aviod any variable over lap.


Then we are reading each element of array and adding using a for loop. We use an else.. if to seperate positive and negative numbers and then add.

find the number of integers divisible by 5 in a given range

/* Write a C program to find the number of integers divisible by 5 *
* between the given range N1 and N2, where N1 < N2 and are integers.*
* Also find the sum of all these integer numbers that divisible by 5*
* and output the computed results */

#include stdio.h
#include conio.h

void main()
{
int i, N1, N2, count = 0, sum = 0;

clrscr();

printf ("Enter the value of N1 and N2\n");
scanf ("%d %d", &N1, &N2);

/*Count the number and compute their sum*/
printf ("Integers divisible by 5 are\n");

for (i = N1; i < N2; i++)
{
if (i%5 == 0)
{
printf("%3d,", i);
count++;
sum = sum + i;
}
}

printf ("\nNumber of integers divisible by 5 between %d and %d = %d\n",
N1,N2,count);
printf ("Sum of all integers that are divisible by 5 = %d\n", sum);

} /* End of main()*/
/*-----------------------------
Output
Enter the value of N1 and N2
2
27
Integers divisible by 5 are
5, 10, 15, 20, 25,
Number of integers divisible by 5 between 2 and 27 = 5
Sum of all integers that are divisible by 5 = 75
------------------------------------------------------*/



<

This program diplayes all the numbers divisible 5 between a given range. So we set a variable to given first number of range(N1 here) and increment it till end of range(N2 here) and diving every numder coming inside it by 5 with the help of FOR loop. When there is a remainder '0' we will print that number.

To generate and print prime numbers in a given range

/* Write a C program to generate and print prime numbers in a given *
* range. Also print the number of prime numbers */

#include stdio.h
#include conio.h
#include stdlib.h
#include math.h

void main()
{
int M, N, i, j, flag, temp, count = 0;

clrscr();

printf("Enter the value of M and N\n");
scanf("%d %d", &M,&N);

if(N < 2)
{
printf("There are no primes upto %d\n", N);
exit(0);
}
printf("Prime numbers are\n");
temp = M;

if ( M % 2 == 0)
{
M++;
}
for (i=M; i<=N; i=i+2)
{
flag = 0;

for (j=2; j<=i/2; j++)
{
if( (i%j) == 0)
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("%d\n",i);
count++;
}
}
printf("Number of primes between %d and %d = %d\n",temp,N,count);
}
/*---------------------------------
Output
Enter the value of M and N
15 45
Prime numbers are
17
19
23
29
31
37
41
43
Number of primes between 15 and 45 = 8
-------------------------------------------*/

This program is an extention of the previous one. We add another extra loop to increment the number isself untill it reaches the limit set of the priniting of prime numbers. This uses the netsed FOR loop concept for execution.

check whether a given number is prime or not

/* Write a C program to check whether a given number is prime or not *
* and output the given number with suitable message */

#include stdio.h
#include stdlib.h
#include conio.h

void main()
{
int num, j, flag;

clrscr();

printf("Enter a number\n");
scanf("%d", &num);

if ( num <= 1)
{
printf("%d is not a prime numbers\n", num);
exit(1);
}

flag = 0;

for ( j=2; j<= num/2; j++)
{
if( ( num % j ) == 0)
{
flag = 1;
break;
}
}

if(flag == 0)
printf("%d is a prime number\n",num);
else
printf("%d is not a prime number\n", num);
}
/*------------------------
Output
RUN 1
Enter a number
34
34 is not a prime number

RUN 2
Enter a number
29
29 is a prime number
-----------------------------*/


This program checks whether the given number is prime or not. We know that a prime number is not divisible by any natural number other than 1. So if we think a little bit it is the same that if any number till the half of given number is not diving it, It is meant to be a prime. Because if the one factor is greater than half of the given number, then the other factor is less 2, which is not a natural number. Hence it can be termed as prime.


Hence we initialize a variable to 2 and increment it till it reaches half of the given number. If at any time we get a remainder zero, we declare it as not prime, else its accepted as a prime number

find the value of cos(x) using the series

/* Write a C program to find the value of cos(x) using the series *
* up to the given accuracy (without using user defined function) *
* Also print cos(x) using library function. */

#include stdio.h
#include conio.h
#include math.h
#include stdlib.h

void main()
{
int n, x1;
float acc, term, den, x, cosx=0, cosval;

clrscr();

printf("Enter the value of x (in degrees)\n");
scanf("%f",&x);

x1 = x;

/* Converting degrees to radians*/

x = x*(3.142/180.0);
cosval = cos(x);

printf("Enter the accuary for the result\n");
scanf("%f", &acc);
term = 1;
cosx = term;
n = 1;

do
{
den = 2*n*(2*n-1);
term = -term * x * x / den;
cosx = cosx + term;
n = n + 1;
} while(acc <= fabs(cosval - cosx)); printf("Sum of the cosine series = %f\n", cosx); printf("Using Library function cos(%d) = %f\n", x1,cos(x)); } /*End of main() */ /*------------------------------ Output Enter the value of x (in degrees) 30 Enter the accuary for the result 0.000001 Sum of the cosine series = 0.865991 Using Library function cos(30) = 0.865991 RUN 2 Enter the value of x (in degrees) 45 Enter the accuary for the result 0.0001 Sum of the cosine series = 0.707031 Using Library function cos(45) = 0.707035 ---------------------------------------------*/

This program is completly same as previous program. Same explanation. Insted we use the cosine taylor formula here


Hence we have the series



x2 x4 x6 x8


1 -
+ - + - ...


2! 4! 6! 8!



Notice that the series only contains even powers of x and even factorials. Even numbers can be represented by 2n. Also notice that this is an alternating series, hence the McLaurin series is




Find the value of sin(x) using the series

/* Write a C program to find the value of sin(x) using the series *
* up to the given accuracy (without using user defined function) *
* Also print sin(x) using library function. */

#include stdio.h
#include conio.h
#include math.h
#include stdlib.h

void main()
{
int n, x1;
float acc, term, den, x, sinx=0, sinval;

clrscr();

printf("Enter the value of x (in degrees)\n");
scanf("%f",&x);

x1 = x;

/* Converting degrees to radians*/

x = x*(3.142/180.0);
sinval = sin(x);

printf("Enter the accuary for the result\n");
scanf("%f", &acc);

term = x;
sinx = term;
n = 1;

do
{
den = 2*n*(2*n+1);
term = -term * x * x / den;
sinx = sinx + term;
n = n + 1;

} while(acc <= fabs(sinval - sinx));

printf("Sum of the sine series = %f\n", sinx);
printf("Using Library function sin(%d) = %f\n", x1,sin(x));

} /*End of main() */

/*------------------------------
Output
Enter the value of x (in degrees)
30
Enter the accuary for the result
0.000001
Sum of the sine series = 0.500059
Using Library function sin(30) = 0.500059

RUN 2
Enter the value of x (in degrees)
45
Enter the accuary for the result
0.0001
Sum of the sine series = 0.707215
Using Library function sin(45) = 0.707179
---------------------------------------------*/

This program uses the sine series formula. The absolute value is the number of terms used inorder to get the result. By increasing the number of times you are increasing the accuracy but at the cost of memory and execution time. So well balance has to considered in giving the absolute value.


You can increase the accuracy by exapanding the series with the odd powers of x. The program uses a varaible n to keep track of the number of terms in the fornula. When it meets the necessary limit, the value is printed. Another point to note is that first we are converting degrees into radinans using the formula x=(angle)*(PI / 180)


Check whether it is a palindrome

/* Write a C program to reverse a given integer number and check *
* whether it is a palindrome. Output the given numbers with suitable*
* message */

#include stdio.h
#include conio.h

void main()
{
int num, temp, digit, rev = 0;

clrscr();

printf("Enter an integer\n");
scanf("%d", &num);

temp = num; /* original number is stored at temp */

while(num > 0)
{
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}

printf("Given number is = %d\n", temp);
printf("Its reverse is = %d\n", rev);

if(temp == rev )
printf("Number is a palindrome\n");
else
printf("Number is not a palindrome\n");
}
/*------------------------
Output
RUN 1
Enter an integer
12321
Given number is = 12321
Its reverse is = 12321
Number is a palindrome

RUN 2
Enter an integer
3456
Given number is = 3456
Its reverse is = 6543
Number is not a palindrome
-----------------------------------*/

The main point to note is the logic in the program. 121 can be written as 100+20+1.

that is 1*100+2*10+1. This principal is used. So first the number is saved on other variable. Then divided by 10. the remainders are added in the same above way to get the number. Now this number is compared to duplicate copy of original number to check its same or not. If its same we will print it as a palindrome or else the otherwise

Sunday, July 13, 2008

sum of odd and even numbers from 1 to N

/* Write a C program to find the sum of odd numbers and *
* sum of even numbers from 1 to N. Output the computed *
* sums on two different lines with suitable headings */

#include stdio.h
#include conio.h

void main()
{
int i, N, oddSum = 0, evenSum = 0;

clrscr();

printf("Enter the value of N\n");
scanf ("%d", &N);

for (i=1; i <=N; i++)
{
if (i % 2 == 0)
evenSum = evenSum + i;
else
oddSum = oddSum + i;
}

printf ("Sum of all odd numbers = %d\n", oddSum);
printf ("Sum of all even numbers = %d\n", evenSum);
}
/*-----------------------------
Output
RUN1

Enter the value of N
10
Sum of all odd numbers = 25
Sum of all even numbers = 30

RUN2
Enter the value of N
50
Sum of all odd numbers = 625
Sum of all even numbers = 650

------------------------------*/

This is a straight example. Uses the concepts of even and odd numbers and sum of n numbers together

find the GCD and LCM of two integers

/* Write a C program to find the GCD and LCM of two integers *
* output the results along with the given integers. Use Euclids' algorithm*/

#include stdio.h
#include conio.h

void main()
{
int num1, num2, gcd, lcm, remainder, numerator, denominator;
clrscr();

printf("Enter two numbers\n");
scanf("%d %d", &num1,&num2);

if (num1 > num2)
{
numerator = num1;
denominator = num2;
}
else
{
numerator = num2;
denominator = num1;
}
remainder = num1 % num2;
while(remainder !=0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
lcm = num1 * num2 / gcd;
printf("GCD of %d and %d = %d \n", num1,num2,gcd);
printf("LCM of %d and %d = %d \n", num1,num2,lcm);
} /* End of main() */
/*------------------------
Output
RUN 1
Enter two numbers
5
15
GCD of 5 and 15 = 5
LCM of 5 and 15 = 15
------------------------------*/

This uses a Euclid's GCD (and LCM) algorithm. The discription is found here.

http://www.geocities.com/SiliconValley/Garage/3323/aat/a_eucl.html. Its better explained there. There is nothing much to tell about syntax.

print first N FIBONACCI numbers

/*Write a C program to generate and print first N FIBONACCI numbers*/

#include stdio.h

void main()
{
int fib1=0, fib2=1, fib3, N, count=0;

printf("Enter the value of N\n");
scanf("%d", &N);

printf("First %d FIBONACCI numbers are ...\n", N);
printf("%d\n",fib1);
printf("%d\n",fib2);
count = 2; /* fib1 and fib2 are already used */

while( count < N)
{
fib3 = fib1 + fib2;
count ++;
printf("%d\n",fib3);
fib1 = fib2;
fib2 = fib3;
}
} /* End of main() */

/*--------------------------
Enter the value of N
10
First 5 FIBONACCI numbers are ...
0
1
1
2
3
5
8
13
21
34
-------------------------------*/

This program is to print the fibanocci series. 0 1 1 2 3 5 8 13

The points to note in this program are two variables are preinstianted as the logic of it says that the sum of previous two numbers is the present number. Here there is a good point to note. The COUNT value is initially assigned to 0. but later changed to 2 as after execution, we only need 8 values excluding the initial value instanciated

Find the sum of 'N' natural numbers

/* Write a C program to find the sum of 'N' natural numbers*/

#include stdio.h
#include conio.h

void main()
{
int i, N, sum = 0;

clrscr();

printf("Enter an integer number\n");
scanf ("%d", &N);

for (i=1; i <= N; i++)
{
sum = sum + i;
}

printf ("Sum of first %d natural numbers = %d\n", N, sum);
}

/*----------------------------------------
Output
RUN1

Enter an integer number
10
Sum of first 10 natural numbers = 55


RUN2

Enter an integer number
50
Sum of first 50 natural numbers = 1275
------------------------------------------*/

Another straight forward program which uses a for loop to increment the number. The sum value is pre instiantiated to zero and we use a for loop to increment it. The output is displayed. The other way to execute this program is using the fornula for addition of n natural numbers

simulate a simple calculator

/* Write a C program to simulate a simple calculator to perform *
* arithmetic operations like addition, subtraction,multiplication *
* and division only on integers. Error message should be repoetrd *
* if any attempt is made to divide by zero */

#include stdio.h
#include conio.h

void main()
{
char oper; /* oper is an operator to be selected */
float n1, n2, result;

clrscr();

printf ("Simulation of a Simple Calculator\n\n");

printf("Enter two numbers\n");
scanf ("%f %f", &n1, &n2);

fflush (stdin);

printf("Enter the operator [+,-,*,/]\n");
scanf ("%c", &oper);


switch (oper)
{
case '+': result = n1 + n2;
break;
case '-': result = n1 - n2;
break;
case '*': result = n1 * n2;
break;
case '/': result = n1 / n2;
break;
default : printf ("Error in operation\n");
break;
}

printf ("\n%5.2f %c %5.2f= %5.2f\n", n1,oper, n2, result);

}
/*-----------------------------
Output
Simulation of Simple Calculator

Enter two numbers
3 5
Enter the operator [+,-,*,/]
+

3.00 + 5.00= 8.00


RUN2
Simulation of Simple Calculator

Enter two numbers
12.75
8.45
Enter the operator [+,-,*,/]
-

12.75 - 8.45= 4.30

RUN3
Simulation of Simple Calculator

Enter two numbers
12 12
Enter the operator [+,-,*,/]
*

12.00 * 12.00= 144.00


RUN4
Simulation of Simple Calculator

Enter two numbers
5
9
Enter the operator [+,-,*,/]
/

5.00 / 9.00= 0.56


------------------------------*/

This program is a command line calculator. This uses as the input of necessary operation as a string input and uses a case statement to execute the necessary arthematic equation. If a wrong operator is given then the error ms is displayed.

roots of a quadratic quadratic equation

/* write a C program to find and output all the roots of a *
* quadratic equation, for non-zero coefficients. In case *
* of errors your program should report suitable error message*/

#include stdio.h
#include conio.h
#include stdlib.h
#include math.h

void main()
{
float A, B, C, root1, root2;
float realp, imagp, disc;

clrscr();

printf("Enter the values of A, B and C\n");
scanf("%f %f %f", &A,&B,&C);

/* If A = 0, it is not a quadratic equation */

if( A==0 || B==0 || C==0)
{
printf("Error: Roots cannot be determined\n");
exit(1);
}
else
{
disc = B*B - 4.0*A*C;
if(disc < 0)
{
printf("Imaginary Roots\n");
realp = -B/(2.0*A) ;
imagp = sqrt(abs(disc))/(2.0*A);
printf("Root1 = %f +i %f\n",realp, imagp);
printf("Root2 = %f -i %f\n",realp, imagp);
}
else if(disc == 0)
{
printf("Roots are real and equal\n");
root1 = -B/(2.0*A);
root2 = root1;
printf("Root1 = %f \n",root1);
printf("Root2 = %f \n",root2);
}
else if(disc > 0 )
{
printf("Roots are real and distinct\n");
root1 =(-B+sqrt(disc))/(2.0*A);
root2 =(-B-sqrt(disc))/(2.0*A);
printf("Root1 = %f \n",root1);
printf("Root2 = %f \n",root2);
}
}

} /* End of main() */

/*---------------------------
Output
RUN 1
Enter the values of A, B and C
3 2 1
Imaginary Roots
Root1 = -0.333333 +i 0.471405
Root2 = -0.333333 -i 0.471405

RUN 2
Enter the values of A, B and C
1 2 1
Roots are real and equal
Root1 = -1.000000
Root2 = -1.000000

RUN 3
Enter the values of A, B and C
3 5 2
Roots are real and distinct
Root1 = -0.666667
Root2 = -1.000000
---------------------------------*/

The important points to note in this program are the usage of stdlib and math header files. The use of latter is already mentioned. The first is used because here we have used a abs() funtion which takes the unsigned value of discriminent. The logic is straight. First we calculate discriminant of the equation and check if the roots are real. If they are real, then we calculate normal value, and if not we use the absolute value to calculate the imaginary roots

find the biggest of three numbers

/* Write a C program to find the biggest of three numbers*/

#include stdio.h
#include conio.h
#include math.h

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

clrscr();

printf("Enter the values of a,b and c\n");
scanf ("%d %d %d", &a, &b, &c);

printf ("a = %d\tb = %d\tc = %d\n", a,b,c);

if ( a > b)
{
if ( a > c)
{
printf ("A is the greatest among three\n");
}
else
{
printf ("C is the greatest among three\n");
}
}
else if (b > c)
{
printf ("B is the greatest among three\n");
}
else
printf ("C is the greatest among three\n");


}

/*-----------------------------
Output
Enter the values of a,b and c
23 32 45
a = 23 b = 32 c = 45
C is the greatest among three

RUN2
Enter the values of a,b and c
234
678
195
a = 234 b = 678 c = 195
B is the greatest among three

RUN3
Enter the values of a,b and c
30 20 10
a = 30 b = 20 c = 10
A is the greatest among three
------------------------------*/

This is a straight forward program. The logic is the same what we have been studying from childhood.

Chech whether number is positive or negative

/* Write a C program to check whether a given integer *
* number is positive or negative*/

#include stdio.h
#include conio.h

void main()
{
int number;
clrscr();

printf("Enter a number\n");
scanf ("%d", &number);

if (number > 0)
printf ("%d, is a positive number\n", number);
else
printf ("%d, is a negative number\n", number);

}
/*-----------------------------
Output
Enter a number
-5
-5, is a negative number

RUN2
Enter a number
89
89, is a positive number
------------------------------*/

This is also an easy program. The only thing to note is logic. It checks whether value is above '0' or not and displayes the output

heck whether a given integer is odd or even

/* Write a C program to check whether a given integer is odd or even*/

#include stdio.h
#include conio.h

void main()
{
int ival, remainder;

clrscr();

printf("Enter an integer :");
scanf ("%d", &ival);

remainder = ival % 2;

if (remainder == 0)
printf ("%d, is an even integer\n", ival);
else
printf ("%d, is an odd integer\n", ival);

}
/*-----------------------------
Output

RUN1

Enter an integer :13
13, is an odd integer

RUN2
Enter an integer :24
24, is an even integer

---------------------------------*/

This is also an easy program. The only thing to note is logic. It deivides input number by 2 and declares the result depending on the value of remainder.

Find the simple interest

/* Write a C program to find the simple interest , given principle, *
* rate of interest and times*/

#include stdio.h
#include conio.h

void main()
{

float p, r, si;
int t;

clrscr();

printf("Enter the values of p,r and t\n");
scanf ("%f %f %d", &p, &r, &t);

si = (p * r * t)/ 100.0;

printf ("Amount = Rs. %5.2f\n", p);
printf ("Rate = Rs. %5.2f%\n", r);
printf ("Time = %d years\n", t);
printf ("Simple interest = %5.2f\n", si);

}

/*-----------------------------
Output
Enter the values of p,r and t
2000
8
3
Amount = Rs. 2000.00
Rate = Rs. 8.00%
Time = 3 years
Simple interest = 480.00

------------------------------*/

This is a pretty straight forward example which uses the basic mathematical formula for calculation. The only new thing to note here is %5.2f which is dealt in previous example.

Area of a circle, given the radius

/* Write a C program to find the area of a circl, given the adius*/

#include stdio.h
#include conio.h
#include math.h
#define PI 3.142

void main()
{
float radius, area;
clrscr();

printf("Enter the radius of a circle\n");
scanf ("%f", &radius);

area = PI * pow (radius,2);

printf ("Area of a circle = %5.2f\n", area);
}

/*-----------------------------
Output

RUN1
Enter the radius of a circle
3.2
Area of a circle = 32.17

RUN 2
Enter the radius of a circle
6
Area of a circle = 113.11

------------------------------*/

This program calculates the area of the circle using the classical formula. This program seems straight forward but there are a couple of concepts highlighted here. The first one is the predefined value of PI in preprocessor statements. This declares the value of PI before only. So that it can be used as a keyword temporarily. This thye of constants are called symbolic constants


pow() is the predefined function in math header file. So we have declared it in predefined functions.


The third most imporatnat thing is %5.2f. This thpe of declaration is used for defining the data type of output. This allocates 5 vacant spaces for the whole output obtained from statement. The 2 allocates 2 places for the value after decimal. So only two values are displyed in the output. The 5 places being occupied are 3,2,.,1,7. The main reason of doing so is to stop the memory over flow. This not only saves the execution time but also reduces the memory spaces used. You can think that we can declare the same at starting. If we are doimg so, that memory is allocated form starting only which will be vacant till the program is executed. So its better we create it just before executing as it will save our resources.

Area of a triangle, given three sides, C learn by Example, Tutorial

/* Write a C program to find the area of a triangle, given three sides*/

#include stdio.h
#include conio.h
#include math.h

void main()
{
int s, a, b, c, area;
clrscr();

printf("Enter the values of a,b and c\n");
scanf ("%d %d %d", &a, &b, &c);

/* compute s*/

s = (a + b + c) / 2;

area = sqrt ( s * (s-a) * (s-b) * (s-c));

printf ("Area of a triangale = %d\n", area);
}

/*-----------------------------
Output

Enter the values of a,b and c
3
4
5
Area of a triangale = 6
------------------------------*/

This program uses the formula area = square root of (s*(s-a)*(s-b*(s-c)).

Indorer to use execute this we need to use the command sqrt() (square root function) which is predefined in math.h header file. So we are declaring that file in the preprcessor statements. Rest else is straight forward

Introduction

This is not a beginner guide. It means that ithis doesnt deal with the concepts like 'int','%d' etc. The author assumes that the readers have prior knowledge of the programming syntax. It is a reference guide for students and professionals to have a quick look and remind all the concepts and logics for various programs. This is a for a quick reference learn by example guide highlights the important logic and concepts of C. One can understand the logic the programs by having a look at them and all the twists in the program are explained below

So go through and have fun....