Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PPS T Notes - 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

PROGRAMMING FOR PROBLEM

SOLVING (18ESCS114)

Mrs. Shruti Tavaragundi


Guest Faculty
Dept. of CSE, UVCE
Introduction to C Programming
C Programming Language is a very popular computer programming language through which

users and computers can communicate.

What is C?

C is a computer programming language used to design computer software and applications.

Why do we use C?

We use the C programming language to design computer software and applications.

Who invented C?

C Programming Language was invented in the year 1972 by Dennis Ritchie (Dennis MacAlistair

Ritchie). He was an American Computer Scientist worked at Bell Labs as a researcher along

with Ken Thompson. He was born on 9th September 1941 and lived till 12th October 2011.

He is said to be the Father of C.

Software used to create and execute a C Program

Following are the applications and software used to create and execute C programs.

1. Turbo C

2. Turbo C++

3. GNU C

4. Code Blocks

5. Net Beans
Introduction to Computer Systems
What is a Computer?

The computer is an electronic device which operates under the control of instructions stored

in its memory. A computer can take data from the user through input devices (Input), process

the user given data (Processing), produces the result to the user through output devices

(Output)and stores data (Information) for future use. A Computer can be defined as follows...

The Computer is an electronic device which operates under the control of instructions

stored in its memory and it takes the data from the user, a process that data gives the result

and stores the result for future use.

What does a computer consist of?

Every computer mainly consists of three things and those are...

1. Hardware

2. Software

3. User

Here the user interacts with the software, and the software makes the computer hardware

parts to work for the user.

What is Computer Hardware?


All physical components of the computer are called as computer hardware. A user can see,

touch and feel every hardware of the computer. All hardware components perform any task

based on the instructions given by the computer software.

The computer hardware is the physical part of a computer.

The computer hardware components are as follows...

1. Input Devices - These are the parts through which a user can give the data to the

computer.

2. Output Devices - These are the physical components of a computer through which the

computer gives the result to the user.

3. Storage Devices - These are the physical components of a computer in which the data

can be stored.

4. Devices Drives - Using drives, user can read and write data on to the storage devices

like CD, floppy, etc.,

5. Cables - Various cables (Wires) are used to make connections in a computer

6. Other Devices - Other than the above hardware components, a computer also

contains components like Motherboard, CPU (Processor), SMPS, Fans, etc.,

Input Devices
Computer input devices are the physical components of the computer which are used to give

the data given by the user to the computer. Using input devices the user can give the data to

the computer.

Example
Output Devices
Computer output devices are the physical components of the computer which are used to

give the computer result to the User. Using output devices, the user can see the computer-

generated result.

Example
Storage Devices
Computer storage devices are the physical components of the computer which are used to

store data internally or externally.

Example

Device Drives

Computer Device drives are the physical components of the computer which are used to read

and write data on the storage devices.


Example

Computer Cables

In a Computer, various cables are used to make connections among the various hardware

components of the computer.

Example

Other Devices

Other devices of the computer are shown below...

CPU (Processor)
SMPS

CPU Fan (Heat Sink)

Motherboard

How does Computer work?


When a user wants to communicate with the computer, the user interacts with an application.

The application interacts with the operating system, and the operating system makes

hardware components to work according to the user given instructions. The hardware

components send the result back to the operating system, then the operating system

forwards the same to the application and the application shows the result to the user.

By using input devices, the user interacts with the application and the application uses output

devices to show the result. All input and output devices work according to the instructions

given by the operating system.

The working process of a computer is shown in the following figure.

Computing Environments
What is Computing Environment?
When we want to solve a problem using a computer, the computer makes use of various

devices which work together to solve that problem. There may be a various number of ways

to solve a problem. We use the various number of computer devices arranged in different

ways to solve different problems. The arrangement of computer devices to solve a problem

is said to be a computing environment. The formal definition of the computing environment

is as follows.
Computing Environment is a collection of computers which are used to process and

exchange information to solve various types of computing problems.

Types of Computing Environments

The following are the various types of computing environments.

1. Personal Computing Environment

2. Time-Sharing Computing Environment

3. Client-Server Computing Environment

4. Distributed Computing Environment

5. Grid Computing Environment

6. Cluster Computing Environment

Personal Computing Environment


Personal computing is a stand-alone machine. In a personal computing environment, the

complete program resides on the stand-alone machine and executed from the same

machine. Laptops, mobile devices, printers, scanners and the computer systems we use at

home, office are the examples for the personal computing environment.

Time-Sharing Computing Environment


The time-sharing computing environment is a stand-alone computer in which a single user

can perform multiple operations at a time by using a multitasking operating system. Here the

processor time is divided among different tasks and this is called “Time-sharing”. For example,

a user can listen to music while writing something in a text editor. Windows 95 and later

