You are on page 1of 39

Introduction to C

A language is a means of communication. A programming language is a well


defined set of rules for specifying a program sequence of instruction. A
programming language consists of symbols, characters and rules that permits
people to communicate with computers.

C language is one of the most popular language. In the beginning, the


programmer had to learn different languages to create different types of
applications. The problem with low level language is that they are very
difficult for the human to understand and developed. On the other hand,
high level languages are easy for the humans to understand.

Before developing the C language, there was developed the program named
BCPL by Martin Richard in 1966. The full form of BCPL is Basic Combined
Programming Language. He had developed the BCPL program by combining
by various programming languages. Then after, Ken Thompson developed
next program named B. The B language was developed in 1969 by improving
the BCPL language. C is a general purpose programming language. C language
C language has been designed and developed by Dennis Ritchie at
AT & T’s Bell Lab in 1972. The language is associated with UNIX
operating system. The source code for the UNIX operating system is
coded in C.

Features of C
(1) It is highly portable language.
(2) It is structured programming language because the program is
divided into number of functions.
(3)C is faster and efficient high level programming language.
(4) It is extendable program.
(5) C is a flexible language. It permits to write any complex
programs.
(6) It has small size.
Advantages of C language
 It is easy for debugging (correction of error) testing and
maintaining.
 It is portable programming language. This means a program
written for one computer may run successfully on other
computers.
 Adding new features of easier and faster.
 It is easy to learn.
 It is easy to interact with hardware.
 It has both features of high level languages.
Disadvantages of C language
 The program takes more time to design and implement the
software.
 There is no run time checking.
 There is no strict type checking. (For example: we can pass an
integer value for the floating data type).
 It doesn’t support OOP, so to overcome C++ language was
introduced.
Structure of C program
There are three main things to be considered to solve the program. The
input, processes and output. Every programming language follows the set
of rules. A simple C program and its structure is as follows.
(1) #include<stdio.h>
(2) #include<conio.h>
(3) void main()
(4) {
(5) printf(“Welcome in C programming Language”);
(6) printf(“Thank you!”);
(7) getch();
(8) }
On the above structure,
1,2,3,4 In most of simple C program, it is fixed.
5,6 It is used to display text enclosed within “………….”.
7 It is used to hold output screen until you pressed any key from
keyboard.
8 It is the termination of C program.
Compiling Process
Compiler is a program that
transforms all the source code
written in C language into object
code for the execution of that
program. The compiler of the
program begins with saving the
source code with extension .c. This
source code will not understand by
the computer. The next step is to
convert the source code into
machine language (object code).
This task is performed by a
software or program as a compiler.
Every language has its own
compiler that converts the source
code into object code. The
compiler will compile the program
successfully if the source code is
correct, else the object code will
not be produced.
Preprocessor:
Preprocessor is a program that processes the code before it passes
through the compiler. It is often known as a macro processor. It
operates under the control of preprocessor command lines and
directives. Preprocessor directives are placed in the source program
before the main line, before the source code passes through the
compiler. It is examined by the preprocessor for any preprocessor
directives. Preprocessor directives follow the special syntax rule and
begin with the symbol # and do not require any semicolon at the end.
Compiler:
The code which is expanded by the preprocessor is passed to the
compiler. The compiler converts this code into assembly code. Or we
can say that the C compiler converts the pre-processed code into
assembly code.
Assembler:
The assembly code is converted into object code by using an
assembler. The name of the object file generated by the assembler is
the same as the source file.
Linker:
In computing, a linker or link editor is a computer
system program that takes one or more object files (generated by
a compiler or an assembler) and combines them into a single
executable file, library file, or another "object" file.
Header Files:
Header files are standard file of C programming language. It
contains the function definition of library function.
#include<stdio.h>:
It is standard input output header file. It contains the function
definition of input output function such as scanf(), printf() etc.
#include<conio.h>:
It is a header file which is included in the program that is used
to clrscr(), getch() etc. The conio stands for Console Input
Output.
#include<math.h>:
This header file is used for mathematical functions. Such as
pow(), sqrt(), sin(), cos(), (tan) etc.
#include<string.h>:
It is a header file. It contains the function definition of string
processing functions such as strlen(), strcpy() etc.
Fundamental of C
Character Set:
A group of alphabetic, numeric and other characters that have
some relationship with C programming language and recognized
by compiler is called character set. The character set consists the
following:
Alphabets: A to Z and a to z.
Numbers: 0 to 9.
Special Characters:
;, :, {, }, “, /, \, !, @, $, % etc.

