0% found this document useful (0 votes)
5 views48 pages

Module 1 Notes Final

The document provides an introduction to the C programming language, detailing its history, features, and structure. It covers the evolution of C from its origins in ALGOL and BCPL to the latest standards like C17 and the upcoming C23. Additionally, it explains the basic structure of a C program, the character set, tokens, constants, and the use of symbolic constants.

Uploaded by

anumod9b
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views48 pages

Module 1 Notes Final

The document provides an introduction to the C programming language, detailing its history, features, and structure. It covers the evolution of C from its origins in ALGOL and BCPL to the latest standards like C17 and the upcoming C23. Additionally, it explains the basic structure of a C program, the character set, tokens, constants, and the use of symbolic constants.

Uploaded by

anumod9b
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 1

INTRODUCTION TO C PROGRAMMING
History of C Language
ALGOL' was the foundation or progenitor of programming languages. It was first introduced
in 1960. 'ALGOL' was widely used in European countries. The ALGOL had introduced the
concept of structured programming to the developer community. The year 1967 marked the
introduction of a novel computer programming language known as 'BCPL', an acronym for
Basic Combined Programming Language. BCPL was designed by Martin Richards in the
mid-1960s.

Dennis K&R C

Dennis Ritchie along with Brian Kernighan published the first edition of their book "The C
Programming Language". Popularly known as K&R (the initials of its authors), the book
served for many years as an informal specification of the language.

ANSI C

In the 1980s, the American National Standards Institute (ANSI) began working on a formal
standard for the C language. This led to the development of ANSI C, which was standardized
in 1989.

Ritchie created C at Bell Laboratories in the early 1970s. It developed from an older language
named B that Ken Thompson created. The main purpose of C's creation was to construct the
Unix operating system, which was crucial in the advancement of contemporary computers.

In 1971, Dennis Ritchie started working on C, and he and other Bell Labs developers kept
improving it. The language is appropriate for both system programming and application
development.

C99

In 1999, the ISO/IEC approved an updated version of the C standard known as C99. The C
standard was further revised in the late 1990s.

C11

C11, published in 2011, is another major revision of the C standard. The C11 standard adds
new features to C and the library and introduced features such as multi-threading support,
anonymous structures and unions, and improved Unicode support.
C17

The C17 standard has been published in June 2018. C17 is the current standard for the C
programming language. No new features have been introduced with this standard revision.

C18

The most recent version of the C standard, C18, was published in 2018. It includes minor
revisions and bug fixes compared to C11.

C23

C23 is the informal name for the next major C language standard revision, expected to be
published in 2024. 14 new keywords are expected to be introduced in this revision.

Features of C Language
C is the widely used Procedure Oriented Programming (POP) language. It
provides many features that are given below.

1. Simple

2. Machine Independent or Portable

3. Mid-level programming language


4. Structured programming language

5. Rich Library

6. Memory Management

7. Fast Speed

8. Pointers

9. Recursion

[Link]

1) Simple

C is a simple language in the sense that it provides a structured approach (to break
the problem into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed on different


machines with some machine specific changes. Therefore, C is a machine
independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop
system applications such as kernel, driver, etc. It also supports the features of a
high-level language. That is why it is known as mid-level language.

4) Structured programming language

C is a structured programming language in the sense that we can break the


program into parts using functions. So, it is easy to understand and modify.
Functions also provide code reusability. The program structure follows
the "top-down approach".

5) Rich Library

C provides a lot of inbuilt functions that make the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C language, we can free


the allocated memory at any time by calling the free() function.

7) Speed

The compilation and execution time of C language is fast since there are lesser
overhead.

8) Pointer

C provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, array,
etc.

9) Recursion

In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.

10) Extensible

C language is extensible because it can easily adopt new features.


Importance of C
1. C is robust language and has rich set of built-in functions, data types
and operators which can be used to write any complex program.
2. Program written in C are efficient due to availability of several data types and
operators.
3. C supports low level features like bit level programming and direct access
to memory using pointer which is very useful for managing resource
efficiently.
4. C has high level constructs and it is more user friendly as its syntaxes
approaches to English like language.
5. Generally, we use to call C as a middle level language. Because, the ‘C’
compiler combines the capabilities of an assembly language with the features
of a high-level language. Therefore, it is best for writing both system software
and business packages.
6. ‘C’ Programs are efficient and fast.
7. C is highly portable, that is, ‘C’ programs written on one computer can be run
on another with little (or) no modification.
8. ‘C’ language is best for structured programming, where the user can think of a
problem in terms of function modules (or) blocks.
9. It has the ability to extend itself. We can add our own functions to the C library.
It was named ‘C’ because it is an offspring of BCPL (Basic Combined Programming
Language) which was popularly called ‘B’ language.

