Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 45

PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

INTRODUCTION TO C PROGRAMMING

OVERVIEW OF C
 C language was developed by Dennis Ritchie in 1972 at
Bell Laboratories.
 In 1989, the C language was standardized, where C
language features were defined, also known as the 1989
ANSI standard for C, and that is the reason, you will see C
language also called C89, because of the 1989 ANSI
standard.
 The current latest version of the C language is C99, as some
new features were added to the C language in 1999.

You must be thinking, 1999 was more than 20 years ago, but
the C language is still very relevant and widely used although
there are many other new languages like C++, Java, Python, C#,
etc. in the market.

C Language is a middle-level, structured programming


language, that needs a compiler for running the programs
written in C language. It is a high-level independent language.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Features of C
 C language is a robust language whose rich set of
built-in functions & operators.
 C compiler combines the capabilities of an assembly
language with the features of high-level language.
 Well suited for writing both system-software and
business packages.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 Programs written in c are efficient & fast. Due to


variety of datatypes & powerful operator.
 Several standard functions are available. C highly
portable. C programs written for one computer can be
run on another with little or no modification
 The modular structure makes program debugging,
testing, maintenance easier.
 Feature of c is ability to extend itself. C program is
basically collection of functions that are supported by
the c library.

STRUCTURE OF C PROGRAM WITH EXAMPLES

Documentation section (comments)/*---------*/


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Linkage section
Definition section
Global declaration section
Main( )
{
Declaration part;
Executable part;
}
Sub-program section

Documentation Section
 The documentation section is the part of the program where
the programmer gives the details associated with the
program.

 He usually gives the name of the program, the details of the


author and other details like the time of coding and
description. It gives anyone reading the code the overview of
the code.

Example
/**
* File Name: Helloworld.c
* Author: Manthan Naik
* date: 09/08/2019
* description: a program to display hello world
*              no input needed
*/

Link Section
This part of the code is used to declare all the header files that
will be used in the program. This leads to the compiler being told
to link the header files to the system libraries.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Example

#include<stdio.h>

Moving on to the next bit of this basic structure of a C program article,

Definition Section
In this section, we define different constants. The keyword define is used in
this part.

#define PI=3.14

Global Declaration Section


This part of the code is the part where the global variables are declared. All
the global variable used are declared in this part. The user-defined functions
are also declared in this part of the code.

float area(float r);

int a=7;

Main Function Section


Every C-programs needs to have the main function. Each main function
contains 2 parts. A declaration part and an Execution part. The declaration
part is the part where all the variables are declared. The execution part
begins with the curly brackets and ends with the curly close bracket. Both
the declaration and execution part are inside the curly braces.

int main(void)

int a=10;

printf(" %d", a);

return 0;

Sub Program Section


All the user-defined functions are defined in this section of the program.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

int add(int a, int b)

return a+b;

Sample C program

*File Name: areaofcircle.c

* Author: vidya

* date: 09/08/2019

* description: a program to calculate area of circle

*user enters the radius

**/

#include<stdio.h>//link section

#define pi 3.14;//defination section

float area(float r);//global declaration

int main()//main function

float r;

printf(" Enter the radius:n");

scanf("%f",&r);

printf("the area is: %f",area(r));

return 0;

float area(float r)

return pi * r * r;//sub program

}
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Creating and executing of C program


 Generally, the programs created using programming languages like C,
C++, Java, etc., are written using a high-level language like English.

 But, the computer cannot understand the high-level language. It can


understand only low-level language.

 So, the program written in the high-level language needs to be converted


into the low-level language to make it understandable for the computer.
This conversion is performed using either Interpreter or Compiler .

return a

Step 1: Creating a Source Code


}

Source code is a file with C programming instructions in a high-level language.