Use of Comments:
A comment is an explanation or description of the source code of
the program. It helps a developer to explain logic of the code and
improves program readability. At run-time, a comment is ignored
by the compiler. There are two types of comment in C language.
They are: Line comment and Block comment.
(i) Line Comment:
If we want place only one line of comment somewhere in the program, we
can write comment after double forward slashes (//). This is just one line
comment hence it is called line comment. It doesn’t have ending slash. For
example:
//Makawanpur Multiple Campus

(ii) Block Comment:


If we want to place some blocks of comments in a program, we can write
comment starting by forward slash asterisk (/*) and write multiple lines of
comment and ending with asterisk forward slash (*/). For example:
/*Makawanpur Multiple Campus
Hetauda-2, Makawanpur */

Identifiers:
An identifier is nothing but a name assigned to an element in a program.
Example, name of a variable, function, etc. Identifiers are the user-defined
names consisting of 'C' standard character set. As the name says,
identifiers are used to identify a particular element in a program. Each
identifier must have a unique name. Following rules must be followed for
identifiers:
(i) The first character must be an alphabet or underscore than digits or
alphabets.
(ii) It must consists of letters, digits and underscore
(iii) A keyword cannot be used as an identifier.
(iv) It should not contain any whitespace character.
Keyword:
There are certain words which are reserved by the C compiler. They
have standard predefined meaning in C. These words are known as
keyboard. They can’t be used as identifiers in the program. Keywords
have fixed meanings, and the meaning cannot be changed. They act as
a building block of a 'C' program. There are a total of 32 keywords in
'C'. Keywords are written in lowercase letters.
auto const double float int short struct unsigned

break continue else for long signed switch void

case default enum goto register sizeof typedef volatile

char do extern if return static union while


Token:
Token is the smallest unit in a 'C' program. The compiler breaks a program into the
smallest possible units (tokens) and proceeds to the various stages of the compilation.
A token is divided into six different types, Keywords, Identifiers, Constants, Strings,
Special Characters, and Operators.
Keywords (eg: int, while), Identifiers (eg: main, total), Constants (eg: 10, 20),
Strings (eg: “total”, “hello”), Special symbols (eg: (), {}), Operators (eg: +, /,-,*)
Data Types in C
C language provides us the way to hold any type of data in it. It is called data type. To
store data inside computer, we need to identify the type of data elements. A set of data
that specifies the possible range of values in a program and stored in a memory are
called data type. There are two types of data type. They are as follows:
Primary Data Type:
The fundamental data types are called primary data types. They are also
used to build other data types. The fundamental data types are given in
the following:
Data Types Type Memory Require
void Nothing 0 byte
char Character 1 byte
int Integer 2 bytes
float Floating Point Number 4 bytes
double Large Floating Point Number 8 bytes

Secondary Data Type:


The data type which is constructed by merging some features of
primary data type is called secondary data type. These data type is a
type of regeneration of primary data types. These can hold similar
and dissimilar data on it. The examples of secondary data type are
array, pointer, structure union etc.
Variable:
Variable is the name of memory location. So, the name of memory
location is called variable. Unlike constant, variables are changeable,
we can change value of a variable during execution of a program. A
programmer can choose a meaningful variable name. Example :
average, height, age, total etc. The purpose of variable declaration is
to allocate memory space inside a memory of computer.
(i) It tells the computer what the variable name is.
(ii) It specifies what type of data the variable will hold.
Constant:
A constant is an identifier whose value can not be changed
throughout the program execution whereas the value of variable
keeps changing. A constant value is the one which does not change
during the execution of a program. There are two types of constant
(a) Numeric Constant
(b) Non-numeric / Character Constant.
(a) Numeric Constant:
The constant that stores numeric data only is called numeric constant.
There are two types of numeric constant:
(i) Integer Constant:
The numeric constant that does not contain decimal point is called integer
constant.
(i) Real/Float Constant:
The numeric constant that contains fractional number (having decimal
point) is called real constant.

(b) Character Constant:


There are two types of character constant.
(i) Single Character:
A character constant stores only single character. It is enclosed by single
quotation mark. For example: ‘A’, ‘B’, ‘h’, ‘2’ etc.
(ii) String Constant:
A string constant is a set of characters enclosed in double quotation marks.
The characters in a starting constant sequence may be an alphabet,
number, special characters and blank space. For example: “RAM”, “123”,
“Makawanpur Multiple Camps” etc.
Operator:
An operator is a symbol or sign which helps to perform a certain
mathematical calculation or logical manipulations. It performs an
operation on one or more operands. Operands are values or variables
declare within program. For example 2+4 where + sign is an operator
which indicates addition operation between 2 and 4 operands.
Classification of Operator/Types of Operator
(a) Arithmetic Operator:
An operator that performs mathematical calculation of values or
variable. It can perform simple arithmetic calculations such as
addition, subtraction, multiplication, division and modulation.
Operator Meaning Examples
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (Remainder) a%b
(b) Relational Operator:
It is required to compare the relationship between operands and
bring out the decision accordingly. It is also called comparison
operator because it is used to compare any two expressions. Using
relational operator, we can compare two values or variables in a
program.
Operator Meaning Examples
< is less than a<b
<= is less than or equal to a<=b
> greater than a>b
>= greater than or equal to a>=b
== is equal to a= = b
!= is not equal to a!=b
(c)Logical Operator:
Logical operators are used to give logical value either true or false. Expressions
which involve logical operations are evaluated and found to be one of two state
True or False. If we want to test multiple conditions in the process of making a
decision, we have to perform simple test in separate if statement.
Operator Meaning Examples
&& Logical AND (a<b)&&a>c)
|| Logical OR (a>b)||(a>c)
! Logical NOT !(a= = b)