Basic Structure of C Program


Basically, structure of the C program is divided into six different sections.
The six sections are,
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.

Link Section

The link section consists of the header files of the functions that are used in
the program. It provides instructions to the compiler to link functions from
the system library.

Definition Section

All the symbolic constants are written in definition section. Macros are known
as symbolic constants.

Global Declaration Section

The global variables that can be used anywhere in the program are declared
in global declaration section. This section also declares the user defined
functions.

main() Function Section

It is necessary have one main() function section in every C program. This


section contains two parts, declaration and executable part. The declaration
part declares all the variables that are used in executable part. These two
parts must be written in between the opening and closing braces. Each
statement in the declaration and executable part must end with a semicolon
(;). The execution of program starts at opening braces and ends at closing
braces.

Subprogram Section

The subprogram section contains all the user defined functions that are used
to perform a specific task. These user defined functions are called in the
main() function.

Example: -
ELEMENTS OF C LANGUAGE AND
PROGRAM CONSTRUCTS
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, special symbols and white spaces.

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, , backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | etc.,

White spaces
It includes blank space, tab space, backspace, new line, etc.
C Tokens
Tokens are the smallest individual elements of a program, which are
meaningful to the compiler. C programs are written using these tokens and the
syntax of the language.

The following are the types of C tokens: Keywords, Identifiers, Constant, Strings,
Operators, and Special Symbols.

[Link]:

Keywords are pre-defined or reserved words in a programming language.


Each keyword is meant to perform a specific function in a program. Since keywords
are referred names for a compiler, they can’t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not allowed.
C language supports 32 keywords which are 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

[Link]
They are used for naming of variables, functions, array etc. These are user-defined
names which consist of alphabets, number, underscore ‘_’. Identifier’s name should
not be same or same as keywords. Keywords are not used as identifiers.
Rules for naming C identifiers −
 It must begin with alphabets or underscore.
 Only alphabets, numbers, underscore can be used, no other special
characters, punctuations are allowed.
 It must not contain white-space.
 It should not be a keyword.
 It should be up to 31 characters long.

[Link] (Literals)
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants
as [Link] are treated just like regular variables except that their values
cannot be modified after their definition.

Integer Literals(Constants)
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal.
An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and can
be in any order, i.e., both lu and ul are the same.

Decimal number (base 10)

It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.

Octal number (base 8)


It is defined as a number in which 0 is followed by digits such as 0,1,2,3,4,5,6,7. For
example, 012, 034, 055, etc.

Hexadecimal number (base 16)

It is defined as a number in which 0x or 0X is followed by the hexadecimal digits


(i.e., digits from 0 to 9, alphabetical characters from (a-z) or (A-Z)).
Here are some examples of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Example

#include <stdio.h>
int main()
{
const int a=23; // constant integer literal
printf("Integer literal : %d", a);
return 0;
}

Output

Integer literal : 23

Floating-point(Real) Constants
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.
While representing decimal form, you must include the decimal point, the exponent,
or both; and while representing exponential form, you must include the integer part,
the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
1.2, +9.0, -4.5
Example of float literal in decimal form.

#include <stdio.h>
int main()
{
const float a=4.5; // constant float literal
const float b=5.6; // constant float literal
float sum;
sum=a+b;
printf("%f", sum);
return 0;
}

Output

10.100000

Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'),
or a universal character (e.g., '\u02C0').

String Constants
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape sequences,
and universal characters. String literals are stored in C as an array of chars,
terminated by a null character, ‘\0’.
Example:- “A”,”Hai”,”123”

Defining Constants
There are two simple ways in C to define constants −
 Using #define preprocessor.(Symbolic Constants)
Example : - #define PI 3.141592
 Using const keyword.
Example :- const int a=23;
Symbolic Constants in C
A symbolic constant is a name given to some numeric constant, or a character
constant or string constant, or any other constants.