versions of Windows OS, iOS and Linux operating systems are the examples for this

computing environment.

Client-Server Computing Environment


The client-server environment contains two machines (Client machine and Server machine).

These both machines will exchange the information through an application. Here Client is a

normal computer like PC, Tablet, Mobile, etc., and Server is a powerful computer which stores

huge data and manages the huge amount of file and emails, etc., In this environment, client

requests for data and server provides data to the client. In the client-server environment, the

communication between client and server is performed using HTTP (Hyper Text Transfer

Protocol).
Distributed Computing Environment
In the distributed computing environment, the complete functionality of the software is not

on a single computer but is distributed among multiple computers. Here we use a method of

computer processing in which different programs of an application run simultaneously on

two or more computers. These computers communicate with each other over a network to

perform the complete task. In a distributed computing environment, the data is distributed

among different systems and that data is logically related to each other.

Grid Computing Environment

Grid computing is a collection of computers from different locations. All these computers

work for a common problem. A grid can be described as a distributed collection of a large

number of computers working for a single application.

Cluster Computing Environment

Cluster computing is a collection of interconnected computers. These computers work

together to solve a single problem. In a cluster computing environment, a collection of

systems work together as a single system.

Computer Languages
What is Computer Language?
Generally, we use languages like English, Hindi, etc., to make communication between two

persons. That means when we want to make communication between two persons we need

a language through which persons can express their feelings. Similarly, when we want to

make communication between user and computer or between two or more computers we

need a language through which user can give information to the computer and vice versa.

When a user wants to give any instruction to the computer the user needs a specific language

and that language is known as a computer language.

The user interacts with the computer using programs and that programs are created using

computer programming languages like C, C++, Java, etc.,

Computer languages are the languages through which the user can communicate with the

computer by writing program instructions.

Every computer programming language contains a set of predefined words and a set of rules

(syntax) that are used to create instructions of a program.

Computer Languages Classification

Over the years, computer languages have been evolved from Low-Level to High-Level

Languages. In the earliest days of computers, only Binary Language was used to write

programs. The computer languages are classified as follows...

Low-Level Language (Machine Language)


Low-Level language is the only language which can be understood by the computer. Binary

Language is an example of a low-level language. Low-level language is also known as Machine


Language. The binary language contains only two symbols 1 & 0. All the instructions of binary

language are written in the form of binary numbers 1's & 0's. A computer can directly

understand the binary language. Machine language is also known as the Machine Code.

As the CPU directly understands the binary language instructions, it does not require any

translator. CPU directly starts executing the binary language instructions and takes very less

time to execute the instructions as it does not require any translation. Low-level language is

considered as the First Generation Language (1GL).

Advantages

• A computer can easily understand the low-level language.

• Low-level language instructions are executed directly without any translation.

• Low-level language instructions require very less time for their execution.

Disadvantages

• Low-level language instructions are very difficult to use and understand.

• Low-level language instructions are machine-dependent, that means a program

written for a particular machine does not execute on another machine.

• In low-level language, there is more chance for errors and it is very difficult to find

errors, debug and modify.

Middle-Level Language (Assembly Language)

Middle-level language is a computer language in which the instructions are created using

symbols such as letters, digits and special characters. Assembly language is an example of

middle-level language. In assembly language, we use predefined words called mnemonics.

Binary code instructions in low-level language are replaced with mnemonics and operands in

middle-level language. But the computer cannot understand mnemonics, so we use a

translator called Assembler to translate mnemonics into binary language. Assembler is a

translator which takes assembly code as input and produces machine code as output. That

means, the computer cannot understand middle-level language, so it needs to be translated


into a low-level language to make it understandable by the computer. Assembler is used to

translate middle-level language into low-level language.

Advantages

• Writing instructions in a middle-level language is easier than writing instructions in a

low-level language.

• Middle-level language is more readable compared to low-level language.

• Easy to understand, find errors and modify.

Disadvantages

• Middle-level language is specific to a particular machine architecture, that means it is

machine-dependent.

• Middle-level language needs to be translated into low-level language.

• Middle-level language executes slower compared to low-level language.

High-Level Language
A high-level language is a computer language which can be understood by the users. The

high-level language is very similar to human languages and has a set of grammar rules that

are used to make instructions more easily. Every high-level language has a set of predefined

words known as Keywords and a set of rules known as Syntax to create instructions. The high-

level language is easier to understand for the users but the computer cannot understand it.

High-level language needs to be converted into the low-level language to make it

understandable by the computer. We use Compiler or interpreter to convert high-level

language to low-level language.

Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples of high-level

languages. All these programming languages use human-understandable language like

English to write program instructions. These instructions are converted to low-level language

by the compiler so that it can be understood by the computer.