(d) Assignment Operator:


The assignment operator is used to assign the value of expression into variable. It is
written in the form:
variable=expression
Example: x=a+b Where, x is a variable and a+b is an expression. Here the value of
a+b is evaluated and substituted to the variable x.
(e) Unary Operator/ (Increment/Decrement):
The increment and decrement operators are very useful operators in C language.
They are extensively used in loops. The syntax of the operators are given below:
(1) ++ variable (Pre increment)
(2) Variable ++ (Post increment)
(3) – - variable (Pre decrement)
(4) Variable – - (Post decrement)
The increment operator ++ adds the value 1 to the current value of operands and
the decrement operator – subtracts the value of 1 from the current value of
operand.
(f) Conditional Operator:
Conditional operator is also known as Ternary Operator as it checks condition to
make decision. It uses two symbol: the question mark(?) and the colon(:) but not
together. This is the only operator used in C that takes three operand so it is named
ternary operator.
Syntax:
(Condition)? Statement 1: Statement 2
Example:
A=10
B=15
c=(a>b)?a:b
In this operator, at first condition is checked and if it is found then statement 1 will
be executed otherwise statement 2 is executed.
(g) Comma Operator:
The comma operator is used to separate the pair of expression within
programming statement. The comma operator is represented by using a token.
For example: value= (x=10,y=5, x+y)
(h) The Size of Operator:
The size of operator gives the size of the data type or variable in terms of bytes
occupied in the memory. The operand may be a variable, a constant.
m = sizeof(int)
The size of operator is normally used to determine the lengths of array and
structures when their sizes are not known to the programmer.
Expression:
An expression is a combination of variables, constants and operators written
according to the syntax of C language. In C programming language, every
expression evaluates to a value that is, every expression results in some value
of certain type that can be assigned to a variable.

Algebraic Expression C Expression


axb–c a*b-c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) (a * b/c)
3x2 + 2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c
Input / Output Functions
C doesn’t have any built-in input/output statements as part of its syntax. All input/output
operators are carried out through printf() and scanf() function. There exist several functions
that have more less become standard for input and output operations in C. These functions are
collectively known as the standard I/O library it can take or accept any type of data. Each
program that uses a standard input/output function must contain a statement.
#include<stdio.h> at the beginning. The instruction #include….. tells the compiler to search for
a file named stdio.h and place its contents at this pints in the program. The C language consists
of some I/O functions like getchar(), putchar(), putch(), getche() etc. The printf() and scanf()
are known as formatted I/O functions because they can take any type of format of data form the
I/O devices. Printf() can be used to display some conversion characters along with some
unchanged characters.
Statements:
A smallest executable entity within a program code is called statement.
Statement causes the computer to carry out some actions.
(i) Simple Statement:
A simple statement consists of an expression followed by a semicolon. The
execution of a simple statement causes the expression to be evaluated.
Example:
a=5;
c=d+e;
printf(“Ram”);
(ii) Compound Statement:
A compound statement consists of several individual statements enclosed
in a pair of braces { }. It provides capability for embedding statements
within other statements.
Example:
{
r=5;
area=3.14*r*r;
}
Remember
printf() statement:
It can be used to display some conversion characters along with some
unchanged characters.
scanf() statement:
It can be used to get inputs from the user.
getchar():
The getchar() function is used to read (or accept) a single character.
putchar():
The putchar() function is used to display the character contained in the
variable name at the terminal,
gets():
The gets() function is used to read a string from the standard input and store
in the given variable.
puts():
The puts() function is used to display text in the monitor which is stored in
the variable.
Control Structure/Statement
In C program, statements are executed sequentially in the order
which they appear in the program. But sometimes we may want to use
a condition for executing only a part of program. Also many situations
arise where we may want to execute some statements several times.
Control statements enable us to specify the order in which the various
instructions in the program are executed. This determines the flow of
control. Control statements define how the control is transferred to
other parts of the program. In other word, the control instruction
determine the flow of control in a program. They are:
(i) Sequential Control Statements
(ii) Decision Control Statement
(iii) Looping Control Statement
(iv) Jumping Control Statement
(i) Sequential Control Statement:
Sequence instruction means executing one instruction after another, in order
the source code occurs. This is usually built into the language as a default
action of C. If an instruction is not a control statement then the next
instruction is executed in sequence. This process executes the next statement
in sequence.