Symbolic constant names are also known as constant identifiers. Pre-processor


directive #define is used for defining symbolic constants.

Syntax for Creating Symbolic Constants

#define symbolic_constant_name value_of_the_constant

Examples

#define PI 3.141592

#define SIZE 50
#define TRUE 1
#define FALSE 0

#define MAX 500

Here PI, TRUE,FALSE, SIZE ,MAX are symbolic constants.

Note: symbolic constants names are written in uppercase by convention,


but it is not required.

Advantages of using Symbolic Constants


i)Understandability

They can be used to assign names to values. For example we can define
the value of ‘pi’ as #define PI 3.141592 and use the name PI in place 3.141592.
This will increase understandability.

ii)Modifiability

Replacement/Modification of value has to be done at only one place and


wherever the name appears in the text it gets the value by execution of the
preprocessor. So modification of values are easy.
iii)Saves time.

If the Symbolic Constant appears 20 times in the program; it needs to be


changed at one place only. This saves time.

4. Strings
Strings in C are always represented as an array of characters having null
character '\0' at the end of the string. This null character denotes the end of
the string. Strings in C are enclosed within double quotes, while characters
are enclosed within single characters. The size of a string is a number of
characters that the string contains.
char a[11] = "CPROGRAMING"; // The compiler allocates the 11 bytes to the
'a' array.
char a[] = "CPROGRAMING"; // The compiler allocates the memory at the
run time.
char a[11] = {'C','P','R','O','G','R','A','M','I','N',’G’,'\0'}; // String is represented in
the form of characters.
5. Special Symbols
Some special characters are used in C, and they have a special meaning
which cannot be used for another purpose.
Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
Simple brackets ( ): It is used in function declaration and function calling. Printf ()
is a pre-defined function.
Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
Tilde (~): It is used as a destructor to free memory.
Period (.): It is used to access a member of a structure or a union.
6. Operators
Operators in C is a special symbol used to perform the functions. The data items on
which the operators are applied are known as operands. Operators are applied
between the operands. Depending on the number of operands, operators are
classified as follows:
Unary Operator: A unary operator is an operator applied to the single operand. For
example: increment operator (++), decrement operator (--), size of, (type)*.
Binary Operator: The binary operator is an operator applied between two operands.
The following is the list of the binary operators: Arithmetic, Relational, Shift, Logical,
Bitwise, Conditional, and Assignment Operators.

C Escape Sequences or Backslash Character


Constants
In C Programming Language escape sequence is a special string comprise a
backslash (\) followed by a letter or by a combination of digits used to control
output on monitor. Escape sequences are typically used to represent actions such
as newline, carriage returns, tab movements and non-printing characters over the
monitor. The following table lists the common ANSI escape sequences and their
meaning.

Character Meaning

‘\a’ alert

‘\b’ backspace

‘\f’ form feed

‘\n’ newline

‘\t’ horizontal tab

‘\r’ carriage return

‘\v’ vertical tab

‘\\’ backslash

‘\’ ’ single quote

‘\" ’ double quote

‘\?’ Question mark

‘\0’ null
Variables in C
A variable is a data name that may be used to store a data value. The
primary purpose of variables is to store data in memory for later use. Unlike
constants which do not change during the program execution, variables value
may change during execution. If you declare a variable in C, that means you are
asking the operating system to reserve a piece of memory with that variable
name.

A variable name can be chosen by the programmer in a meaningful way so as


to reflect its function or nature in the program.

Examples : - sum, Average, Total_Marks…

Rules to name a Variable


1. Variable name must not start with a digit.
2. Variable name can consist of alphabets, digits and special symbols like
underscore _.
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-
sensitive, so it is suggested to keep the variable names in lower case.

Declaring and Initializing a variable


Declaration of variables must be done before they are used in the program. Declaration
does the following things.

1. It tells the compiler what the variable name is.

2. It specifies what type of data the variable will hold.

The process of giving initial values to variables is called initialization.

Primary Type Declaration


There are several ways to declare variables:

dataType variableName;
 This declares a variable, declares its data type, and reserves memory for it. It
says nothing about what value is put in memory.

dataType variableName = initialValue ;

 This declares a variable, declares its data type, reserves memory for it, and
puts an initial value into that memory. The initial value must be of the correct
data type.