Advantages
• Writing instructions in a high-level language is easier.

• A high-level language is more readable and understandable.

• The programs created using high-level language runs on different machines with little

change or no change.

• Easy to understand, create programs, find errors and modify.

Disadvantages

• High-level language needs to be translated into low-level language.

• High-level language executes slower compared to middle and low-level languages.

Understanding Computer Languages

The following figure provides a few key points related to computer languages.

From the above figure, we can observe the following key points...

• The programming languages like C, C++, Java, etc., are written in High-level language

which is more comfortable for the developers.

• A high-level language is closer to the users.

• Low-level language is closer to the computer. Computer hardware can understand

only the low-level language (Machine Language).

• The program written in the high-level language needs to be converted to low-level

language to make communication between the user and the computer.


• Middle-level language is not closer to both user and computer. We can consider it as

a combination of both high-level language and low-level language.

Creating and Running 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.

Popular programming languages like C, C++, Java, etc., use the compiler to convert high-level

language instructions into low-level language instructions. A compiler is a program that

converts high-level language instructions into low-level language instructions. Generally, the

compiler performs two things, first it verifies the program errors, if errors are found, it returns

a list of errors otherwise it converts the complete code into the low-level language.

To create and execute C programs in the Windows Operating System, we need to install Turbo

C software. We use the following steps to create and execute C programs in Windows OS…

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

• 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.

The compilation is the process of converting high-level language instructions into low-level

language instructions.

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 3: Executing / Running Executable File (Ctrl + F9)


After completing compilation successfully, an executable file is created with a .exe extension.

The processor can understand this .exe file content so that it can perform the task specified

in the source file.


We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file

is submitted to the CPU. On receiving .exe file, CPU performs the task according to the

instruction written in the file. The result generated from the execution is placed in a window

called User Screen.

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

When we execute a C program it undergoes with the following process…

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 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.

Program Development Life Cycle


When we want to develop a program using any programming language, we follow a sequence

of steps. These steps are called phases in program development. The program development

life cycle is a set of steps or phases that are used to develop a program in any programming
language.

Generally, the program development life cycle contains 6 phases, they are as follows….

• Problem Definition

• Problem Analysis

• Algorithm Development

• Coding & Documentation

• Testing & Debugging

• Maintenance

1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the problem.

In this phase we need to understand the problem statement, what is our requirement, what

should be the output of the problem solution. These are defined in this first phase of the

program development life cycle.

2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem.

That means we gather the required resources to solve the problem defined in the problem

definition phase. We also determine the bounds of the solution.

3. Algorithm Development

During this phase, we develop a step by step procedure to solve the problem using the

specification given in the previous phase. This phase is very important for program

development. That means we write the solution in step by step statements.

4. Coding & Documentation

This phase uses a programming language to write or implement the actual programming

instructions for the steps defined in the previous phase. In this phase, we construct the actual

program. That means we write the program to solve the given problem using programming

languages like C, C++, Java, etc.,

5. Testing & Debugging

During this phase, we check whether the code written in the previous step is solving the

specified problem or not. That means we test the program whether it is solving the problem

for various input data values or not. We also test whether it is providing the desired output

or not.

6. Maintenance

During this phase, the program is actively used by the users. If any enhancements found in

this phase, all the phases are to be repeated to make the enhancements. That means in this

phase, the solution (program) is used by the end-user. If the user encounters any problem or
wants any enhancement, then we need to repeat all the phases from the starting, so that the

encountered problem is solved or enhancement is added.

C Background
C is a structured programming language. It is also known as function orientated programming

language. C programming language was developed in the year of 1972 by Dennis Ritchie at

Bell Laboratories in the USA (AT & T).

In the year of 1968, research was started by Dennis Ritchie on programming languages like

BCPL, CPL. The main aim of his research was to develop a new language to create an OS called

UNIX. After four years of research, a new programming language was created with solutions

for drawbacks in languages like BCPL & CPL. In the year of 1972, the new language was

introduced with the name “Traditional C”.

The name 'c' was selected from the sequence of previous language ‘B’ (BCPL) because most

of the features of 'c' were derived from BCPL (B language).

The first outcome of the c language was the UNIX operating system. The initial UNIX OS was

completely developed using 'c' programming language.

The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and also “Father of

UNIX”.

The c programming language is very popular because it is reliable, simple and easy to use and

it is the base for almost all the other programming languages.


The following are the language before ‘c’ & various versions of ‘c’.

1. CPL (Common Programming Language)

The CPL was invented by Martin Richards at the University of Cambridge in the early of 1960s.

2. BCPL (Basic Combined Programming Language)

The BCPL was invented by Martin Richards at the University of Cambridge in the year of 1966.

It was a popular programming language at that time. BCPL allows the user, direct access to