Syntax
Start
Statement 1
Statement 2
Statement 3
……………………………..
……………………………..
……………………………..
……………………………..
……………………………..
Statement N
Stop
(ii) Decision Control Statement/Selective Control Structure:
The decision control statements are the decision making statements that
decides the order of execution of statements based on the conditions. In the
decision making statements, the programmer specify which conditions are to
be executed or tested with the statement to be executed if the condition is
true or false. In selective control structure, selection is made on the basis of
condition. We have to options to go when the given condition is true or false.
(1) If Statement:
It is the simplest form of condition statement in which statements are
executed if the test expression (condition) is true. When the condition is false
there is no option to go within this structure. In such situation control must
be out from the structure and statements outside this structure will be
executed.
(2) If else statement:
This is the another form of selective control structure. If condition is true then
if() portion statements are evaluated. Otherwise else part of the statement are
evaluated. This is appropriate where we have to check only one condition. The
benefit of the if() else is only one of the block of statements are evaluated. That
may be if() statement or else statement.

Syntax:
if(condition)
statement 1;
else
statement 2;

In this case, if the


condition is true, then
statement 1 is executed
otherwise statement 2 is
executed.
(3) if-else if statement:
When we have two or more conditions to be checked in a series we can
use if-else if statement. It is also known as multiple condition
statement or multipath statement or if-else ladder.

Syntax:
if(condition 1)
statement 1;
else if( condition 2)
Statement 2;
………………………………
……………………………….
……………………………….
………………………………
else if (condition N1);
statement N1;
else
statement N:
(4) Nested if else statement:
This type of control statement is used to check condition within condition. An
entire if else statement written within the body of if part or else part of
another if else is called nested if else statement. It is used when a condition is
to be checked inside another condition at a time in the same program to make
decision.

Syntax:
If(condition 1)
{
if (condition 2)
statement 1;
else
Statement 2;
}
else
Statement 3;
Switch Case Statement:
The objective of switch case statement is to check several possible constant value for an expression. The
switch case statement of C programming language allows selection and execution of particular block of
statement from several blocks of statement based upon the value of expression which is included within
switch statement and branches accordingly. The expression must be an integral values. The same task can be
performed using if-else ladder as well but as the number of alternatives increases, selection process becomes
more complex. So, the switch case statement body consists of a series of case labels and an optional default
label. The default label can appear only once and anywhere in the body of the switch statement.

Syntax
Switch(expression)
{
Case 1;
Statement 1;
Break;
Case 2;
Statement 2;
Break;
Case 3;
Statement 3;
…..
…..
…..
Case N;
Statement N;
Break;
Default:
{
Statement ;
}
-When the switch statement is executed, the value of expression is compared with
the value of case (constant1, constant 2)
-Then the block of statement associated with the case whose value is matched with
expression will be executed.
-Break statement at the end of each block indicates the end of the particular case
and cases an exit from switch statement and control will be transferred to
statement following the switch.
-If none of the case match with the value of expression, then the block of
statement under default is executed.

Looping Control Statement


Looping is the process of executing the same program statement or block of
program statements repeatedly for specified number of times of till the given
condition is true or satisfied. For example if we want to display “Makwanpur
Multiple Campus” 10 times, one way to get the desired output is – we type
printf(“Makawanpur Multiple Campus”); which is time consuming and hence
not preferable. Another way to perform it is use of loop structure. With loop
structure we don’t need to type the same program statement again and again.
Loop structure is also known as repetitive control structure or interactive
control structure. Mainly there are three types of looping structure.
(i) for loop
(ii) while loop
(iii) do while loop
Example: without using loop Example: using loop

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
printf(\nMakawanpur Multiple Campus”); int i;
printf(\nMakawanpur Multiple Campus”); for(i=1;i<=10;i++)
printf(\nMakawanpur Multiple Campus”); {
printf(\nMakawanpur Multiple Campus”); printf(\nMakawanpur Multiple Campus”);
printf(\nMakawanpur Multiple Campus”); }
printf(\nMakawanpur Multiple Campus”); getch();
printf(\nMakawanpur Multiple Campus”); }
printf(\nMakawanpur Multiple Campus”);
printf(\nMakawanpur Multiple Campus”);
printf(\nMakawanpur Multiple Campus”);
getch();
}