dataType variablOne = initialValueOne, variableTwo = initialValueTwo ;

 This declares two variables, both of the same data type, reserves memory,
and puts an initial value in each variable. Again, you can do this for more than
two variables as long as you follow the pattern.

Examples

int i, j, k;
char c, ch;
float f, salary;
double d;

Variables can be initialized (assigned an initial value) in their declaration. The


initializer consists of an equal sign followed by a constant expression as follows −

type variable_name = value;

Some examples are −

int d = 3, f = 5; // definition and initializing d and f.

char x = 'x'; // the variable x has the value 'x'.

C - Data Types
Data type determines the type of data a variable will hold. If a variable x is declared
as int, it means x can hold only integer values. Every variable which is used in the
program must be declared as what data-type it is. In C language, data types can be
classified into three :-

1. Primitive/Basic/Fundamental data types


2. Derived data types
3. User-defined data types
Primitive Data Types
In C there are four types of basic data types - character data type, Integer data type,
floating-point data, and void.

INTEGER DATA TYPE:

 Integer data type allows a variable to store numeric values.


 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using
16 bit processor, 2 byte (16 bit) of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of
memory for 64 bit processor is allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 In order to provide control over the range of numbers and storage space, C
has three classes of integer storage, namely short int, int, and long int in both
signed and unsigned forms.

FLOATING POINT DATA TYPE:

Floating point data type consists of 2 types. They are,

1. float
2. double

1. FLOAT:

 Float data type allows a variable to store decimal values.


 Storage size of float data type is 4. This also varies depend upon the
processor in the CPU as “int” data type.
 We can use up-to 6 digits after decimal using float data type.

For example, 10.456789 can be stored in a variable using float data type.

2. DOUBLE:

 Double data type is also same as float data type which allows up-to 10
digits after decimal.
 The range for double datatype is from 1.7E–308 to 1.7E+308.

CHARACTER DATA TYPE:

 Character data type allows a variable to store only one character.


 Storage size of character data type is 1 byte.
 “char” keyword is used to refer character data type.
 The modifiers signed and unsigned may be applied to char.

VOID DATA TYPE

 Void is an empty data type that has no value.


 We use void data type in functions when we don’t want to return any value
to the calling function.

MODIFIERS USED WITH DATA TYPES IN C

 The amount of memory space to be allocated for a variable is derived by


modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit
processor. We can increase the range by using long int which is 8
byte. We can decrease the range by using short int which is 2 byte.
 There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long

User-Defined Type Declaration


i) Type Defenition

The C programming language provides a keyword called typedef, which you can
use to give a type a new name. You can use typedef to give a name to your user
defined data types as well. In short, we can say that this keyword is used to redefine
the name of an already existing variable. This keyword is useful when we are dealing
with the lengthy data types.

Syntax of typedef

typedef <existing_name> <alias_name>

-
In the above syntax, 'existing_name' is1.1
the name of an already existing variable
3.4 name given to the existing variable.
while 'alias name' is another

Example

1. typedef unsigned int unit;

In the above statements, we have declared the unit variable of type unsigned int by
using a typedef keyword.

Now, we can create the variables of type unsigned int by writing the following
statement:

unit a, b;

instead of writing:

unsigned int a, b;

ii) Enumeration
Enumeration is another user defined datatype in C language. It is used to assign
names to the integral constants which makes a program easy to read and maintain.
The keyword “enum” is used to declare an enumeration.

Syntax of enum

enum enum_name {integer_const1, integer_const2,.....integter_constN};


The enum keyword is also used to define the variables of enum type.
In the above declaration, we define the enum containing 'N' integer constants. The
default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also
change the default value of the integer constants at the time of the declaration.

Two Enum names can have same value.


All unassigned names get value as value of previous name plus one.

For example:

1. enum fruits{mango, apple, strawberry, papaya};

The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3.


If we want to change these default values, then we can do as given below:

2. enum fruits{ mango=2, apple=1, strawberry=5, papaya};


Here papaya will be assigned the value 6.

Variables of type enum can also be defined. They can be defined in two
ways:
// In both of the below cases, "day" is defined as the variable of
type week.
a) Using two statements
enum week{Mon, Tue, Wed};
enum week day;
b) Using a single statement.
enum week{Mon, Tue, Wed}day;

// An example program to demonstrate working of enum in C

#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

Output:
2

Derived Data Types in C