the computer memory. BCPL is the extension of CPL.

3. B Language

B language is derived from BCPL. It was introduced in the year of 1969 by Ken

Thompson and Dennis Ritchie at Bell Laboratory, USA. The B language is similar to BCPL.

4. C Language

C language is derived from the B language. It was introduced in the year of 1972 by Dennis

Ritchie at Bell Laboratory, USA. The C language was mainly developed to create an operating

system called UNIX. The name C is given based on the previous language B and BCPL. Ninety

percent of the UNIX operating system code is written in C language. During the 1970s, the C

language became a very popular programming language. Many universities and

organizations began creating their version of C language for their respective projects. So, C

language has got many variants at that time. Later it was standardized.

5. ANSI C (C89)

In the year of 1983, the ANSI (American National Standards Institute) formed a committee to

frame standard specifications for the C language. In the year of 1989, this committee

introduced a standard version of C with the name "ANSI C" with standard library files. The

ANSI C is also called as C89 in short form.

6. C90

In the year of 1990, the ANSI C was got ISO (International Organization for Standardization)

standardization with the inclusion of a few new features like new library files, new processor
commands. And it was also added with keywords const, volatile and signed, etc... ISO

standardized ANSI C as ISO/IEC 9899:1990. This version is called as C90 in short form.

7. C99

In the year of 1995, many new features were added to the C90 to create a new version of it.

This new version of C was got ISO standardization in the year of 1999 with the name ISO/IEC

9899:1999. In the short form, it is called as C99. Later C99 became the official standard version

of C.

C Program Basics
C is a structured programming language. Every c program and its statements must be in a

particular structure. Every c program has the following general structure...

Line 1: Comments - They are ignored by the compiler

This section is used to provide a small description of the program. The comment lines are

simply ignored by the compiler, that means they are not executed. In C, there are two types

of comments.

1. Single Line Comments: Single line comment begins with // symbol. We can write any

number of single line comments.

2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends

with */. We can write any number of multiple lines comments in a program.
In a C program, the comment lines are optional. Based on the requirement, we write

comments. All the comment lines in a C program just provide the guidelines to understand

the program and its code.

Line 2: Preprocessing Commands

Preprocessing commands are used to include header files and to define constants. We use

the #include statement to include the header file into our program. We use

a #define statement to define a constant. The preprocessing statements are used according

to the requirements. If we don't need any header file, then no need to write #include

statement. If we don't need any constant, then no need to write a #define statement.

Line 3: Global Declaration

The global declaration is used to define the global variables, which are common for all the

functions after its declaration. We also use the global declaration to declare functions. This

global declaration is used based on the requirement.

Line 4: int main()

Every C program must write this statement. This statement (main) specifies the starting point

of the C program execution. Here, main is a user-defined method which tells the compiler

that this is the starting point of the program execution. Here, int is a data type of a value that

is going to return to the Operating System after completing the main method execution. If we

don't want to return any value, we can use it as void.

Line 5: Open Brace ( { )

The open brace indicates the beginning of the block which belongs to the main method. In C

program, every block begins with a '{' symbol.

Line 6: Local Declaration

In this section, we declare the variables and functions that are local to the function or block

in which they are declared. The variables which are declared in this section are valid only

within the function or block in which they are declared.

Line 7: Executable statements


In this section, we write the statements which perform tasks like reading data, displaying the

result, calculations, etc., All the statements in this section are written according to the

requirements.

Line 9: Closing Brace ( } )

The close brace indicates the end of the block which belongs to the main method. In C

program every block ends with a '}' symbol.

Line 10, 11, 12, ...: User-defined function()

This is the place where we implement the user-defined functions. The user-defined function

implementation can also be performed before the main method. In this case, the user-

defined function need not be declared. Directly it can be implemented, but it must be before

the main method. In a program, we can define as many user-defined functions as we want.

Every user-defined function needs a function call to execute its statements.

General rules for any C program

1. Every executable statement must end with a semicolon symbol (;).

2. Every C program must contain exactly one main method (Starting point of the program

execution).

3. All the system-defined words (keywords) must be used in lowercase letters.

4. Keywords cannot be used as user-defined names(identifiers).

5. For every open brace ({), there must be respective closing brace (}).

6. Every variable must be declared before it is used.

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

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.,

Every character in C language has its equivalent ASCII (American Standard Code for

Information Interchange) value.


Commonly used characters in C with thier ASCII values

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();
return 0;
}

C Tokens
Every C program is a collection of instructions and every instruction is a collection of some

individual units. Every smallest individual unit of a c program is called token. Every instruction

in a c program is a collection of tokens. Tokens are used to construct c programs and they are

said to the basic building blocks of a c program.

In a c program tokens may contain the following...

1. Keywords

