Variables, Data Types, Constants and Operators
Source Code from Notes
Example 1
/* program to add two integer values
and display result */
#include <stdio.h>
main()
{
/* declare variables */
int value1, value2, sum;
/* assign values and compute the result */
value1 = 32;
value2 = 27;
sum = value1 + value2;
/* display the result */
printf("The sum of %d and %d is %d\n",
value1,value2,sum);
}
Example 2
Examples of using these format controls
#include <stdio.h>
/* format controls */
main()
{
printf("single specified character: %c\n",'a');
printf("ASCII character of decimal 65: %c\n", 65);
printf("Integer 65 in decimal: %d\n", 65);
printf("Integer with leading zeros: %04d\n", 65);
printf("Scientific notation: %e\n",31415.9);
printf("Floating point: %f\n",314.159);
printf("Floating point: %0.2f\n",314.159);
printf("General format: %g\n",3.14);
printf("General format: %g\n",0.000314);
printf("String value: %s\n", "Hello");
}
Example 3
This is the example program to calculate the area of a rectangle
#include <stdio.h>
main()
{
/* type definitions */
/* 3 variables - length, breadth and area */
float length, breadth, area;
/* input phase - read length and breadth from user */
printf("Enter the length and breadth\n");
scanf("%f %f", &length, &breadth);
/* computation - calculate area */
area = length * breadth;
/* output phase */
printf("The area of the rectangle with length %f and breadth %f is %f
\n", length, breadth, area);
}
Example 4
This example calculates the average value of three numbers entered by
the user.
/*Program to calculate the average of three numbers*/
#include <stdio.h>
main()
{
float number1,number2,number3;
float average;
/*Enter values*/
printf("Enter three numbers: ");
scanf("%f %f %f",&number1,&number2,&number3);
/*calculate average*/
average = (number1 + number2 + number3)/3.0;
/*Output result*/
printf("The average value of %f %f and %f is %f\n",
number1, number2, number3,average);
}
Example 5
This example prompts the user to input a number and then calculates the
reciprocal of this number.
/*Program to calculate the reciprocal of a number*/
#include <stdio.h>
main()
{
float number;
float reciprocal;
/*Enter Value*/
printf("Enter a number: ");
scanf("%f",&number);
/*Calculate reciprocal*/
reciprocal = 1.0 / number;
/*output result*/
printf("The reciprocal of %f is %f\n",
number, reciprocal);
}
Example 6
This example illustrates the use of constants. It calculates the area and
circumference of a circle, when given the radius.
/* program to calculate circumference and area of circle */
#include <stdio.h>
#define PI 3.14159
main()
{
/*define variables*/
float radius,circumference,area;
/*Input radius*/
printf("Enter the radius: ");
scanf("%f",&radius);
/*calculate radius and circumference*/
circumference = PI * 2 * radius;
area = PI * radius * radius;
/*display results*/
printf("The circumference is %f and the area is %f\n",
circumference,area);
}