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

Previous
Next

Reading Data from the Keyboard

A program is nothing if it is not accepting any data from the user or outputs some data to the user. A program is interactive only if it accepts data's from the user at run time. It should accepts data needed for the program and output the result based on the user input. For example a user may want to input basic salary of an employee to calculate his net salary, he can use the same program to calculate the net salary of another employee by inputting different values upon his requirement.

C provides a library function scanf( ) that accepts data's from the keyboard. It uses the following syntax :

scanf("control string",&variable_name");

control string uses the control string for the type of variable_name, i.e. if we are reading an integer value then control string will be %d, if we are reading a character value then the control string is %c. Variable name preceded by an ampersand (&) symbol. Ampersand (&) is also known as "address of operator", address of operator instructs the computer where to store the data read from the keyboard. Ampersand operator provides the memory address of the variable we specified, and the value just inputted stored to that memory location, we can access the value using the variable name.

scanf("%d",&age); //reading an integer value;
scanf("%f",&avg);//reading a float value;
scanf("%c%d",&grade,&roll); //reading a character and an integer.
scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);//reading 5 integers.

Learning by Example 2

/* Program to read two numbers and find their sum */
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,sum; /* declare three integer variables */
clrscr( );
printf("Enter two numbers : "); /* Prompt the user to enter two numbers */
scanf("%d%d",&a,&b); /* Read two integers from keyboard values in a and b */
sum=a+b; /* add a and b, store result in sum */
printf("Sum=%d",sum); /* Print the value in sum */
/*printf("%d+%d=%d,a,b,sum); */ /* Try using this to print sum*/
getch( );
}
int a,b,sum; will declare three integer variables a,b,sum each variable will get 2 bytes memory space allocated, a,b and sum now may contain some garbage values.

Next we are prompting the user to enter two numbers using the printf( ), it is necessary in our programs to instruct the user what to do next, or what to do from his side for program execution.

While executing scanf("%d%d",&a,&b); the control will wait for two values from keyboard, input two numbers and that numbers will be stored in the variable a and b. Here first number will be stored in variable 'a' and second will be in variable 'b'.

sum=a+b; will add the values within 'a' and 'b' and assignment operator (=) will assign the value thus results to the variable 'sum'.

printf("Sum=%d",sum); will print the sum in the format Sum=250 (If we input two number 175 and 75).

Previous
Next

Variables, Constants, Keywords & Datatypes

All programs deal with some sort of data, a program accepts some data from the user and manipulates it and provide the manipulated/processed data - the information. We may use different kinds of data in our programs, it may be a constant value, or a varying type known as variable. The type of data's used may be different, for example in a mark list preparing program the datas may include student_name,subject,mark,roll_no,avg etc., student_name is a data which uses some characters to form a student name, roll_no represents student's roll number and it may be a number-an integer. Likewise avg may be a decimal value. So we are dealing with different kinds of data.

Constants are data value which is predefined before a program is used. Values remain unchanged during the program execution. For example "C Program" is a string constant.

Variables are identifiers which we used to represent or identify a data. Variables are varying type values. Here the data may change or be assigned different values as the program runs. For example

emp_salary=12000; (emp_salary is a variable which holds the value 12000)
emp_salary=12500; (now emp_salary contains the value 12500)

There are some rules when using variable names.

Rules of naming variables

1. Variable name should only contain alphabets (a-z,A-z), digits(0-9) and underscore(_).
2. Variable name must start with an alphabet or an underscore.
3. Variable name should not contain any blank space.
4. Pre defined words in C (known as Keywords) cannot be used as a variable name.

Care should be taken while program in C as keywords or variables used in C are case sensitive.

Keywords are the basic constructs used to write a program. Keywords have a predefined meaning in C. For example int is a keyword used to declare an integer variable. Keywords cannot be used as a variable/function name.

Variables are used to represent a data in a program, each data may be of different type, age data may be a numeric type(integer). Grade of a student can be a character. So all variables used in a C program must be declared to the appropriate type before we use those variables. Each variables thus declared possess some space of memory to hold the value it represents. In C data types can be divided as Primary and Secondary(Derived).

Primary Data types : int, char, float, double. int data type can be used to represent an integer value, char data type is used to represent a single character, float data type is used to store a decimal value, double data type is used to declare a double precision floating point. Each type have a range of values that it can hold, and each type allocates a specific byte of memory for the value.

1. int
Range : -32768 to +32767
Memory : 2 bytes
Control String : %d

2. char
Range : -128 to +127
Memory : 1 byte
Control String : %c

3. float
Range : 3.4e-38 to 3.4e+38
Memory : 4 bytes
Control String : %f

4. double
Range : 1.4e-308 to 1.4e+308
Memory : 8 bytes
Control String : %lf

int data type allocates 2 bytes to store an integer number. A variable declared as int can hold an integer value in the range of -32768 to +32767. If you want to store an integer above this range instead of int you may use long int, control string of long int is %ld. Control string is associated with C data types and you are required to use appropriate control string with each variable used in your program while you read a data to the variable or print a data in variable. Control string enables the format of data in the variable.

Secondary Data types can be created from the existing data types. It includes arrays, structures, unions, enums, linked lists, pointers etc.

Declaring a Variable : You can declare a variable by specifying the data type of that variable.

Syntax : <datatype> <variable_name>;

int age; /*Declare an integer variable age.*/

float avg,mark; /*2 variables are declared. 4 bytes allocated to each variable, and can store any values which falls in the float range.*/

float avg; /*variable avg is declared*/
avg=98.74;/*avg is initialized with value 98.74*/

char ch='A'; /*a character variable ch is declared with the value A.*/

So now have a look at the program with some variables

/*Program to print variable values */
#include<stdio.h>
#include<conio.h>
main( )
{
int num=850;
float avg=98.54;
double dblval;
char ch='S';
dblval=99745.5684;
clrscr( );
printf("Character ch=%c",ch);
printf("\nInteger num=%d",num);
printf("\nFloat avg=%c",avg);
printf("\nDouble dblval=%lf",dblval);
/*printf("ch=%c\nnum=%d\navg=%f\ndblval=%f",ch,num,avg,dblval);*/
getch( );
}

Previous
Next

Design by The Blogger Templates The Blog Full of Games

© CourseZone
2008 - 2010 All Rights Reserved.