The above both programs give the same output i.e. after running these programs,
you will see the name of “Makawanpur Multiple Campus” 10 times on the screen.
You can imagine if the number of times for repetition increase from 10 to 20 or 50 or
100 or even more, then which method do you find short and efficient?
for loop:
It is the most common type of loop which is used to execute program statement or
block of program statements repeatedly for specified number of time. Mainly it consists
three expressions. initialization, condition and increment/decrement. The initialization
defines the loop starting point, condition defines the loop stopping points and counter
helps to increment/decrement the value of counter variable.
Syntax:
for(initialization;condition;increment/decrement)
{
statements to be executed repeatedly;
}
(ii) while loop:
The while loop executes the program repeatedly until the given condition is
true. It checks condition at first; if it is found true then it executes the
statements written in its body part otherwise it just gets out the loop
structure.

Syntax:
Initialization;
while(condition)
{
Statement;
Increment/decrement;
}

Where, initialization means starting


point, condition means stopping
point and increment/decrement
means counter.
do while loop:
The do while loop is an exit control loop. This loop runs at least
once even though the termination condition is set to false. This
loop test the condition at exit point hence it is called exit control
loop. The syntax of the loop is as follows:

Syntax:
Initialization
do
{
Statements
……………………
…………………..
increment/decrement
}while(termination condition);
Array and String
Array:
An array is a collection of similar type of data items treated as single unit. It
acts to store related data under the same name with an index, also known as
a subscript, which helps to access individual array element. Array data type
may be int, float, char etc. depending upon the nature of problems. In other
word, array is the collection of similar elements. These similar elements
could be all integers, or all floats or all characters etc. All elements of any
given array must be of the same type i.e. we can’t have an array of 10
numbers, of which 5 are integers and 5 are floats.
Characteristics of Array
 All the array elements share the common name.
 The elements of array stored in contiguous memory locations
 By declaring or using array, person becomes short and simple which
handles large volume of similar type of data items.
 We put the array size of fixed length as required that means once the size
is declared then the size bill be fixed at the execution time of the
program.
Advantages of Array
 It is easier for handling similar types of data in a program.
 It is efficient for solving problem like sorting, searching,
indexing etc.
 It saves memory
 It is very close to matrix, therefore it is easy for solving matrix
related problem.

Disadvantages of Array
 It is not possible to hold dissimilar type of data in an array.
 It is difficult to visualize the multidimensional array.
 It is static in nature so it is difficult to define the size of array
during running time.
Write a program to input the salary of 10 employees and print them without
using array.
#include<stdio.h>
#include<conio.h>
void main()
{
float s1,s2,s3,s4,s5,s6,s7,s8,s9,s10;
clrscr();
printf(“\nEnter the salaries of 10 employees: “);
scanf(“%f%f%f%f%f%f%f%f%f%f”,&s1,&s2,&s3,&s4,&s5,&s6,&s7,&s8,&s9,&s10);
printf(“\nThe salaries are:”);
printf*(“\nRs.%f”,s1);
printf*(“\nRs.%f”,s2);
printf*(“\nRs.%f”,s3);
printf*(“\nRs.%f”,s4);
printf*(“\nRs.%f”,s5);
printf*(“\nRs.%f”,s6);
printf*(“\nRs.%f”,s7);
printf*(“\nRs.%f”,s8);
printf*(“\nRs.%f”,s9);
printf*(“\nRs.%f”,s10);
getch();
Write a program to input the salary of 10 employees and print them without using
array.
#include<stdio.h>
#include<conio.h>
void main()
{
float s[10];
int i;
printf(“\nEnter the salaries of 10 employees: “);
for(i=0;i<10;i++)
{
scanf(“%f”,&s[i]);
}
Printf(“\nThe salaries are as follows: “);
for(i=0;i<10;i++)
{
printf(“\nRs.%f,s[i]);
}
getch();
}
Types of Array:
(1) One Dimensional Array:
An array which has only one subscript is named as one dimensional array, a
subscript is a number of large bracket in which we put the size of the array.

(2) Multi Dimensional Array:


An array which has more than one subscript is named as multidimensional
array.

You might also like