Programming in C'
Programming in C'
Programming in ‘C’
PROGRAM DEVELOPMENT TOOLS
1.1 Algorithm
Oval Terminal
Document Printout
Rectangle Process
Diamond Decision
Circle Connector
Arrow Flow
Limitations of flowcharts
1. Flowcharts are difficult to modify. Re-drawing of flowchart may be necessary
2. Translation of flowchart into computer program is always not easy
Start
Read N
Count = 0
Sum = 0
Avg = 0
Sum = Sum + a
Count = Count+1
True
Count<=
n
?
False
Avg = sum / n
Print
avg.
Stop
C has five types of primary constants. They are integer, float, char, logical and
string. The numeric constants can be preceded by a minus sign if needed.
Rules for constructing Integer constants
Escape sequence
Some non-printing characters and some other characters such as double quote (“),
single quote (‘), question mark (?) and backslash (\), require an escape sequence. A list of
commonly used backslash character constants is given below.
Escape Escape
Meaning ASCII value Meaning ASCII value
Sequence Sequence
\a Bell 7 \r Carriage return 13
\b Back Space 8 \” Double Quote 34
\t Tab 9 \’ Single Quote 39
\n New line 10 \? Question Mark 63
\v Vertical tab 11 \\ Back Slash 92
\f Form feed 12 \0 Null 0
Variables
A variable can be considered as a name given to the location in memory. The
term variable is used to denote any value that is referred to a name instead of explicit
value. A variable is able to hold different values during execution of a program, where as
a constant is restricted to just one value.
For example, in the equation 2x + 3y = 10; since x and y can change, they are
variables, whereas 2,3 and 10 cannot change, hence they are constants. The total
equation is known as expression.
Rules for constructing variable names
(a) The name of a variable is composed of one to several characters, the first of
which must be a letter
(b) No special characters other than letters, digits, and underscore can be used in
variable name. Some compilers permit underscore as the first character.
(c) Commas or Blanks are not allowed with in a variable name.
(d) Upper case and Lower case letters are significant. That is the variable income is
not same as INCOME.
(e) The variable name should not be a C key word. Also it should not have the same
name as a function that is written either by user or already exist in the C library.
The following are valid variable names:
Bitwise operators
C supports a set of bitwise operations. The lowest logical element in the memory
is bit. C allows the programmer to interact directly with the hardware of a particular
system through bitwise operators and expression. These operators work only with int
and char datatypes and cannot be used with float and double type.
The following table shows the bitwise operators that are available in C.
Operator Meaning
- One’s Complement
| Bitwise OR
& Bitwise AND
^ Bitwise Exclusive OR (XOR)
>> Right Shift
<< Left Shift
Increment & Decrement operators
C has two very useful operators for adding and subtracting a variable. These are
the increment and decrement operators, ++ and --
These two operators are unary operators. The increment operator ++ adds 1 to its
operand, and the decrement operator -- subtracts 1 from its operand. Therefore, the
following are equivalent operations.
++i; is equivalent to i = i + 1;
--i; is equivalent to i = i – 1;
These operators are very useful in loops.
Assignment operators
In addition to usual assignment operator =, C has a set of shorthand operators, that
simplifies the coding of a certain type of assignment statement. It is of the form
var op = exp
where var is a variable, op is a C binary arithmetic operator and exp is an
expression.
The operator += means add the expression on the right to the variable on the left
and the operator -= means subtract the expression on the right from the variable on the
left.
Compile Source
C Compiler Program
Synta
x
Errors
?
Logic and
Data
Errors?
CORRECT OUTPUT
Stop
PROGRAMS
Prog.1: To print a message on the screen.
/* Printing a message on the screen */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“This is my First Program in C ”);
getch();
}
Output
This is my First Program in C
Prog.2: To print our Institute Name.
/* Printing our institute name */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Welcome to Millennium Software Solutions”);
getch();
}
Output
Welcome to Millennium Software Solutions
Prog.3: To Display Multiple Statements.
/* Printing our Institute Address*/
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“Millennium Software Solutions”);
-x-
/* Even or Odd */
#include<stdio.h>
#include<conio.h>
void main( )
{
int n;
clrscr( );
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n%2==0)
printf(“It is Even number”);
if(n%2!=0)
printf(“It is Odd number”);
getch( );
}
Output 1
Enter a number:4
It is Even number
Output 2
Enter a number:5
It is Odd number
Note that there is no semicolon between the condition and the statement i.e., no
semicolon following if(n%2==0).
It is important to note that, if the condition is false the statement is skipped and
control goes to the next statement immediately after if statement.
2.3 The if-else Statement
The general form of if-else statement is…
PROGRAMS
Conditional Operators (?:)
Prog.21: To check whether the year is leap or not
/* Inputting year is Leap or not */
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf(“Enter year:”);
scanf(“%d”,&year);
(year%4==0)?printf(“Leap year”):printf(“Not leap year”);
getch();
}
Output 1
Enter a char:a
Vowel
Output 2
Enter a char:b
Consonant
Output 3
Enter a char:U
Vowel
Prog.43: To print words corresponding numbers below 9
/* Numbers -> words (0-9)*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number(0-9):”);
scanf(“%d”,&n);
switch(n)
{
case 0:printf(“Zero”);
break;
case 1:printf(“One”);
break;
case 2:printf(“Two”);
break;
case 3:printf(“Three”);
break;
case 4:printf(“Four”);
break;
case 5:printf(“Five”);
break;
case 6:printf(“Six”);
-x-
3. LOOPS
3.1 Def: A portion of program that is executed repeatedly is called a loop.
The C programming language contains three different program statements for program
looping. They are
1. For loop
2. While loop
3. Do-While loop
3.2 The For Loop
The for loop is most common in major programming languages. However, the
for loop in languages is very flexible and very powerful. Generally, the for loop is used
to repeat the execution statement for some fixed number of times.
The general form of for loop is
for(initialization;condition;increment/decrement)
statement;
where the statement is single or compound statement.
initialization is the initialization expression, usually an assignment to the loop-
control variable. This is performed once before the loop actually begins execution.
condition is the test expression, which evaluated before each iteration of the loop,
which determines when the loop will exist.
increment is the modifier expression, which changes the value of loop control
variable. This expression is executed at the end of each loop.
Semi colons separate these three sections.
/* *
* *
* * *
* * * *
* * * * * */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“* ”);
}
printf(“\n”);
}
getch();
}
Output
*
* *
* * *
* * * *
* * * * *
Prog.66: To print the following format
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
/* 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5 */
/* 1
2 2
3 3 3
4 4 4 4
5 5 5 5 5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,i);
}
printf(“\n”);
}
/* 5 5 5 5 5
4 4 4 4
3 3 3
2 2
1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,i);
}
printf(“\n”);
}
getch();
}
Output
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
/* 1 2 3 4 5
1 2 3 4
1 2 3
1 2
1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Prog.70: To print the following format
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
/* 1 1 1 1 1
2 2 2 2
3 3 3
4 4
5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
/* 5 4 3 2 1
5 4 3 2
5 4 3
5 4
5 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
5 4 3 2 1
5 4 3 2
/* 5
5 4
5 4 3
5 4 3 2
5 4 3 2 1 */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=5;j>=i;j--)
{
printf(“%d ”,j);
}
printf(“\n”);
}
getch();
}
Output
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
Prog.73: To print the following format
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
/* 5
4 4
3 3 3
2 2 2 2
While Loop
Prog.74 : To print the message 10 times.
/* Print a message 10 times */
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
printf(“\nMillennium Software Solutions”);
i++;
}
getch();
}
Output
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
Millennium Software Solutions
do-while Loop:
Note: Do all above programs using do-while loop syntax.
Syn: initialization;
do
{
statements;
incre / decre;
}while(condition);
4. ARRAYS
4.1 Def: An Array is a collection of same data type. The elements of an array are
referred by a common name and are differentiate from one another by their position with
in an array. The elements of an array can be of any data type but all elements in an array
must be of the same type.
The general form of declaring a array is
type array_name[size];
where type is a valid datatype, array_name is the name of the array and size is the
number of elements that array_name contains.
Example:
int A[100],marks[20];
float rates[50];
char name[30];
int A[100];
here int data type of elements that an array
A name of array
100 size of an array
The individual elements of an array can be referenced by means of its subscript (or
index)
Suppose A is an array of 20 elements, we can reference each element as
1. The size of an array can be omitted in the declaration. If the size is omitted, then
the compiler will reserve the memory location corresponds to number of
individual elements that includes in the declaration.
2. If the array elements are not given any specific values, they are supposed to
contain garbage values.
3. C will not allow to specify repetition of an initialization, or to initialize an ]
element in the middle of an array without supplying all the preceding values.
The following program illustrates the Initialization of array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5] = {4,3,2,1,5},i;
Note that, when initialize a character array by listing its elements, we must explicitly
specify the null terminator. When a character string is assigned to a character array, C
adds the null character at the end of string automatically.
A two-dimensional array can be initialized to a list of strings. For example,
char day[7][15] = { “Monday”,
“Tuesday”,
“Wednesday”,
“Thursday”,
“Friday”,
“Saturday”,
“Sunday”
};
Reading and writing strings
The scanf(), printf() function is used with %s with format specification to read
and print a string.
Main Program
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
register int count;
int sum;
clrscr();
for(count=0;count<10;count++)
sum = sum + count;
printf(“The sum is:%d”,sum);
getch();
}
3. Extern: This is the default storage class for all global variables. Extern storage
class variables get initialized (to zero in the case of integers) automatically, retain
their value throughout the execution of the program and can be shared by
different modules of the same program. However, assuming “int intvar;”is
present in a.c., to be also to have proper binding with the same variable, b.c
(another file) should have “extern int intvar”.
Example:
a.c file b.c file
#include<stdio.h> float f = 84.237;
#include<conio.h> extern int intvar;
int intvar; funct(char c, int intvar)
extern float f; {
void main() char c1,c2;
{ :
char ch; :
funct(ch,intvar); }
Example:
Program: STRUCTURE AS FUNCTION PARAMETERS
#include<stdio.h>
#include<conio.h>
struct stores
{
char name[20];
float price;
int quantity;
};
struct stores update(struct stores,float,int);
float mul(struct stores);
void main()
{
float p_increment, value;
int q_increment;
static struct stores item={“XYZ”,25.75,12};
clrscr();
printf(“\nInput increment values:”) ;
printf(“price increment and quantity increment\n”);
scanf(“%f%d”,&p_increment,&q_increment);
item = update(item,p_increment,q_increment);
printf(“\nUpdate values of item”);
printf(“\n\nName:%s”,item.name);
printf(“\nPrice:%.2f”,item.price);
printf(“\nQuantity:%d”,item.quantity);
value = mul(item);
printf(“\nValue of the item=%.2f”,value);
getch();
}
struct stores update(struct stores product, float p, int q)
{
product.price+=p;
product.quantity+=q;
return(product);
}
float mul(struct stores stock)
7.8 UNIONS
Unions are a concept borrowed from structures and therefore follow the same syntax as
structures. However, there is major distinction between them in terms of storage. In
structures, each member has its own storage location, whereas all the members of a union
use the same location. This implies that, although a union may contain many members of
different types, it can handle only one member at a time. Like structures, a union can be
declared using the keyword union as follows:
union item
{
int m;
float x;
char c;
}code;
8. Pointers
8.1 INTRODUCTION Pointers are another important feature of C language. They are a
powerful tool and handy to use once they are mastered. There are a number of reasons
for using pointers.
1. A pointer enables us to access a variable that is defined outside the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
5. The use of a pointer array to character strings results in saving of data storage
space in memory.
8.2 ACCESSING THE ADDRESS OF A VARIABLE
The actual location of a variable in the memory is system dependent and therefore, the
address of a variable is not known to us immediately. We can determine the address of
the variable with the help of the operator & in C. We have already seen the use of this
address operator in the scanf function. The operator & immediately preceding a variable
returns the address of the variable associated with it. For example,
p = &quantity;
would assign the address to the variable p. The & operator can be remembered as
‘address of’.
Example: Accessing Addresses of variables
#include<stdio.h>
#include<conio.h>
9. File Management in C
9.1 INTRODUCTION
A file is a place on the disk where a group of related data is stored. Like most other
languages, C supports a number of functions that have the ability to perform basic file
operations, which include:
Naming a file,
Opening a file,
Reading data from a file,
Writing data to a file, and
Closing a file.
High level I/O functions
Function Name Operation
fopen() Creates a new file for use
Opens an existing file for use.
fclose() Closes a file which has been opened for use.
Getc() Reads a character from a file.
putc() Writes a character to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to file.
fseek() Sets the position to a desired point in the file
Ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file.
The first statement declares the variable fp as a “pointer to the data type FILE”. As
stated earlier, FILE is a structure that is defined in the I/O library. The second statement
opens the file named filename and assigns as identifier to the FILE the pointer fp. This
pointer which contains all the information about the file is subsequently used as a
communication link between the system and the program.
The second statement also specifies the purpose of opening this file. The mode
does this job. Mode can be one of the following:
r open the file for reading only.
w open the file for writing only.
a open the file for appending (or adding) data to it.
Note that both the filename and mode are specified as strings. They should be enclosed
in double quotation marks.
When trying to open a file, one of the following things may happen:
1. When the mode is ‘writing’ a file with the specified name is created if the file
does not exist. The contents are deleted, if the file already exists.
2. When the purpose is ‘appending’, the file is opened with the current contents safe.
A file with the specified name is created if the file does not exist.
3. If the purpose is ‘reading’, and if it exists, then the file is opened with the current
contents safe; otherwise an error occurs.
Consider the following statements:
FILE *p1, *p2;
p1 = fopen(“data”,”r”);
printf("Contents of %s file\n\n",argv[1]);
fp=fopen(argv[1],"r");
for(i=2;i<argc;i++)
{
fscanf(fp,"%s",word);
printf("%s",word);
}
fclose(fp);
printf("\n\n");
for(i=0;i<argc;i++)
printf("%*s\n",i*5,argv[i]);
getch();
}