2. Identifiers

3. Operators

4. Special Symbols

5. Constants

6. Strings

7. Data values

In a C program, a collection of all the keywords, identifiers, operators, special symbols,

constants, strings, and data values are called tokens.

Consider the following C program...

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();
return 0;
}

In the above program there are 22 tokens.

C Keywords
As every language has words to construct statements, C programming also has words with a

specific meaning which are used to construct c program instructions. In the C programming

language, keywords are special words with predefined meaning. Keywords are also known as

reserved words in C programming language.

In the C programming language, there are 32 keywords. All the 32 keywords have their

meaning which is already known to the compiler.

Keywords are the reserved words with predefined meaning which already known to the

compiler

Whenever C compiler come across a keyword, automatically it understands its meaning.

Properties of Keywords

1. All the keywords in C programming language are defined as lowercase letters so they

must be used only in lowercase letters

2. Every keyword has a specific meaning, users can not change that meaning.

3. Keywords can not be used as user-defined names like variable, functions, arrays,

pointers, etc...

4. Every keyword in C programming language represents something or specifies some

kind of action to be performed by the compiler.

The following table specifies all the 32 keywords with their meaning...
C Identifiers
In C programming language, programmers can specify their name to a variable, array, pointer,

function, etc... An identifier is a collection of characters which acts as the name of variable,

function, array, pointer, structure, etc... In other words, an identifier can be defined as the

user-defined name to identify an entity uniquely in the c programming language that name

may be of the variable name, function name, array name, pointer name, structure name or a

label.

The identifier is a user-defined name of an entity to identify it uniquely during the program

execution

Example

int marks;

char studentName[30];

Here, marks and studentName are identifiers.

Rules for Creating Identifiers

1. An identifier can contain letters (UPPERCASE and

lowercase), numerics & underscore symbol only.

2. An identifier should not start with a numerical value. It can start with a letter or an

underscore.

3. We should not use any special symbols in between the identifier even whitespace.

However, the only underscore symbol is allowed.

4. Keywords should not be used as identifiers.

5. There is no limit for the length of an identifier. However, the compiler considers the

first 31 characters only.

6. An identifier must be unique in its scope.

Rules for Creating Identifiers for better programming

The following are the commonly used rules for creating identifiers for better programming...

1. The identifier must be meaningful to describe the entity.


2. Since starting with an underscore may create conflict with system names, so we avoid

starting an identifier with an underscore.

3. We start every identifier with a lowercase letter. If an identifier contains more than

one word then the first word starts with a lowercase letter and second word onwards

first letter is used as an UPPERCASE letter. We can also use an underscore to separate

multiple words in an identifier.

C 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...

The Data type is a set of value with predefined characteristics. data types are used to

declare variable, constants, arrays, pointers, and functions.

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

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.

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.

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.

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

C Variables
Variables in a c programming language are the named memory locations where the user can

store different values of the same datatype during the program execution. That means a

variable is a name given to a memory location in which we can store different values of the

same data type. In other words, a variable can be defined as a storage container to hold values

of the same datatype during the program execution. The formal definition of a data type is as

follows...

Variable is a name given to a memory location where we can store different values of the

same datatype during the program execution.

Every variable in c programming language must be declared in the declaration section before

it is used. Every variable must have a datatype that determines the range and type of values

be stored and the size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol. The following are the

rules to specify a variable name...

1. Variable name should not start with a digit.

2. Keywords should not be used as variable names.

3. A variable name should not contain any special symbols except underscore(_).

4. A variable name can be of any length but compiler considers only the first 31

characters of the variable name.

Declaration of Variable

Declaration of a variable tells the compiler to allocate the required amount of memory with

the specified variable name and allows only specified datatype values into that memory

location. In C programming language, the declaration can be performed either before the

function as global variables or inside any block or function. But it must be at the beginning of

block or function.

Declaration Syntax:

datatype variableName;

Example
int number;

The above declaration tells to the compiler that allocates 2 bytes of memory with the

name number and allows only integer values into that memory location.

C Constants
In C programming language, 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.

In C programming language, a constant can be of any data type like integer, floating-point,

character, string and double, etc.,

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.

Character Constants

A character constant is a symbol enclosed in single quotation. A character constant has a

maximum length of one character.

Example

'A'

'2'

'+'

In the C programming language, there are some predefined character constants called escape

sequences. Every escape sequence has its own special functionality and every escape

sequence is prefixed with '\' symbol. These escape sequences are used in output function

called 'printf()'.

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 btechppsclass"
We can define string constant using multiple lines as follows...

" This\is\btechppsclass "

We can also define string constant by separating it with white space as follows...

"This" "is" "btechppsclass"

All the above three defines the same string constant.

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 ;

Example

const int x = 10 ;

