Sample C Programs
Sailing through Programs
Here we will do some sample programs from the knowledge of what we have learned so far./* Program to do all arithmetic operations */
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,sum,pro,diff,quo;
clrscr( );
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
sum=a+b;
pro=a*b;
diff=a-b;
quo=a/b;
printf("Sum=%d\n",sum);
printf("Difference=%d\n",diff);
printf("Product=%d\n",pro);
printf("Quotient=%d\n",quo);
getch( );
}
In this program we need to do all arithmetic operations on two numbers, so there have to be two variables to store two numbers, and to store the result of four arithmetic operations we need 4 variables. So we have declared all 6 variables, 'a' and 'b' for storing two numbers and sum, pro, diff, and quo to store the arithmetical operation's results. Whenever you use a variable in your program try to give some meaningful name.
After Declaring two numbers, we are prompting for the user to enter two numbers, and the values thus enter by the user are stored in to 'a' and 'b'. So we got that two numbers to perform the arithmetical calculations, then we added all those code to find the sum, product, quotient, and division. Then print the result we've calculated.
/*Program to Interchange two values without using any other variables*/
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b;
clrscr( );
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
printf("\nBefore Swapping the Values\n");
printf("a=%d\tb=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter Swapping the Values\n");
printf("a=%d\tb=%d\n",a,b);
getch( );
}
A simple logic is applied to swap the values.
Before-> a=10 and b=20
a=a+b; /* a=30 and b=20 */
b=a-b; /* a=30 and b=10 */
a=a-b; /* a=20 and b=10 */
After-> a=20 and b=10
Multiplication and Division technique can also be used to swap the values. Use the following logic:-
Before-> a=10 and b=2
a=a*b; /* a=20 and b=2 */
b=a/b; /* a=20 and b=10 */
a=a/b; /* a=2 and b=10*/
After-> a=2 and b=10



0 comments:
Post a Comment