In C, the data types derived from the primitive or built-in data types are called Derived
Data Types. In other words, the derived data types are those data types that are created by
combining primitive data types and other derived data types.

Functions
A function is called a C language construct which consists of a function-body associated
with a function-name. In every program in C language, execution begins from the main
function, which gets terminated after completing some operations which may include
invoking other functions.

Function Declaration

return_type function_name(data_type param1, data_type param2, ...);

Arrays
Array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. An array is capable of storing the collection of data of primitive, derived, and
user-defined data types.

Array Declaration

data_type array_name [size];

Pointer
A pointer in C language is a data type that stores the address where data is stored. Pointers
store memory addresses of variables, functions, and even other pointers.

Pointer Declaration
data_type * ptr_name;
where,
 data_type: type of data that a pointer is pointing to.
 ptr_name: name of the pointer.
 *: dereferencing operator.

Structure
In C, a structure is a user-defined data type that can be used to group items of possibly
different types into a single type.
 The struct keyword is used to define a structure. The items in the structure are called its
members and they can be of any valid data type.

Syntax

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
Union
Unions are similar to structures in many ways. What makes a union different is that all the
members in the union are stored in the same memory location resulting in only one member
containing data at the same time. The size of the union is the size of its largest member.
Union is declared using the "union" keyword.

Syntax

union union_name {
datatype member1;
datatype member2;
...
};
Comments in C
A comment is an explanation or description of the source code of the program. It
helps a developer explain logic of the code and improves program readability. At run-time, a
comment is ignored by the compiler , so they won’t be executed.

There are two types of comments in C:

1) Single-line Comments which uses a double slash // dedicated to comment


single lines.
Example: -
// This is a single line comment
2) Multiline Comments, comment that starts with a slash asterisk /* and
finishes with an asterisk slash */ and you can place it anywhere in your code,
on the same line or several lines. Example: -

/*This is a

Multiline comment*/

SAMPLE PROGRAMS

Example 1: Displaying a Text

#include <stdio.h>

int main()

/* printf function displays the content that is passed between the double quotes. */

printf("WELCOME TO C PROGRAMMING");

return 0;

Output:

WELCOME TO C PROGRAMMING
Example 2: Program to Print an Integer entered by the user.

#include <stdio.h>

int main()

int num;

/* Here we are displaying a message for the user.*/

printf("Enter an integer: ");

/* Here scanf() function reads the integer value entered by user


and stores it into the variable num*/

scanf("%d", &num);

// displaying the value of num using printf

printf("The number entered by user is: %d", num);

return 0;

Output:

Enter an integer: 101

The number entered by user is: 101

Example 3: Program to check whether the given


integer is positive or negative.

#include <stdio.h>
void main()

int num;

printf("Enter a number: \n");

scanf("%d", &num);

if (num > 0)

printf("%d is a positive number \n", num);

else if (num < 0)

printf("%d is a negative number \n", num);

else

printf("0 is neither positive nor negative");

Output 1:

Enter a number:

0 is neither positive nor negative

Output 2:

Enter a number:

-3

-3 is a negative number
C OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators. C operators can be classified as follows.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and decrement Operators
7. Conditional Operators
8. Special Operators.

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulo division Operator, gives remainder of an integer B%A=0


division.

The % operator cannot be used on floating point data.

Relational Operators
Relational operators are used to compare or relate two quantities. An expression
containing a relational operator is termed as a relational expression. The value of a
relational expression is either one or zero. The following table shows all the relational
operators supported by C. Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then (A == B) is not true.
the condition becomes true.

!= Checks if the values of two operands are not equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.

> Checks if the value of left operand is greater than the value of right (A > B) is not true.
operand. If yes, then the condition becomes true.

< Checks if the value of left operand is less than the value of right (A < B) is true.
operand. If yes, then the condition becomes true.

>= Checks if the value of left operand is greater than or equal to the (A >= B) is not true.
value of right operand. If yes, then the condition becomes true.

<= Checks if the value of left operand is less than or equal to the value (A <= B) is true.
of right operand. If yes, then the condition becomes true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −

Operator Description Example


&& Called Logical AND operator. If both the operands are (A && B) is false.
non-zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two operands (A || B) is true.


is non-zero, then the condition becomes true.

! Called Logical NOT Operator. It is used to reverse the !(A && B) is true.
logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.