Here, 'x' is a integer constant with fixed value 10.

Example Program
#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 ) ;

The above program gives an error because we are trying to change the constant variable

value (x = 100).

Using '#define' preprocessor


We can also create constants using '#define' preprocessor directive. When we create constant

using this preprocessor directive it must be defined at the beginning of the program (because

all the preprocessor directives must be written before the global declaration).

We use the following syntax to create constant using '#define' preprocessor directive...

#define CONSTANTNAME value

Example

#define PI 3.14

Here, PI is a constant with value 3.14

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

#defien PI 3.14

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) ;


}

C Storage Classes
In C programming language, storage classes are used to define things like storage

location (whether RAM or REGISTER), scope, lifetime and the default value of a variable.

In the C programming language, the memory of variables is allocated either in computer

memory (RAM) or CPU Registers. The allocation of memory depends on storage classes.

In C programming language, there are FOUR storage classes and they are as follows...

1. auto storage class

2. extern storage class

3. static storage class

4. register storage class

auto storage class

The default storage class of all local variables (variables declared inside block or function) is

auto storage class. Variable of auto storage class has the following properties...

Property Description

Keyword Auto

Storage Computer Memory (RAM)

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is define

Example Program 1
#include<stdio.h>
#include<conio.h>
int main(){
int i;
auto char c;
float f;
printf("i = %d\tc = %c\tf = %f",i,c,f);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>

int main(){
int a=10;
{
int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}

Example Program 3
#include<stdio.h>
#include<conio.h>

int main(){
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}

External storage class

The default storage class of all global varibles (variables declared outside function) is external

storage class. Variable of external storage class has the following properties...
Property Description

Keyword Extern

Storage Computer Memory (RAM)

Default Value Zero

Scope Global to the program (i.e., Throughout the program)

Life time As long as the program’s execution does not comes to end

Example Program 1
#include<stdio.h>
#include<conio.h>

int i; //By default it is extern variable


int main(){
printf("%d",i);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>

extern int i; //extern variable


int main(){
printf("%d",i);
return 0;
}

Static storage class


The static storage class is used to create variables that hold value beyond its scope until the

end of the program. The static variable allows to initialize only once and can be modified any

number of times. Variable of static storage class has the following properties...

Property Description

Keyword Static

Storage Computer Memory (RAM)

Default Value Zero

Scope Local to the block in which the variable is defined

Life time The value of the persists between different function calls (i.e., Initializatio

Example Program 1
#include<stdio.h>
#include<conio.h>

static int a;
int main(){
printf("%d",a);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>

static int i=10;


int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}
Register storage class
The register storage class is used to specify the memory of the variable that has to be

allocated in CPU Registers. The memory of the register variable is allocated in CPU Register

but not in Computer memory (RAM). The register variables enable faster accessibility

compared to other storage class variables. As the number of registers inside the CPU is very

less we can use very less number of register variables. Variable of register storage class has

the following properties...

Property Description

Keyword Register

Storage CPU Register

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is define

Example Program 1
#include<stdio.h>
#include<conio.h>

int main(){
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}

The following table provides detailed properties of all storage classes...


Storage Default
Class Keyword Memory Location Value Scope

Automatic auto Computer Garbage Local to the block in which the


Memory (RAM) Value variable has defined

External extern Computer Zero Global to the program (i.e.,


Memory (RAM) Throughout the program)

Static static Computer Zero Local to the block in which the


Memory (RAM) variable has defined

Register register CPU Register Garbage Local to the block in which the
Value variable has defined

C Output Functions
C programming language provides built-in functions to perform output operation. The output

operations are used to display data on user screen (output screen) or printer or any file. The

c programming language provides the following built-in output functions...

1. printf()

2. putchar()

3. puts()

4. fprintf()

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". When we want to use printf() function in our program we need

to include the respective header file (stdio.h) using the #include statement. The printf()

function has the following syntax...

Syntax:
printf("message to be display!!!");
Example Program
#include<stdio.h>
#include<conio.h>
void main(){

printf("Hello! Welcome to btechsmartclass!!!");

Output:

In the above example program, we used the printf() function to print a string on to the output

screen.

The printf() function is also used to display data values. When we want to display data values

we use format string of the data value to be displayed.

Syntax:

printf("format string",variableName);
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);

Output:
In the above example program, we used the printf() function to print data values of variables

i and x on to the output screen. Here i is a an integer variable so we have used format string

%d and x is a float variable so we have used format string %f.

The printf() function can also be used to display string along with data values.

Syntax:

printf("String format string",variableName);


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

void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);

Output:

In the above program, we are displaying string along with data values.

Every function in the C programming language must have a return value. The printf() function

also have an integer as a return value. The printf() function returns an integer value equivalent

to the total number of characters it has printed.

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);

Output:

In the above program, first printf() function printing "btechsmartclass" which is of 15

characters. So it returns integer value 15 to the variable "i". The value of "i" is printed in the

second printf() function.

Formatted printf() function

Generally, when we write multiple printf() statements the result is displayed in a single line

because the printf() function displays the output in a single line. Consider the following

example program...

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

void main(){
printf("Welcome to ");
printf("btechsmartclass ");
printf("the perfect website for learning");

Output:

In the above program, there are 3 printf() statements written in different lines but the output

is displayed in single line only.


To display the output in different lines or as we wish, we use some special characters

called escape sequences. Escape sequences are special characters with special functionality

used in printf() function to format the output according to the user requirement. In the C

programming language, we have the following escape sequences...

Escape sequence Meaning

\n Moves the cursor to New Line

\t Inserts Horizontal Tab (5 characters space)

\v Inserts Vertical Tab (5 lines space)

\a Beep sound

\b Backspace (removes the previous character from its current p

\\ Inserts Backward slash symbol

\? Inserts Question mark symbol

\' Inserts Single quotation mark symbol

\" Inserts Double quotation mark symbol

Consider the following example program...

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

void main(){
printf("Welcome to\n");
printf("btechsmartclass\n");
printf("the perfect website for learning");
}

Output:

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. This function is used to print only a single character. To print

multiple characters we need to write multiple times or use a looping statement. Consider the

following example program...

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

void main(){
char ch = 'A';
putchar(ch);

Output:

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. Consider the following example program...

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

Output:

fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used to print a

line into the file. When you want to use fprintf() function the file must be opened in writting

mode.

C Input Functions
C programming language provides built-in functions to perform input operations. The input

operations are used to read user values (input) from the keyboard. The c programming

language provides the following built-in input functions.

1. scanf()

2. getchar()

3. getch()

4. gets()

5. fscanf()

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".
When we want to use scanf() function in our program, we need to include the respective

header file (stdio.h) using #include statement. The scanf() function has the following syntax...

Syntax:

scanf("format strings",&variableNames);
Example Program
#include<stdio.h>
#include<conio.h>

void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);

Output:

In the above example program, we used the scanf() function to read an integer value from

the keyboard and store it into variable 'i'.

The scanf function also used to read multiple data values of different or the same data types.

Consider the following example program...

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

void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);

Output:

In the above example program, we used the scanf() function to read one integer value and

one float value from the keyboard. Here 'i' is an integer variable so we have used format string

%d, and 'x' is a float variable so we have used format string %f.

The scanf() function returns an integer value equal to the total number of input values read

using scanf function.

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

void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);

Output:

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. To read multiple characters we need

to write multiple times or use a looping statement. Consider the following example program...

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

void main(){
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);

Output:

getch() function

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. To read multiple characters we need to write multiple times or use a looping

statement. Consider the following example program...

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

void main(){
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);
}

Output:

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.

Consider the following example program...

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

void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}