To create source code, we use any text editor to write the program instructions.
The instructions written in the source code must follow the C programming
language rules. The following steps are used to create a source code file in
Windows OS…

 Click on the Start button
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 Select Run
 Type cmd and press Enter
 Type cd c:\TC\bin in the command prompt and press Enter
 Type TC press Enter
 Click on File -> New in C Editor window
 Type the program
 Save it as FileName.c (Use shortcut key F2 to save)

Step 2: Compile Source Code (Alt + F9)


 The compilation is the process of converting high-level language instructions
into low-level language instructions. We use the shortcut key Alt + F9 to
compile a C program in Turbo C.
 Whenever we press Alt + F9, the source file is going to be submitted to the
Compiler. On receiving a source file, the compiler first checks for the Errors.
If there are any Errors then compiler returns List of Errors, if there are no
errors then the source code is converted into object code and stores it
as a file with .obj extension. Then the object code is given to the Linker.
The Linker combines both the object code and specified header file code
and generates an Executable file with a .exe extension.

Step 4: Check Result (Alt + F5)


After running the program, the result is placed into User Screen. Just
We need to open the User Screen to check the result of the program execution.
We use the shortcut key Alt + F5 to open the User Screen and check the result.

Execution Process of a C Program


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

The file which contains c program instructions in a high-level language is said


to be source code. Every c program source file is saved with .c extension,
for example, Sample.c.

Whenever we press Alt + F9 the source file is submitted to the compiler.


Compiler checks for the errors, if there are any errors, it returns a list of errors,

otherwise generates object code in a file with name Sample.obj and submit it to

the linker. The linker combines the code from specified header file into an object

file and generates executable file as Sample.exe. With this compilation process

completes.

Now, we need to run the executable file (Sample.exe). To run a program we

press Ctrl + F9. When we press Ctrl + F9 the executable file is submitted to the
CPU. Then CPU performs the task according to the instructions written in
that program and place the result into UserScreen.

Then we press Alt + F5 to open UserScreen and check the result of the program.

Important Points
C program file (Source file) must save with .c extension.

The compiler converts complete program at a time from high-level


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

language to low-level language.

Input to the compiler is .c file and output from the compiler is .exe file,

but it also generates .obj file in this process.

The compiler converts the file only if there are no errors in the source code.

CPU places the result in User Screen window.

Overall Process
 Type the program in C editor and save with .c extension (Press F2 to save).
 Press Alt + F9 to compile the program.
 If there are errors, correct the errors and recompile the program.
 If there are no errors, then press Ctrl + F9 to execute/run the program.
 Press Alt + F5 to open User Screen and check the result.

C Character Set
As every language contains a set of characters used to construct words,
statements, etc., C language also has a set of characters which
include alphabets, digits, and special symbols. C language supports a
total of 256 characters.

Every C program contains statements. These statements are constructed


using words and these words are constructed using characters from C
character set. C language character set contains the following set of
characters...

1. Alphabets

2. Digits

3. Special Symbols
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Alphabets
C language supports all the alphabets from the English language. Lower and

upper case letters together support 52 alphabets.

LOWER CASE LETTERS - a to z

UPPER CASE LETTERS - A to Z

Digits
C language supports 10 digits which are used to construct numerical values

in C language.

Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols
C language supports a rich set of special symbols that include symbols to

perform mathematical operations, to check conditions, white spaces,

backspaces, and other special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline

space NULL bell backspace verticaltab etc.,

C program to print all the characters of C character Set


#include<stdio.h>
#include<conio.h>
int main()
{
int i;
clrscr();
printf("ASCII ==> Character\n");
for(i = -128; i <= 127; i++)
printf("%d ==> %c\n", i, i);
getch();
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

return 0;
}