An expression which combines two or more relational expressions is called as a


logical expression or compound relational expression.
Example – A>B && X==19.

Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =.It evaluates expression on right side of = symbol and assigns
evaluated value to left side of the variable.

Shorthand assignment operator


C supports a short variant of assignment operator called compound assignment or
shorthand assignment operators. Shorthand assignment operator combines one of
the arithmetic or bitwise operators with assignment operator.
The following table lists the assignment operators supported by the C language −

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b
Operator Example Same as

/= a /= b a = a/b

%= a %= b a = a%b

Bitwise Operators

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.
These two operators are unary operators, meaning they only operate on a single operand.
These operators can be used in two forms – pre increment/decrement and post
increment/decrement.

Pre-increment operator: A pre-increment operator is used to increment the value


of a variable before using it in an expression. In the Pre-Increment, value is first incremented
and then used inside the expression.

Syntax: ++x

a = ++x;
Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets
modified before using it in the expression.

Post-increment operator: A post-increment operator is used to increment the


value of variable after executing expression completely in which post increment is used. In
the Post-Increment, value is first used in the expression and then incremented.

Syntax: x++

b = x++;
Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of
‘x’ is assigned to ‘b’ and after that it will be incremented.
In the same way we can use decrement operator also.

Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements
are the decision-making statements which depends upon the output of the expression. It is
represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behaviour of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.

Syntax
1. Expression1? expression2: expression3;

The pictorial representation of the above syntax is shown below:


In the above syntax, the expression1 is a Boolean condition and it will be
evaluated first. It can be either true or false.
If the expression1 results into a true value, then the expression2 will execute and
it’s result will be the result of the entire expression.
If the expression1 returns false value then the expression3 will execute and it’s
result will be the result of the entire expression.
Example:
#include<stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));
return 0;
}

Special Operators
Below are some of the special operators that the C programming language offers.

The Comma Operator


 The Comma operator can be used to link the related expressions together.

Example For Comma Operator

Comma Operator In for Loops


for(i=0,j=1;i>10:i++,j++)

value=(x=10, y=20, x+y)

sizeof operator

sizeof returns the size of a variable or datatype.

sizeof (data_type/variable)
Example:
X=sizeof(int);
Y=sizeof(n);

Reference operator or Address Operater ("&")

The reference operator noted by ampersand ("&"), is also a unary operator in c languages

that uses for assign address of the variables. It returns the pointer address of the variable.

This is called "referencing" operator.

Syntax

data_type x;
data_type *pt;
pt = &x

Dereference/Indirection operator ("*") or Pointer Operator

The dereference operator or indirection operator, noted by asterisk ("*"), is also a unary

operator in c languages that uses for pointer variables. It operates on a pointer variable,
and returns value equivalent to the value at the pointer address. This is called

"dereferencing" the pointer.

data_type *pt;

C Expressions
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an array element
or a constant.

There are four types of expressions exist in C:

1. Arithmetic Expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions

Arithmetic Expressions
An arithmetic expression is an expression that consists of operands (variables or constants)
and arithmetic operators. An arithmetic expression computes a value of type int, float or double.

When an expression contains only integral operands, then it is known as pure integer
expression when it contains only real operands, it is known as pure real expression, and when it
contains both integral and real operands, it is known as mixed mode expression.

For example:

9/2 + a-b;

X*Y-Z

Evaluation of Arithmetic Expressions


The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.

Expressions are evaluated using an assignment of the form,

Variable = expression

Example

x= a*b-c
When the statement is encountered, the expression is evaluated first and the result then replaces
the previous value of the variable on the LHS. All variables used in the expression must be assigned
values before evaluation is attempted. Also, all variables used in the program must be defined
before they are used in the expressions.

Type Conversion in Expressions


C allows us to convert data of one type to that of another. This is known as type conversion.

There are two types of type conversion in C.

1. Implicit Conversion
2. Explicit Conversion (also known as Type Casting)

Implicit Type Conversion (Automatic Type conversion)


The type conversion that is done automatically by the compiler is known as implicit type
conversion. This type of conversion is also known as automatic type conversion. It is done by the
compiler on its own, without any external trigger from the user.
It generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data. That is, All the data
types of the variables are upgraded to the data type of the variable with largest data type.

The rules of implicit type conversion in c is as follows.