Output:

fscanf() function
The fscanf() function is used with the concept of files. The fscanf() function is used to read

data values from a file. When you want to use fscanf() function the file must be opened in

reading mode.

C Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. 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

+ Addition

- Subtraction

* Multiplication

/ Division

% Remainder of the Division


⇒ 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, it performs concatination (appending).

⇒ The remainder of the division operator is used with integer data type only.

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.

Operator Meaning

< Returns TRUE if the first value is smaller than second value otherwise returns FA

> Returns TRUE if the first value is larger than second value otherwise returns FAL

<= Returns TRUE if the first value is smaller than or equal to second value otherwise

>= Returns TRUE if the first value is larger than or equal to second value otherwise

== Returns TRUE if both values are equal otherwise returns FALSE

!= Returns TRUE if both values are not equal otherwise returns FALSE

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.


Operator Meaning

&& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE

! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it 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.

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. 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.

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

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

j = ++i; // Pre-Increment

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

Output:

Post-Increment or Post-Decrement

In the case of post-increment, the value of the variable is increased by one after the

expression evaluation. In the case of post-decrement, the value of the variable is decreased

by one after the expression evaluation. That means, 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.

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

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

j = i++; // Post-Increment

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

Output:

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

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

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

+= Add both left and right-hand side values and store the result into left-hand side

-= Subtract right-hand side value from left-hand side variable value and store the r
into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and store the re
into left-hand side variable

/= Divide left-hand side variable value with right-hand side variable value and store
into the left-hand side variable
Operator Meaning

%= Divide left-hand side variable value with right-hand side variable value and store
into the left-hand side variable

Bitwise Operators (&, |, ^, ~, >>, <<)

The bitwise operators are used to perform bit-level operations in the c programming

language. When we use the bitwise operators, the operations are performed based on the