Tokens in C
Tokens in C is the most important element to be used in creating a program
in C. We can define the token as the smallest individual element in C. For
`example, we cannot create a sentence without using words; similarly, we
cannot create a program in C without using tokens in C. Therefore, we can
say that tokens in C is the building block or the basic component for
creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories :

o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C

Keywords in C
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Keywords in C can be defined as the pre-defined or the reserved

words having its own importance, and each keyword has its own

functionality. Since keywords are the pre-defined words used by the

compiler, so they cannot be used as the variable names. If the keywords are

used as the variable names, it means that we are assigning a different

meaning to the keyword, which is not allowed. C language supports 32

keywords given below:

Auto Double int struct

Break Else long switch

Case Enum register typedef

Char Extern return union

Const Float short unsigned

Continue For signed void

Default Goto sizeof volatile

Do If static while

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures,


etc. Identifiers in C are the user-defined words. It can be composed of
uppercase letters, lowercase letters, underscore, or digits, but the starting
letter should be either an underscore or an alphabet. Identifiers cannot be
used as keywords. Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an


underscore, and then it can be followed by any of the character, digit,
or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

o Commas or blank spaces cannot be specified within an identifier.


o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful,
short, and easy to read.

Variables in C
A variable is a name of the memory location. It is used to store data. Its
value can be changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be


easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;  

The example of declaring the variable is given below:

1. int a;  
2. float b;  
3. char c;  

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20;//declaring 2 variable of integer type  
2. float f=20.8;  
3. char c='A';  

Rules for defining variables


o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It
can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int,
float, etc.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Valid variable names:

1. int a;  
2. int _ab;  
3. int a30;  

Invalid variable names:

1. int 2;  
2. int a b;  
3. int long;  

Types of Variables in C
There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

1. Local Variable
A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1( )
{  
int x=10;//local variable  
}  

You must have to initialize the local variable before it is used.


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Global Variable
A variable that is declared outside the function or block is called a global
variable. Any function can change the value of the global variable. It is
available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable  
void function1( )
{  
int x=10;//local variable  
}  

Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1( )
{  
int x=10;//local variable  
static int y=10;//static variable  
x=x+1;  
y=y+1;  
printf("%d,%d",x,y);  
}  

If you call this function many times, the local variable will print the
same value for each function call, e.g, 11,11,11 and so on. But the static
variable will print the incremented value in each function call, e.g. 11,
12, 13 and so on.

Automatic Variable
All variables in C that are declared inside the block, are automatic variables
by default. We can explicitly declare an automatic variable using auto
keyword.

void main( )
{  
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

int x=10;//local variable (also automatic)  
auto int y=20;//automatic variable  
}  

External Variable
We can share a variable in multiple C source files by using an external
variable. To declare an external variable, you need to use extern keyword.

myfile.h

extern int x=10;//external variable (also global)  
program1.c
#include "myfile.h"  
#include <stdio.h>  
void printValue( )
{  
    printf("Global variable: %d", global_variable);  
}  

DATA TYPES
Data used in c program is classified into different types based on its
properties. In the C programming language, a data type can be defined as a
set of values with similar characteristics. All the values in a data type have
the same properties.

Data types in the c programming language are used to specify what kind
of value can be stored in a variable.

The memory size and type of the value of a variable are determined by the
variable data type.

In a c program, each variable or constant or array must have a data type
and this data type specifies how much memory is to be allocated and what
type of values are to be stored in that variable or constant or array. The
formal definition of a data type is as follows...
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

In the c programming language, data types are classified as follows...

1. Primary data types (Basic data types OR Predefined data types)


2. Derived data types (Secondary data types OR User-defined data
types)
3. Enumeration data types
4. Void data type

Primary data types


The primary data types in the C programming language are the basic data

types. All the primary data types are already defined in the system. Primary

data types are also called as Built-In data types.

The following are the primary data types in c programming language...

1. Integer data type

2. Floating Point data type

3. Double data type


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

4. Character data type

Integer Data type

The integer data type is a set of whole numbers. Every integer value does not

have the decimal value. We use the keyword "int" to represent integer data

type in c. We use the keyword int to declare the variables and to specify the

return type of a function. The integer data type is used with different type

modifiers like short, long, signed and unsigned. The following table provides

complete details about the integer data type.


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Floating Point data types

Floating-point data types are a set of numbers with the decimal value. Every

floating-point value must contain the decimal value.

The floating-point data type has two variants...

 float

 double

We use the keyword "float" to represent floating-point data type and

"double" to represent double data type in c. Both float and double are

similar but they differ in the number of decimal places. The float value

contains 6 decimal places whereas double value contains 15 or 19 decimal

places. The following table provides complete details about floating-point

data types.

Character data type

The character data type is a set of characters enclosed in single quotations.

The following table provides complete details about the character data type.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

The following table provides complete information about all the data types in

c programming language...

void data type


The void data type means nothing or no value. Generally, the void is used to

specify a function which does not return any value. We also use the void

data type to specify empty parameters of a function.


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Enumerated data type


An enumerated data type is a user-defined data type that consists of integer

constants and each integer constant is given a name. The keyword "enum"

is used to define the enumerated data type.

Derived data types


Derived data types are user-defined data types. The derived data types are

also called as user-defined data types or secondary data types. In the c

programming language, the derived data types are created using the

following concepts...

 Arrays

 Structures

 Unions

 Enumeration

Constants in C
A constant is similar to the variable but the constant hold only one value
during the program execution. That means, once a value is assigned to the
constant, that value can't be changed during the program execution. Once
the value is assigned to the constant, it is fixed throughout the program. A
constant can be defined as follows...

A constant is a named memory location which holds only one value throughout the
program execution.

 A constant can be of any data type like integer, floating-point,

character, string and double, etc.,


 Constants are also called as literals.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 It is considered best practice to define constants using only

upper-case names.

Syntax:

Const type const-name;

Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal
integer. A decimal integer value is specified as direct integer value whereas
octal integer value is prefixed with 'o' and hexadecimal value is prefixed with
'OX'.
An integer constant can also be unsigned type of integer constant or long
type of integer constant. Unsigned integer constant value is suffixed with 'u'
and long integer constant value is suffixed with 'l' whereas unsigned long
integer constant value is suffixed with 'ul'.

Example
125 ----->Decimal Integer Constant
O76----->Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant

Floating Point constants


A floating-point constant must contain both integer and decimal parts.
Some times it may also contain the exponent part. When a floating-point
constant is represented in exponent form, the value must be suffixed with 'e'
or 'E'.

Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Character Constants
A character constant is a symbol enclosed in single quotation. A character
constant has a maximum length of one character.
‘8’ is not as same as 8. Character constants have a specific set of integer
values known as ASCII (American standard code for information
interchange).

Example: 'A' , '2' , ‘;’


String Constants
A string constant is a collection of characters, digits, special symbols and
escape sequences that are enclosed in double quotations.

We define string constant in a single line as follows...


"This is firstyear BCA class"

Creating constants in C
In a c programming language, constants can be created using
two concepts...

1. Using the const keyword


2. Using #define preprocessor

Using the 'const' keyword


We create a constant of any datatype using 'const' keyword. To
create a constant, we prefix the variable declaration with 'const'
keyword.
The general syntax for creating constant using 'const' keyword is
as follows...

const datatype constantName ;


OR
const datatype constantName = value ;
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Example
const int x = 10 ;
Here, 'x' is a integer constant with fixed value 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}

Using '#define' preprocessor


We can also create constants using '#define' pre-processor
directive. When we create constant using this pre-processor
directive it must be defined at the beginning of the program
(because all the pre-processor directives must be written before
the global declaration.
We use the following syntax to create constant using '#define'
pre-processor directive...

#define CONSTANTNAME value


#include<stdio.h>
#include<conio.h>
#defien PI 3.14
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

void main( )
{
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}

Declaration and Initialization of varaibles

 Declaration of variable in c can be done using following


syntax:
Datatype variablename;
Or
Datatype variable1, variable2,………….. variable-n;
Where datatype is any valid c datatype and variable-name is
any valid identifier.
Ex:
int a ;
flaot var;
double x;

Initialization of variable
C variables declared can be initialized with the help of
assignment operator ‘=’;
Syntax
Datatype variable-name = const/literal/expression
Ex:
int a=10,b=20;
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

int c=a+b;

#include<stdio.h>
void main( )
{
int age;
age=20;
printf(“%d”,age);
}
Points to remember:
 Variables should be declared in the c program before
use.
 Memory space is not allocated for a variable while
declaration. It happens only on the variable definition.
 Variable initialization means assigning a value to the
variable.

Symbolic constants
 Symbolic constant is the name that subsitutes for a
sequence of characters or a numeric constant, a character
constant or a string constant.

 When a program is compiled each occurrence of a symbolic


constant is replaced by its corresponding character
sequence.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Syntax :
#define name text
Ex:
#define MAX 50
#define TRUE 1
#define FALSE 0
#define SIZE 15
 A pre-processor is a system program, which comes into
action prior to compiler and it replaces the
replacement of text by the actual text

Advantages of Symbolic constant

 they can be used to assign names to value.


 Replacement of value has to be done at one place and
wherever the name appears in the text it gets the value
by execution of the pre-processor.
 Saves time . If the symbolic constant appears 20 times
in the program, it needs to be changed at one place
only.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Input and output with C:

Formatted I/O functions

 printf and scanf

 control stings and escape sequences

 output specifications with printf functions;

Unformatted I/O functions to read and display single character and

a string

 getchar, putchar.

 gets and puts functions.

printf() function
The printf() function is used to print string or data values or a combination
of string and data values on the output screen (User screen). The printf()
function is built-in function defined in a header file called "stdio.h".The
printf (print formatted) standard library function is used to print the values
of expressions on standard output (i. e., display) in a specified format. A
typical call to the printf function takes the form of a C statement as
printf ( format _string, expr1, expr2, … ) ;
where exprl, expr2, … are expressions whose values are to be printed
and format_string specifies how they should be printed. The ellipsis (… )
indicates that the printf function call may contain variable number of
expressions. These expressions are optional and may be omitted.

Syntax:

printf(format_string,expr1,expr2…….expr-n);

scanf() function
The scanf() function is used to read multiple data values of different data
types from the keyboard. The scanf( ) function is built-in function defined in
a header file called "stdio.h
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

The scanf() function is use to read data from the standard input
stream stdin into the locations given by each entry in argument-list.
Arguments must be pointers to variables whose types correspond to
those in format-string. Input fields are interpreted by a format-string,
which consists of a multibyte character string that begins and ends in
a shift state.
The scanf( ) function has the following syntax...

Syntax:

scanf("format strings",&variableNames);

Control Strings

 control strings are also known as format specifiers.


 They are used in formatted input and output operations.

There are mostly six types of format specifiers that are


available in C.

Format Specifier Description


%d- Integer Format Specifier
%f- Float Format Specifier
%c- Character Format Specifier
%s- String Format Specifier
%u- Unsigned Integer Format Specifier
%ld- Long Int Format Specifier

Escape sequences

An escape sequence in C language is a sequence of characters that


doesn't represent itself when used inside string literal or character.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

It is composed of two or more characters starting with backslash \.

Unformatted Input and Output functions


-------------------------------------------------------

putchar() function
The putchar() function is used to display a single character on the
output screen. The putchar() functions prints the character which is
passed as a parameter to it and returns the same character as a
return value.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch = 'A';
putchar(ch);
}
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

puts() function
The puts() function is used to display a string on the output screen. The
puts() functions prints a string or sequence of characters till the newline.

Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
puts(name);
}

getchar() function
The getchar() function is used to read a character from the keyboard
and return it to the program. This function is used to read a single
character.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);
}
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

getch()
The getch() function is similar to getchar function. The getch() function is
used to read a character from the keyboard and return it to the program.
This function is used to read a single character.

Ex:

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);
}

gets() function
The gets() function is used to read a line of string and stores it into a
character array. The gets() function reads a line of string or sequence
of characters till a newline symbol enters. 

Ex:
#include<stdio.h>
#include<conio.h>
void main( )
{
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

C Operators and Expressions


An operator is a symbol used to perform arithmetic and logical operations in
a program.
An operand is one which acts on operators to perform any mathematical
operations
That means an operator is a special symbol that tells the compiler to
perform mathematical or logical operations.
C programming language supports a rich set of operators that are classified
as follows.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

Arithmetic Operators (+, -, *, /, %)

The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division
and percentage modulo. The following table provides information about
arithmetic operators.

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Operator Meaning Example

% Remainder of the Division 5%2=1

⇒ The addition operator can be used with numerical data types and
character data type. When it is used with numerical values, it performs
mathematical addition and when it is used with character data type values,

⇒ The remainder of the division operator is used with integer data type only.it
performs concatenation in strings (appending).

Relational Operators (<, >, <=, >=, ==, !=)


 The relational operators are the symbols that are used to compare two
values. That means the relational operators are used to check the
relationship between two values.
 Every relational operator has two results TRUE or FALSE. In simple
words, the relational operators are used to define conditions in a
program. The following table provides information about relational
operators.

Operato
r Meaning Example

< Returns TRUE if the first value is smaller than 10 < 5 is


second value otherwise returns FALSE FALSE

> Returns TRUE if the first value is larger than 10 > 5 is


second value otherwise returns FALSE TRUE

<= Returns TRUE if the first value is smaller than 10 <= 5 is


or equal to second value otherwise returns FALSE
FALSE
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Operato
r Meaning Example

>= Returns TRUE if the first value is larger than or 10 >= 5 is


equal to second value otherwise returns FALSE TRUE

== Returns TRUE if both values are equal 10 == 5 is


otherwise returns FALSE FALSE

!= Returns TRUE if both values are not equal 10 != 5 is


otherwise returns FALSE TRUE

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple
conditions into one condition. The following table provides information
about logical operators.

Operato
r Meaning Example

&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 > 10 is
otherwise returns TRUE TRUE

! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 > 10)
returns FALSE if it is TRUE is TRUE

⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the
conditions is FALSE then complete condition becomes FALSE.

⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the
conditions is TRUE then complete condition becomes TRUE.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Increment & Decrement Operators (++ & --)

 The increment and decrement operators are called unary operators because

both need only one operand.

 The increment operators adds one to the existing value of the operand and

the decrement operator subtracts one from the existing value of the operand.

The following table provides information about increment and decrement

operators.

Operator Meaning

++ Increment - Adds one to existing value

-- Decrement - Subtracts one from existing value

The increment and decrement operators are used infront of the operand (++a) or
after the operand (a++). If it is used infront of the operand, we call it as pre-
increment or pre-decrement and if it is used after the operand, we call it as post-
increment or post-decrement.

Pre-Increment or Pre-Decrement
 In the case of pre-increment, the value of the variable is increased by
one before the expression evaluation.
 In the case of pre-decrement, the value of the variable is decreased by
one before the expression evaluation.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 That means, when we use pre-increment or pre-decrement, first the


value of the variable is incremented or decremented by one, then the
modified value is used in the expression evaluation.

Ex:

#include<stdio.h>
#include<conio.h>

void main( )
{
int i = 5,j;

j = ++i; // Pre-Increment

printf("i = %d, j = %d", i ,j);

Post-Increment or Post-Decrement
when we use post-increment or post-decrement, first the expression is
evaluated with existing value, then the value of the variable is incremented
or decremented by one.
Ex:

#include<stdio.h>
#include<conio.h>
void main( )
{
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}

Assignment Operators (=, +=, -=, *=, /=, %=)


PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

The assignment operators are used to assign right-hand side value (Rvalue)
to the left-hand side variable (Lvalue). The assignment operator is used in
different variants along with arithmetic operators. The following table
describes all the assignment operators in the C programming language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable     A = 15

+= Add both left and right-hand side values and store the result into left-     A += 10
hand side variable ⇒A=
A+10

-= Subtract right-hand side value from left-hand side variable value and     A -= B
store the result ⇒ A = A-B
into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and     A *= B
store the result ⇒ A = A*B
into left-hand side variable

/= Divide left-hand side variable value with right-hand side variable     A /= B
value and store the result ⇒ A = A/B
into the left-hand side variable

%= Divide left-hand side variable value with right-hand side variable     A %= B
value and store the remainder ⇒A=A
into the left-hand side variable %B

Conditional Operator (?:)


 The conditional operator is also called a ternary operator because it
requires three operands.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 This operator is used for decision making. In this operator, first we


verify a condition, then we perform one operation out of the two
operations based on the condition result.
 If the condition is TRUE the first option is performed, if the condition
is FALSE the second option is performed.

 The conditional operator is used with the following syntax.

Condition ? expr1 :expr2;

Example
A = (10<15)?100:200; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot, etc.)

The following are the special operators in c programming language.

sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a
variable. This operator is used with the following syntax .

sizeof(variableName);

Example:

sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)


This operator is used to define pointer variables in c programming language.

Comma operator (,)


This operator is used to separate variables while they are declaring, separate
the expressions in function calls, etc.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

Dot operator (.)


This operator is used to access members of structure or union.

C Operator Precedence and Associativity

Operator Precedence

Operator precedence is used to determine the order of operators evaluated


in an expression. In c programming language every operator has precedence
(priority). When there is more than one operator in an expression the
operator with higher precedence is evaluated first and the operator with the
least precedence is evaluated last.

Operator Associativity
Operator associativity is used to determine the order of operators with equal
precedence evaluated in an expression. In the c programming language,
when an expression contains multiple operators with equal precedence, we
use associativity to determine the order of evaluation of those operators.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

C Expression Evaluation
In the C programming language, an expression is evaluated based on the

operator precedence and associativity. When there are multiple operators in

an expression, they are evaluated according to their precedence and

associativity. The operator with higher precedence is evaluated first and the

operator with the least precedence is evaluated last.

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.

1 + 16 8 is multiplied by 2, giving value 16.

17

Type conversion
In a c programming language, the data conversion is performed in two
different methods as follows...

1. Type Conversion
2. Type Casting

Type Conversion
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 The type conversion is the process of converting a data value from one
data type to another data type automatically by the compiler.
 Sometimes type conversion is also called implicit type conversion.
The implicit type conversion is automatically performed by the
compiler.
 If the operands are of two different datatypes then an operand having
lower datatype is automatically converted into higher datatype

Ex:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}

Typecasting
 Typecasting is also called an explicit type conversion. Compiler
converts data from one data type to another data type implicitly.
 When compiler converts implicitly, there may be a data loss. In such a
case, we convert the data from one data type to another data type
using explicit type conversion. Forcefull type conversion and done by
the programmer. To perform this we use the unary cast operator.
PROGRAMMING IN C –NEP SCHEME VVFGC MYSORE

 To convert data from one type to another type we specify the target
data type in parenthesis as a prefix to the data value that has to be
converted. The general syntax of typecasting is as follows.

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf(“%d%d%d”,&a,&b,&c);
avg = (a + b + c) / 3 ;
printf( "avg before casting = %f”,avg);
avg = (float)(a + b + c) / 3 ;
printf( "avg after casting = %f”,avg);
return 0;
}

Points on type casting

Converting float to an int will truncate the fraction. Hence


losing the meaning of the value.
Converting double to float will round up the digits.
Converting long int into int will cause dropping of excess
high order bits.
Converting smaller datatype into higher datatype is called
type promotion.
Highly recommended to convert from smaller to higher to
prevent data loss.

You might also like