How to write, compile and run a program in C

Invention of C
C was first invented and implemented by Dennis Ritchie. C is the result of a development process
that started with an older language called BCPL. BCPL was developed by Martin Richards and it
influenced a language called B, which was invented by Ken Thompson. B led to the development
of C in 1970s.
For many years, the de facto standard for C was the version supplied with the Unix version 5
operating system. It was first describe in The C programming Language by Brian Kernighan and
Dennis Ritchie. In the summer of 1983 a committee was established to create an ANSI standard
that would define the C language once and for all.
C is called a middle-level language
C is called a middle-level computer language because it combines the best elements of high-level
languages with the control and flexibility of assembly language. As a middle-level computer
language, C allows the manipulation of bits, bytes, and addresses- the basic elements with which
the computer functions. Despite this fact C code is also very portable. Portability means that it is
easy to adapt software written for one type of computer or operating system to another.
C is not a strongly typed language. C permits almost all type conversions. For example, you may
freely intermix character and integer types in an expression.
In the same vein, C does not demand strict type compatibility between a parameter and an
argument. C allows an argument to be of any type as long as it can be reasonably converted into the
type of parameter. Further, C provides all of the automatic conversions to accomplish this.
C is a Structured Language
C is commonly referred to as a structured language. The distinguishing feature of a structured
language is compartmentalization of code and data. His is the ability of a language to section off
and hide from the rest of the program all information and instructions necessary to perform a
specific task. One way that you achieve compartmentalization is by using subroutines so that the
events that occur within them cause no side effects in other parts of the program. This capability
makes it very easy for programs to share sections of code.
A structured language allows you a variety of programming possibilities. It directly supports
several loop constructs, such as while, do-while, and for.
In a structured language, the use of goto is either prohibited or discouraged and is not the common
form of program control.
A structured language allows you to place statements anywhere on a line and does not require a strict field concept.
1
Example of nonstructured programs are FORTRAN, BASIC, COBOL. Examples of structured programs are Pascal,
Ada, Java, C, C++, Modula-2.
Another way to structure and compertmentalize code in C is through the use of code blocks. A code block is a logically
connected group of program statements that is treated as a unit.
C Keyword
There are 32 keywords in C. These are shown in table.
auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for,
goto, if, int , long, register, return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, while.
In addition many compilers have added several keywords that better exploit their operating
environment. Here is a list of some commonly used extended keywords: asm, _cs, _ds, _es, _ss,
cdecl, far, huge, interrupt, near, pascal. All C( and C++) keywords are loercase.
The first program in C
Now you know C is a structured language. You must write a program in a specified format. Your
first program is a “Welcome“ program (prog1.c). See the program bellow.
( prog1.C)
#include<stdio.h>
void main()
{
printf(“Welcome to C”);
}
For now don’t ask too much why I have used #include<stdio.h>. Just know it to write a C program
you should use it. Then why void main() ? Every C program must use a main() function. void is a
return type of the function main(). You will know more about it in future. And printf() is a function
that can display a message on monitor. This program will display the message “Welcome to C”.
How to write, compile and run a program in C
At first open the C software( C\C++ compiler) of your computer. Write the program as given and
save it as prog1.c. The file extension of C program is .C. Now press Alt-F9 (Alter F9) to compile
the program. If the program is error- free then press Ctrl-F9 (Control F9) to run the program. To see
the output press Alt-F5. You can see the output “Welcome to C” on your monitor.
2
Variables and Constants
C can use different types of data. Data may be represented either by
variables or by constants. Variables and constants can store data. A program
can alter the value of a variable. The value of a constant is fixed and
cannot be altered in a program. Now you will see and understand a program
that uses a variable.
(Prog2.c)
#include<stdio.h>
void main()
{
int i=20;
char ch=’A’;
printf(“\nThe value of i is %d”,i);
printf(“\nThe value of ch is %c”,ch);
}
Here i is an integer type of variable which stores a value of 20. integer means
whole number without any fraction. This program will display the message “The
value of i is 20”. To display the value of an integer variable “%d” is used in
printf(). Similarly %f for float, %c for char. “\n” is used to print the
statement to the next line.
There are five basic data types in C: char( Character), int (integer), float(
floating point number/ fractional number), double (fractional number with bigger
range) and void (valueless).
Table: Data types and their size, range
Type
Size in Bits
char
8
int
16
float
32
double
64
Range
-128 to 127
-32768 to 32767
Six digits of precision
Ten digits of precision
Modifiers of Basic data types
Modifier is used to alter the meaning of the basic type to fit various
situations more precisely. The modifiers are
signed
unsigned
long
short
Table: Some examples of data types with modifiers
Type
Size in Bits
Range
unsigned char
8
0 to 255
signed char
8
-128 to 127
unsigned int
16
0 to 65535
signed int
16
-32768 to 32767
short int
16
-32768 to 32767
long int
32
-2147483648 to 2147483647
long double
80
Ten digits of precision
3
const
Variables of type const may not be changed by your program.
const int a=10;
Constants
Hexadecimal and octal Constants
String Constants
Blackslash Character Constants
Identifiers name
In C the names of variables, labels and functions are called identifiers. These
identifiers can vary from one to several characters. These identifiers can vary
from one to several characters. The first character must be a letter or an
underscore.
Correct Identifiers
var1, test23
st_name
Incorrect
1var, hi!there
st-name, st..name
Operators
There are four main classes of operators: arithmetic, relational, logical and
bitwise. In addition, there are some special operators for particular tasks.
Arithmetic
+
Addition
Subtraction
*
Multiplication
/
Division
%
Modulus
++
Increment
-Decrement
Relational
>
Greater than
>= Greater than or
equal to
<
Less than
<= Less than or
equal to
== Equal
!= Not Equal
Logical
&&
AND
||
OR
!
NOT
Bitwise
&
AND
|
OR
^
XOR
~
NOT
Now we will see an example of some arithmetic operators.
(Prog3.c)
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter the value of a ”);
scanf(“%d”,&a);
printf(“Enter the value of b ”);
scanf(“%d”,&b);
c=a+b;
printf(“\nThe value of c is %d”,c);
c=a-b;
printf(“\nThe value of c is %d”,c);
c=a*b;
printf(“\nThe value of c is %d”,c);
c=a/b;
4
printf(“\nThe
c=a%b;
printf(“\nThe
++a;
printf(“\nThe
--b;
printf(“\nThe
value of c is %d”,c);
value of c is %d”,c);
value of a is %d”,a);
value of b is %d”,b);
}
This program takes two inputs from keyboard by scanf() functions into variables
a and b. Then it performs addition, subtraction, multiplication, division and
finds modulus and display the results. Finally it increment a by 1 and decrement
b by 1 and display them.
Other operators
The Assignment Operators
Type Conversion in Assignments
Multiple Assignments
The ? Operator
The & and * Pointer Operators
The Comma Operators
The Dot(.) and arrow (->) Operators
The [] and () Operators
Precedence Summary
Highest
() [] ->
! - ++ --(type) * & sizeof
* / %
+ << >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= etc
Lowest
True and False in C
A true value is any nonzero value, including negative numbers. A false value is
zero.
5
Selection Statement
C supports two types of selection statement if and switch.
If statement
The general form of if statement is
if(expression) statement1;
else statement2;
If the expression is true then it will execute statement1 otherwise it will
enter into else and execute statement2. The following program (prog4.c) will
find the maximum number from two floating-point numbers a and b.
(Prog4.c use of if-else)
#include<stdio.h>
void main()
{
float a,b;
printf("Enter the value
scanf("%f",&a);
printf("Enter the value
scanf("%f",&b);
if(a>b)
printf("a is greater
else
printf("b is greater
}
of a ");
of b ");
than b");
than a");
Netsed ifs
A nested is an if that is the target of another if or else.
if(i)
{
if(j) statement
if(k) statement
else statement
1;
2;
3;
}
else
statement 4;
If-else-if statement
The form of if-else-if statement is
if(expression)
statement1;
else if(expression)
statement2;
6
else
.
.
.
statement;
The following program (prog5.c) will take an integer number between 1 to 7
and display the corresponding day say 1 for Saturday and 2 for Sunday and so
on.
(prog5.c use of if-else-if)
#include<stdio.h>
void main()
{
int day;
printf("Enter the number of day ");
scanf("%d",&day);
if(day==1)
printf("Saturday\n");
else if(day==2)
printf("Sunday\n");
else if(day==3)
printf("Monday\n");
else if(day==4)
printf("Tuesday\n");
else if(day==5)
printf("Wednesday\n");
else if(day==6)
printf("Thursday\n");
else if(day==7)
printf("Friday\n");
else printf("You have entered a wrong number");
}
The ? alternatives
You can use ? operator to replace if-else statement. The program prog6.c find
the maximum number from two numbers by using ? operator.
(prog6.c use of ? operator)
#include<stdio.h>
void main()
{
float a,b,max;
printf("\nEnter the value of a ");
scanf("%f",&a);
printf("\nEnter the value of b ");
scanf("%f",&b);
max = a>b ? a:b;
printf(“The maximum number is %8.2f ”,max);
}
If a is greater than b then max will take the first value a otherwise it will
take the second value b.
switch..case statements
The general form of a switch statement is
switch(expression){
case constant1:
statements
7
break;
case constant2:
statements
break;
.
.
.
default:
staments
}
switch statement tests the value of an expression against a list of integer
or a character and jump to the point where a match is found. The program
prog7.c will take the month-number as input from keyboard and display the
name of the month. Say if you give input 1 the output will be January and 2
for February and so on.
(prog7.c use of switch..case)
#include<stdio.h>
void main()
{
int month;
printf(“Enter the month number”);
scanf(“%d”,&month);
switch(month){
case 1:
printf(“January”);
break;
case 2:
printf(“February”);
break;
case 3:
printf(“March”);
break;
case 4:
printf(“April”);
break;
case 5:
printf(“May”);
break;
case 6:
printf(“June”);
break;
case 7:
printf(“July”);
break;
case 8:
printf(“August”);
break;
case 9:
printf(“September”);
break;
case 10:
printf(“October”);
break;
case 11:
printf(“November”);
break;
case 12:
printf(“December”);
break;
default:
printf(“Wrong input”);
}
}
Loops
Loop causes a section
condition is reached.
of
your
program
to
be
repeated
until
a
certain
The for loop
8
In most cases the for loop is used for fixed iterations. The general form of
the for statement is
for(initialization; condition; increment) statement;
The following program (prog8.c) calculate the summation of a series using for
loop. The series is:
s=1+2+3+.............n
(prog8.c use of for loop)
#include<stdio.h>
void main()
{
int i,sum=0,n;
printf("Enter last number");
scanf(“%d”,&n);
for(i=1;i<=n;i++)
sum=sum+i;
printf("Sum of the series is: %d",sum);
}
The loop will start with i=1. It will continue upto n. Every times i will be
increased by 1. All these numbers will be added to sum. Here sum variable was
initialized to 0 at the beginning.
Here is another example of a for loop. This program (prog9.c) will take some
inputs from keyboard and calculate summation and average of those numbers.
(prog9.c use of for loop)
#include<stdio.h>
void main()
{
int i,sum=0,n,x;
printf("How many numbers: ");
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf("Enter number to add: ");
scanf(“%d”,&x);
sum=sum+x;
}
printf("\nSum is: %d",sum);
printf("\nAverage is: %d",sum/n);
}
The while loop
The while loop repeats the body of the loop as long as the loop condition is
true. The general for of while loop is
while(condition) statement;
The program (prog10.c) will take some inputs from keyboard and calculate
summation and average of those numbers using while loop.
9
#include<stdio.h>
void main()
{
int i,sum=0,n,x;
printf("How many numbers: ");
scanf(“%d”,&n);
i=1;
while(i<=n)
{
printf("Enter number to add: ");
scanf(“%d”,&x);
sum=sum+x;
++i;
}
printf("\nSum is: %d",sum);
printf("Average is: %d",sum/n);
}
The program prog11.c will take a number from keyboard and calculate the square
of that number. This process will be continued until you press ESC.
(prog11.c use of while loop)
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
int num, square;
printf(" Press Esc to quit");
ch=getch();
while(ch!=27)
{
printf("\n Enter a number");
scanf("%d",&num);
square=num*num;
printf(" The square of %d is %d", num,square);
printf("\n Press Esc to quit");
ch=getch();
}
}
Here the (ASCII) equivalent of ESC is 27.
The do while loop
The do-while loop test the condition at the end of the loop. This means that a
do-while loop always executes at least once. The general form of the do-while
loop is
do{
statement;
}while(condition);
10
The following program (prog12.c) will take some inputs from keyboard and
calculate summation and average of those numbers using do-while loop.
(prog12.c Not a better use of do-while loop)
#include<stdio.h>
void main()
{
int i,n,x;
float sum=0;
printf("How many numbers: ");
scanf(“%d”,&n);
i=1;
do
{
printf("Enter number to add: ");
scanf(“%d”,&x);
sum=sum+x;
++i;
}while(i<=n);
printf("\nSum is: %f",sum);
printf("\nAverage is: %f",sum/n);
}
The program prog13.c will take a number from keyboard and calculate the square
of that number. This process will be continued until you press ESC.
(prog13.c better use of do-while loop)
#include<stdio.h>
#include<conio.h>
void main(){ char ch;
int num, square;
do
{
clrscr();
printf("\n Enter a number: ");
scanf("%d",&num);
square=num*num;
printf(" The square of %d is %d", num,square);
printf("\n Press Esc to quit");
ch=getch();
}while(ch!=27) ;
}
clrscr() function is used in this program to clear the screen. To use getch()
and clrscr() functions conio.h header is included in this program.
The break statement
The break statement has two uses. You can use it to terminate a switch-case
statement (already shown in prog7.c). You can also use it to terminate a loop
immediately. The program prog14.c will continue until you give a number less
11
than 1000 except 13. If you take 13 as an input from keyboard it will encounter
a break statement and come out from the loop.
(prog14.c use of break statement)
#include<stdio.h>
void main(){
int num;
do{
printf("Press any number less than 1000 except 13");
scanf("%d",&num);
if(num==13)
break;
}while(num<1000);
}
continue statement
The continue statement stops the current iteration of the loop immediately and
starts next iteration.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
int num, square;
do {
printf("\n Enter a number: ");
scanf("%d",&num);
if(num>100)
{
printf("\nThe number is greater than 100");
continue;
}
square=num*num;
printf("\nThe square of %d is %d", num,square);
printf("\n Press Esc to quit");
ch=getch();
}while(ch!=27) ;
}
ASCII value
Every character has an equivalent integer value which is called ASCII number.
For example 65 for A, 66 for B, 48 for 0(zero),49 for 1, 97 for a,98 for b, 27
for ESC and 32 for SPACEBAR.
Array
An array is a collection of elements of the same type. A specific element in an
array is accessed by an index.
12
One–Dimension Array
One-dimensional array can handle a list of elements of single row or column. The
general form of an array is
type var_type[size];
For example a list of 20 integer numbers can be declared as
int list[20];
The program prog15.c find the maximum number from a list of numbers. It takes
inputs from keyboard. Here max variable is used to store the maximum. At first
it stores the first element list[0]. It then test rest of the elements from the
list of an array and find the maximum.
(prog15.c use of one-dimensional array)
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
int list[20], max, n,num,i;
clrscr();
printf("How many numbers? ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter a number: ");
scanf("%d",&num);
list[i]=num;
}
max=list[0];
for(i=1;i<n;i++)
{
if(list[i]>max)
max=list[i];
}
printf("\nThe maximum number is %d",max);
getch();
}
Here is a program to Sort some numbers in ascending order.
#include<iostream.h>
void main()
{
int list[20];
int i,j,temp,n;
cout<<"Enter how many number: ";
cin>> n;
for (i=0;i<n;i++)
{
cout<<"Enter number: ";
cin>>list[i];
}
for(i=0;i<n-1;i++)
13
{
for(j=i+1;j<=n-1;j++)
{
if(list[i]>list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
}
for(i=0;i<n;i++)
cout<<list[i]<<"
";
}
Here we will see another example of a one-dimensional char array. The program
prog16.c will display the string in reverse order. A string is defined as an
array of character terminated by a NULL character. A NULL character is
represented as ‘\0’. To use string functions you must include string.h header.
(prog16.c)
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
int i,l;
char str[20];
clrscr();
printf("Enter a string: ");
scanf("%s", str);
l=strlen(str);
printf("Reverse is: ");
for(i=l-1;i>=0;i--)
printf("%c",str[i]);
getch();
}
To take string as an input from keyboard you should use “%s” inside scanf().
Here & is not used in scanf(), because an array is an address itself. The
function of strlen() function is to find the length of a string.
Null-Terminated String
14
A null-terminated string contains the characters that comprise
follwed by a null. This is the only type of string defined by C.
the
string
Standard string handling functions
strcmp(s1,s2)
strcmp() compares two strings and returns an integer value. If first string
argument is less than the second, strcmp() returns a value less than zero. If
first string argument is equal to the second, the function returns a value
equal to zero. If first string argument is greater than the second, the function
returns a value greater than zero. Comparison is performed from left to right
and according to the ASCII value of corresponding character. Here ‘a’(ASCII
value 97) is greater than ‘A’(ASCII value 65). “bc” is greater than “abcd”.
strcmp(“kabir”,”karim) will return less than zero because “kabir” is smaller
than “karim”.
strcmp(“kabir”,”kabir”) will return zero, as because both are same.
strcmp(“karim”,”kabir”) will return greater than zero.
strcpy(s1,s2)
strcpy() copies the contents of the second string to the first string named in
the strcpy() parameters. For example, the following statement:
strcpy(str,”bangla”);
will copy the string “bangla” to the array str.
strcat(s1,s2)
strcat() is used to join or concatenate(add) the second string with the first
string. Strcat() appends the second string to the first string.
For example, if str is a string variable and contains “bangla”
strcat(str,”desh”)
will add “desh” to the current contents of str. So the value of str will be
“bangladesh”.
strlen(s1)
This function returns the length(number of characters) of the string.
strlen(“kabir”) will return 5. So if you write
i = strlen(“kabir”)
the value of i will be assigned to 5.
strchr(s1,ch)
Returns a pointer to the first occurrence of ch in s1.
strstr(s1,s1)
Returns a pointer to the first occurrence of s2 in s1.
Two-Dimensional Array
Two-dimensional array is used when data are arranged in a matrix (tabular)
form. For example the following data (a matrix) can be handled by twodimensional array.
15
Col 0
5
5
col 1
4
7
<- row 0
<- row 1
Two-dimensional array has two dimensions, one for row and one for column. The
elements can be accessed by the combined (row,col) index. Here 5 can be accessed
by index (0,0) and 2 can be accessed by index (1,0) and so on. The program
prog17.c will take input in two matrixes by using two-dimensional array and add
them in third matrix.
(prog17.c use of two-dimensional array)
#include<stdio.h>
#include<conio.h>
void main()
{
int table1[4][4],table2[4][4],table3[4][4];
int row,col,i,j;
clrscr();
printf("How many rows: ");
scanf("%d", &row);
printf("How many cols: ");
scanf("%d", &col);
printf("Enter data for first matrix\n");
for(i=0;i<row;i++)
{
printf("Enter for row%d ",i);
for(j=0;j<col;j++)
scanf("%d",&table1[i][j]);
printf("\n");
}
printf("Enter data for Second matrix\n");
for(i=0;i<row;i++)
{
printf("Enter for row%d ",i);
for(j=0;j<col;j++)
scanf("%d",&table2[i][j]);
printf("\n");
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
table3[i][j]=table1[i][j]+table2[i][j];
}
printf("\nmatrix after addition\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf(" %d",table3[i][j]);
printf("\n");
}
16
getch();
}
Here table1,table2 takes two matrixes as inputs from keyboard and then add these
matrixes in table3. Finally it displays the added result.
Structure
A structure is a collection of variables referenced under one name. The
variables of the structure are called members. Generally all the members of a
structure are logically related. The structure of a student can be declared as
struct student{
int roll;
char name[25];
char dept[20];
int marks;
};
The program prog18.c will take inputs in a student record and display the record
showing the grade.
(prog18.c use of structure)
#include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char name[25];
char dept[20];
int marks;
};
void main()
{
clrscr();
student st;
printf("Enter the roll: ");
scanf("%d",&st.roll);
printf("\nEnter the name: ");
scanf("%s",st.name);
printf("\nEnter the dept: ");
scanf("%s",st.dept);
printf("\nEnter the marks: ");
scanf("%d",&st.marks);
printf("\nThe roll is: %d",st.roll);
printf("\nThe name is: %s",st.name);
printf("\nThe dept is: %s",st.dept);
printf("\nThe marks is: %d",st.marks);
if(st.marks>=80)
printf("\nGrade is A");
else if(st.marks>=70)
printf("\nGrade is B");
else if(st.marks>=60)
17
printf("\nGrade is C");
else if(st.marks>=50)
printf("\nGrade is D");
else if(st.marks>=40)
printf("\nGrade is D+");
else
printf("\nFail");
getch();
}
student is not a variable. It is a type only. To declare a variable of student
you should write
student st;
The member variables of student can be accessed by st. To access roll we should
write st.roll, for name st.name and so on.
It is possible to declare an array of a structure. To take inputs for 10
students we can declare it as
student st[10];
(prog19.c
#include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char name[25];
char dept[20];
int marks;
};
void main()
{
clrscr();
int i,n;
student st[10];
printf("How many students? ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the roll: ");
scanf("%d",&st[i].roll);
printf("\nEnter the name: ");
scanf("%s",st[i].name);
printf("\nEnter the dept: ");
scanf("%s",st[i].dept);
printf("\nEnter the marks: ");
scanf("%d",&st[i].marks);
}
for(i=0;i<n;i++)
{
printf("\nThe roll is: %d",st[i].roll);
printf("\nThe name is: %s",st[i].name);
printf("\nThe dept is: %s",st[i].dept);
printf("\nThe marks is: %d",st[i].marks);
if(st[i].marks>=80)
18
printf("\nGrade is A");
else if(st[i].marks>=70)
printf("\nGrade is B");
else if(st[i].marks>=60)
printf("\nGrade is C");
else if(st[i].marks>=50)
printf("\nGrade is D");
else if(st[i].marks>=40)
printf("\nGrade is D+");
else
printf("\nFail");
}
getch();
}
Functions
Functions are the building block of C and C++. A function groups a number of
program statements into a single unit.
Need for a function
When programs become large, a single list of instructions becomes difficult to
understand. For this reason functions are used. Another reason for using
functions is to reduce the program size. Once a function is created, it can be
used in many places.
A function can be defined the same way a variable is defined. The general form
of function is
return-type function_name( parameter list)
{
//body
}
The program prog20.c will find the square of a number by using a function. Hence
a function to find the square of a number is defined as follows:
int sqr( int x);
Here the function will take an integer value x as parameter and return an
integer type result.
(prog20.c use of function, call by value)
#include<stdio.h>
#include<conio.h>
int sqr( int x);
void main()
{
clrscr();
int n,s;
printf("Enter the value for n: ");
scanf(" %d",&n);
s=sqr(n);
printf("The square of %d is: %d",n,s);
getch();
}
int sqr( int x)
{
19
x=x*x;
return(x);
}
In main function if you take input 3 into variable n, the value of s will be 9.
So it will print 3 for n and 9 for s.
There are two ways that arguments can be passed to a function 1) call by value
and 2) call by reference.
Call by value
This method copies the value of an argument into the formal parameter to the
function. In this case the changes made to the variable in a function does not
change the argument. In program prog20.c the function argument is passed by
value. Here n is an argument and x is a formal parameter.
Call by Reference
You can create a call by reference by passing a reference to an argument.
Reference arguments are indicated by an & (ampersand) preceding the argument. To
modify the program prog20.c to use call by reference an & is used with the
parameter x in program prog21.c.
(prog21.c use of function, call by reference)
#include<stdio.h>
#include<conio.h>
int sqr( int &x);
void main()
{
clrscr();
int n,s;
printf("Enter the value for n: ");
scanf(" %d",&n);
s=sqr(n);
printf("The square of %d is: %d",n,s);
getch();
}
int sqr( int &x)
{
x=x*x;
return(x);
}
If you take 3 as input to variable n, it will pass its address to the function.
So the change in the value will be permanent. So the output of the print
statement will be 9 for n and 9 for s.
Local Variable
Variables that are declared inside a function are called local variables. In
some C/C++ literature, these variables are referred to as automatic variables.
Local variables may be referenced only by statements that are inside the block
in which the variables are declared. In other words, local variables are not
20
known outside their own code block. A block of code begins with an opening curly
brace and terminates with a closing curly brace.
Local variables exist only while the block of code in which they are declared is
executing. That is, a local variable is created upon entry into its block and
destroyed upon exit.
The most common
function.
code
block
in
which
local
variables
are
declared
is
the
For example
void func1(void)
{
int x;
x=10;
}
Global Variable
Global variables are known throughout the program and may be used by any piece
of code. Also, they will hold their value throughout the program’s execution.
You create global variables by declaring them outside of any function. Any
expression may access them, regardless of what block of cose that expression is
in.
In the following program, the variable count has been declared outside of all
the functions.
#include<stdio.h>
int count;
void func1(void);
void func2(void);
int main(void)
{
count =100;
func1();
return 0;
}
void func1(void)
{
int temp;
temp=count;
func2();
printf("Count is %d",count);
}
void func2(void)
{
int count;
for(count=1;count<10;count++)
putchar('.');
21
}
static Variables
static variables are permanent variables within their own function or file.
Unlike global variables, they are not known outside their function or file, but
they maintain their values between calls.
register Variable
The register specifier requested that the compiler keep the value of a variable
in a register of the CPU rather than in memory, where normal variables are
stored. For example
register int temp;
Pointers
A pointer is a variable that holds an address. A pointer variable name should be
preceded by an asterisk (*). The general form of declaring a pointer variable is
type *name;
for example
float *fptr;
where fptr is a float type pointer variable. To access the value of a variable
through a pointer * is used. Pointers can be initialized using the address &
operator with a variable. The program prog22.c uses an integer type pointer
variable ptr. Here ptr is assigned the address of variable x by using address
operator &. So the ptr will point to the same address as x and have the same
value 10. So in the output both the value will be 10. To print the value of the
pointer variable * is used with ptr.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int *ptr,x=10;
ptr=&x;
printf("\nThe value of x is :%d ",x);
printf("\nThe value of *ptr is: %d",*ptr);
printf("\nThe address of ptr is: %P",ptr);
getch();
}
Pointer expressions
The section examines a few special aspects of pointer expressions.
Pointer Assignments
22
As with any variable, you may use a pointer on the right-hand side of an
assignment statement to assign its value to another pointer. For example,
#include <stdio.h>
int main(void)
{int x;
int *p1,*p2;
p1=&x;
p2=p1;
printf("%p",p2);
return 0;
}
Both p1 and p2 now point to x. The address of x is displayed by using the % p
printf().
Pointer arithmetic
There are only two arithmetic operations that you may use on pointers; addition
and subtraction. Let p1 be an integer pointer with a current value of 2000.
Also, assume integers are two bytes long.
After the expression
p1++;
p1 contains 2002. The reason for this is that each time p1 is incremented, it
will point to the next integer. The same is true for decrements. For example,
assuming that p1 has the value 2000, the expression
p1--;
causes p1 to have the value 1998.
#include <stdio.h>
int main(void)
{int x;
int *p1,*p2;
p1=&x;
p2=p1;
printf("%p",p2);
p2++;
printf("\n%p",p2);
return 0;
}
Each time a pointer is incremented, it points to the memory location of the next
element of its base type. Each time it is decremented, it points to the location
of the previous element.
Pointers and Array
There is a close relationship between pointers and arrays.
char str[20], *p1;
p1=str;
Here, p1 has been set to the address of the first element in str. To access the
5th element in str, you could write
23
str[4]
Or
*(p+4)
#include <stdio.h>
int main(void)
{
char str[80],*p1;
p1=str;
printf("Enter any string: ");
scanf("%s",str);
printf("\nstr[4]= %c",str[4]);
printf("\n*(p1+4)= %c",*(p1+4));
return 0;
}
Standard array-indexing notation is sometimes easier
arithmetic can be faster.
to understand, pointer
Arrays of Pointers
Pointers may be arrayed like any other data type. The declaration for an int
piter array of size 5 is
int *x[5];
To assign the address of an integer variable called var to the third element of
pointer array, write
X[2]=&var;
To find the value of var, we write
*x[2]
Another example is shown to resemble pointer with two dimensional array.
#include <stdio.h>
int main(void)
{
int *x[5],var[4][5]=
{{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}}
;
x[0]=var[0];
x[1]=var[1];
printf("*(x[0]+1)=%d",*x[0]);
printf("\n*(x[0]+1)=%d", *(x[0]+1));
printf("\n*(x[1]+1)=%d", *(x[1]+0));
24
return 0;
}
C’s Dynamic Allocation Functions
File I/O
The C I/O system provides a level of abstraction between the programmer and the
device. This abstraction is called a stream and the actual device is called a
file.
Streams
The C file system is designed to work with a wide variety of devices, including
terminals, disk drives, and tape drives. Even though each device is very
different, the buffered file system transforms each into a logical device called
a stream. All streams behave similarly. Because streams are largely device
independent, the same function that can write to a disk file can also be used to
write to another type of device, such as the console. There are two types of
streams: text and binary.
Text Streams
A text stream is a sequence of characters. Standard C allows a text stream to be
organized into lines terminated by a new line character. However, the newline
character is optional on the last line. In a text stream, certain character
translations may occur as required by the host environment.
Binary Streams
A binary stream is a sequence of bytes that have a one-to-one correspondence to
those in the external device- that is, no character translations occur. Also,
the number of bytes written (or read)is the same as the number on the external
device. However, an implementation-defined number of null bytes may be appended
to a binary stream. These null bytes might be used to pad the information so
that it fills a sector on a disk, for example.
Files
In C, A file may be anything from a disk file to a terminal or printer. You
associate a stream with a specific file by performing an open operation. Once a
file is open, information may be exchanged between it and your program.
You disassociate a file from a specific steam with a close operation. If you
close a file opened for output, the contents, if any, of its associated stream
are written to the external device. This process is generally referred to as
flushing the stream, and guarantees that no information is accidentally left in
the disk buffer. All files are closed automatically when your program terminates
normally, either by main() returning to the operating system or by a call to
exit(). Files are not closed when a program terminates abnormally, such as when
it crashes or when it calls abort().
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
25
char ch;
if((fp=fopen("test1.cpp","r"))==NULL){
printf("Error in File name\n");
exit(1);
}
do{
ch=getc(fp);
printf("%c",ch);
}while(ch!=EOF);
fclose(fp);
}
Here is a program that will read two numbers from one file add them and store
the result in another file.
#include <stdio.h>
main()
{
FILE *infile, *outfile;
int num1;
float num2,total;
infile=fopen("juliet.dat", "r");
outfile=fopen("jil.out", "w");
fscanf(infile,"%d%f",&num1,&num2);
total=num1+num2;
fprintf(outfile,"%d plus %3.2f is %3.2f\n",num1,num2,total);
fclose(infile);
fclose(outfile);
}
Here is a program that will read some numbers stored in one file and will store
in another file after sorting.
#include <stdio.h>
#define SIZE 10
main()
{
FILE *infile, *outfile;
int a[SIZE], i, j, temp;
infile=fopen("khalid.cpp", "r");
outfile=fopen("rom.cpp", "w");
for(i=0;i<=SIZE-1;i++)
fscanf(infile, "%d",&a[i]);
fprintf(outfile,"Data items in original order\n");
for(i=0;i<=SIZE-1;i++)
fprintf(outfile, "%4d",a[i]);
for(i=0; i <=SIZE-1; i++)
/* passes*/
for(j=i+1;j<=SIZE-1;j++)
/*one pass*/
if(a[i]>a[j]) {
/*one comparison*/
temp=a[i];
/*one swap*/
a[i]=a[j];
a[j]=temp;
}
26
fprintf(outfile, "\nData items in ascending order\n");
for(i=0;i<=SIZE-1;i++)
fprintf(outfile, "%4d",a[i]);
fprintf(outfile, "\n");
fclose(infile); fclose(outfile);
}
Home task
1. Write a program to find the area of a circle of a given radius.
2. Write a program to find the root of a quadratic equation ax2+ bx +c=0
3. Solve the above problem with various checking options say nonzero a,
imaginary value etc.
4. Write a program to check a number for odd or even.
5. Write a program to check a year for leap year or not. (A year is leap year
if it is divided by 4 and not divided by 100, or it is divided by 400.)
6. Write a program to find the result of xn. ( Where x and n are given integer)
7. Write a program to find and evaluate a series
1+ 3+ 5+7 +
…………
n numbers.
8. Write a program I) Using Array ii) Not Using Array to find the Fibonacci
Series. In a fibonacci series the first two numbers are 1 1. Then each next
number is the summation of previous two numbers. That means the Fibonacci series
is
1
1
2
3
5
8 .. … ….
9. Write a program to evaluate the following Series
1+x/(1!)+ x2/(2!) + x3/(3!) + . . . .
10. Write a program to find the standard deviation of n numbers.
n
S.D =(X-Xi)2
i=1
11. Write a program to reverse an integer number. For example If input is 4536
output will be 6354.
12.Write a program to test a number whether it is prime or not.
13. Write a program to print all prime numbers from 1 to 300.
14. Write a program to test a string whether it is a palindrome or not. A string
is said to be palindrome if it is same from each side. Say for example “madam”.
15. Write a program to sort floating-point numbers in descending order.
16. Write a program to sort some names in ascending order.
27