binary values. The following table describes all the bitwise operators in the C programming

language.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1

~ the result of Bitwise once complement is negation of the bit (Flipping)

<< the Bitwise left shift operator shifts all the bits to the left by the specified numbe

>> the Bitwise right shift operator shifts all the bits to the right by the specified num
Conditional Operator (?:)

The conditional operator is also called a ternary operator because it requires three operands.

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 ? TRUE Part : FALSE Part;

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.


Dot operator (.)

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

C Expressions
What is an expression?
In any programming language, if we want to perform any calculation or to frame any condition

etc., we use a set of symbols to perform the task. These set of symbols makes an expression.

In the C programming language, an expression is defined as follows.

An expression is a collection of operators and operands that represents a specific value.

In the above definition, an operator is a symbol that performs tasks like arithmetic

operations, logical operations, and conditional operations, etc.

Operands are the values on which the operators perform the task. Here operand can be a

direct value or variable or address of memory location.

Expression Types in C

In the C programming language, expressions are divided into THREE types. They are as

follows...

1. Infix Expression

2. Postfix Expression

3. Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression

The expression in which the operator is used between operands is called infix expression.

The infix expression has the following general structure.

Operand1 Operator Operand2

Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.

The postfix expression has the following general structure.

Operand1 Operand2 Operator

Example

Prefix Expression

The expression in which the operator is used before operands is called a prefix expression.

The prefix expression has the following general structure.

Operator Operand1 Operand2

Example
C Operator Precedence and
Associativity
What is 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.

What is 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.

In c programming language the operator precedence and associativity are as shown in the

following table.

Precedence Operator Operator Meaning

1 () function call
[] array reference
-> structure member access
. structure member access
Precedence Operator Operator Meaning

2 ! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion

3 * multiplication
/ division
% remainder

4 + addition
- subtraction

5 << left shift


>> right shift

6 < less than


<= less than or equal to
> greater than
>= greater than or equal to

7 == equal to
!= not equal to

8 & bitwise AND

9 ^ bitwise EXCLUSIVE OR

10 | bitwise OR
Precedence Operator Operator Meaning

11 && logical AND

12 || logical OR

13 ?: conditional operator

14 = assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
-= assign subtraction
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

15 , separator

In the above table, the operator precedence decreases from top to bottom and increases

from bottom to top.

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.

An expression is evaluated based on the precedence and associativity of the operators in

that expression.

To understand expression evaluation in c, let us consider the following simple example

expression...
10 + 4 * 3 / 2

In the above expression, there are three operators +, * and /. Among these three operators,

both multiplication and division have the same higher precedence and addition has lower

precedence. So, according to the operator precedence both multiplication and division are

evaluated first and then the addition is evaluated. As multiplication and division have the

same precedence they are evaluated based on the associativity. Here, the associativity of

multiplication and division is left to right. So, multiplication is performed first, then division

and finally addition. So, the above expression is evaluated in the order of * / and +. It is

evaluated as follows...

4 * 3 ====> 12

12 / 2 ===> 6

10 + 6 ===> 16

The expression is evaluated to 16.

Type Casting and Conversion in C


In a programming language, the expression contains data values of the same datatype or

different data types. When the expression contains similar datatype values then it is evaluated

without any problem. But if the expression contains two or more different datatype values

then they must be converted to the single datatype of destination datatype. Here, the

destination is the location where the final result of that expression is stored. For example, the

multiplication of an integer data value with the float data value and storing the result into a

float variable. In this case, the integer value must be converted to float value so that the final

result is a float datatype value.


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

follows...

1. Type Conversion

2. Type Casting

Type Conversion

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.

For example, in c programming language, when we assign an integer value to a float variable

the integer value automatically gets converted to float value by adding decimal value 0. And

when a float value is assigned to an integer variable the float value automatically gets

converted to an integer value by removing the decimal value. To understand more about type

conversion observe the following...

int i = 10 ;

float x = 15.5 ;

char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

Example Program
#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);

Output:

In the above program, we assign i = x, i.e., float variable value is assigned to the integer

variable. Here, the compiler automatically converts the float value (90.99) into integer value

(90) by removing the decimal part of the float value (90.99) and then it is assigned to variable i.

Similarly, when we assign x = i, the integer value (90) gets converted to float value (90.000000)

by adding zero as the decimal part.

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. To perform this we use the unary cast operator. 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.

(TargetDatatype) DataValue

Example

int totalMarks = 450, maxMarks = 600 ;

float average ;

average = (float) totalMarks / maxMarks * 100 ;


In the above example code, both totalMarks and maxMarks are integer data values. When we

perform totalMarks / maxMarks the result is a float value, but the destination (average)

datatype is a float. So we use type casting to convert totalMarks and maxMarks into float data

type.

You might also like