1. If one of the operands is long double, the other is promoted to long double before the
operation is carried out.
2. Else, If one of the operands is double, the other is promoted to double before the operation
is carried out.
3. Otherwise, if one of the operands is float, the other is promoted to float before the
operation is carried out.
4. Otherwise, if one of the operands is unsigned long int, the other is promoted to unsigned
long int before the operation is carried out.
5. Otherwise if either operand is long int, the other operand is unsigned int , then
a. If unsigned int can be converted to long int, the unsigned int operand will be
promoted to long int.
b. Else, both operands will be converted to unsigned long int.
6. Otherwise if either operand is long int, the other operand will be promoted to long int.
7. Else, if one of the operands is unsigned int, the other will be converted to unsigned int.

8. Otherwise, If one operand is of type int then the other operand will be converted to int and
the result of the operation will be an int.

Figure : Conversion hierarchy


Example of Implicit Type Conversion

#include<stdio.h>

int main()

int x = 10; // integer x

Int y = 'a'; // y implicitly converted to int. ASCII value //of 'a' is 97

x = x + y;

float z = x + 1.0; // x is implicitly converted to float

printf("x = %d, z = %f", x, z);

return 0;

Output:

x = 107, z = 108.000000

The final result of an expression is converted to the type of the variable on the LHS of the equal to sign before
assigning the value to [Link] following changes are introduced during the final assignment.

 Converting float to an int will truncate the fraction part hence losing the meaning of the value.
 Converting double to float will round up the digits.
 Converting long int to int will cause dropping of excess high order bits.

Explicit Conversion (Type casting)


When the user manually changes data from one type to another, this is known as explicit conversion.
This type of conversion is also known as type casting.

The syntax is:

(data_type)expression;

where, data_type is any valid c data type, and expression may be constant, variable or expression.

Example

Consider the following code:

int x=7, y=5 ;

float z;

z=x/y; /*Here the value of z is 1*/

If we want to get the exact value of 7/5 then we need explicit casting from int to float:
int x=7, y=5;

float z;

z = (float)x/y; /*Here the value of z is 1.4*/

Here x is explicitly converted into float and by the rule of automatic type conversion, the division is
performed in floating point mode, thus retaining the fractional part of the result.

Note: - The type of x remains as int in the other parts of the program.

Data Loss During Conversion (Narrowing Conversion)


Conversion from one data type to another is prone to data loss. This happens when data of a larger type is
converted to data of a smaller type.

Operator Precedence and Associativity


Operator Precedence and Associativity are two characteristics of operators that determine the
evaluation order of sub-expressions in absence of brackets.

Each operator in C has a precedence associated with it. There are distinct levels of precedence and
an operator may belong to one of these levels. The operators at the higher level are evaluated first.

For example: Solve

10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)

and not as (10 + 20) * 30 because the operator * has higher precedence than +.

Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.

For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Mathematical Functions
C Programming allows us to perform mathematical operations through the functions defined
in <math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.

SAMPLE PROGRAMS
[Link] a program to check whether a year is leap year or not.
A year is a leap year if −
 It is evenly divisible by 100
o If it is divisible by 100, then it should also be divisible by 400
 Except this, all other years evenly divisible by 4 are leap years.

#include <stdio.h>

int main() {
int year;
year = 2016;
if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
printf("%d is a leap year", year);
else
printf("%d is not a leap year", year);

return 0;
}

Output
2016 is a leap year

2. Program to find the size of data types in C.

#include<stdio.h>
int main()
{
printf("Size of char: %d bytes\n",sizeof(char));
printf("Size of int: %d bytes\n",sizeof(int));
printf("Size of float: %d bytes\n",sizeof(float));
printf("Size of double: %d bytes", sizeof(double));
return 0;
}
Output:

Size of char: 1 byte


Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes

DATA INPUT OUTPUT FUNCTIONS


Input means to provide the program with some data to be used in the
program and Output means to display data on screen or write the data to a
printer or a file. C programming language provides many built-in functions to
read any given input and to display data on screen when there is a need to
output the result.

Non-formatted Input-Output functions


Non-formatted input/output function meaning it does not allow user to read
input and write output in their format.
getchar()
This is a single character input function. getchar() reads a single character from
the standard input device, which is normally the keyboard. You can use this
method in a loop in case you want to read more than one character.

putchar()
This is a single character output function. putchar() writes a single character to
the standard output device, which is normally the console(screen). In case you
want to display more than one characters, use putchar() method in a loop.
#include <stdio.h>
void main( )
{
char c;
printf("Enter a character");

c = getchar();

putchar(c); //display the character stored in variable c


}

gets()
It reads a string from the keyboard.
The syntax for gets() function is as follows −
gets(variablename);

Example
#include<stdio.h>
#include<string.h>
main(){
char str[10];
printf("Enter your name: \n");
gets(str);
printf("Hello %s welcome to Tutorialspoint", str);
}
Output
Enter your name:
Madhu
Hello Madhu welcome to Tutorialspoint

puts()
It displays a string on the monitor.
The syntax for puts() function is as follows −

puts(variablename/string);
For example,
puts("tutorial");

Example
#include<stdio.h>

void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}

getch()
getch() is character input functions. It reads a character from the keyboard but
does not echo the pressed character and returns character pressed. It is
defined in header file conio.h.
Syntax
character_variable = getch();

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

void main()
{
char ch;
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is: %c”, ch);
}

Output

Press any character:


Pressed character is: e

------------------------------------
Note: while using getch() pressed
character is not echoed. Here pressed
character is e and it is displayed
by printf().

getche()

Like getch(), getche() is also character input functions. It is unformatted input


function meaning it does not allow user to read input in their format.
Difference between getch() and getche() is that getche() echoes pressed
character. getche() also returns character pressed like getch(). It is also defined
in header file conio.h.

Syntax

character_variable = getche();

Example : Reading Character Using getche() & Displaying

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“Press any character: ”);
ch = getche();
printf(“\nPressed character is: %c”, ch);
}
Output of the above program :
Press any character: e
Pressed character is: e

-----------------------------------
Note: while using getch() pressed
character is not echoed but while
using getche() it is echoed. Here pressed
character is e and it is displayed
by printf().

Formatted Input and Output functions


scanf()
The scanf function is used to read formatted input data. The scanf function is
written as -
scanf(<control string>, &address1, &address2, . . . , &addressn);
Here, the first parameter <control string> contains a list of format specifiers
indicating the format and type of data to be read. The remaining parameters -
&address1, &address2, ..., &addressn are addresses of the variables where the
read data will be stored. scanf reads the input data as per the format specifiers
and stores them (i.e., assigns them) to the corresponding addresses. An & is
pre-fixed to the variable name to denote its address.
Example:
scanf("%d %f",&x,&y);
Here the first argument is a string that contains two format specifiers - %d
and %f, the first format specifier (%d) is for argument &x and the second one
(%f) is for the argument &y. So, two pieces of input data will be read - the first
piece is treated according to %d(integer)and the second one is treated
according to %f(float). Format specifiers in the <control string> are always
specified for the remaining arguments, in order, from left to right.

Syntax of format specifier


Each format specifier begins with the percentage character (%) followed by a
conversion character which indicates the type of the corresponding data item.
Similar control string is also used with the printf function . The meaning of the
conversion characters for input/output is given in the table below. This can be
apply to both scanf and printf functions.

Format
Data Type
Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c
Format
Data Type
Specifier

long double
%Lf

It is possible to specify variable field width in a scanf() format string. You


can specify a maximum field width for a given field by placing an integer
value between the ‘%’ and the field type specifier.

printf()
The printf function is used to output data onto the standard output device. In
general, the printf function is written as,
printf(<control string>, arg1, arg2, . . . , argn);
where the <control string> refers to a string containing required formatting
information as in scanf, and arg1, arg2, ..., argn are individual data variables
whose values are to be printed. However, unlike scanf, these data variable
names are not preceded by the & symbol. This is because printf is expected to
only output the values of these variables and not their addresses.
Example:
printf("%d %f",x,y);

NOTE : printf() function returns the number of characters printed by it, and
scanf() returns the number of characters read by it.
Example:
int i = printf("studytonight");
In this program printf("studytonight"); will return 12 as result, which will be
stored in the variable i, because studytonight has 12 characters.

Difference between scanf() and gets()


The main difference between these two functions is that scanf() stops reading
characters when it encounters a space, but gets() reads space as character too.
If you enter name as Study Tonight using scanf() it will only read and store
Stand will leave the part after space. But gets() function will read it completely.

You might also like