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

Unit 1 Notes Autonomous

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

Matrusri Engineering College

Programming for problem solving

Academic Year:2023-24 (I-Semester)


Unit – I

Fundamentalsof computers: Components of a computer system, Operating system, Computer


Languages, Number systems: decimal, binary, octal, hexa decimal systems. algorithm,Flowchart,
Pseudo codes with examples

Introduction to C Programming: C Language evolution, Structure and execution of a C


program, execution phases, Compiler. Interpreter, Linker, Loaders, Tokens, Expressions and
evaluation

Statements: Declaration, Assignment statements, Standard I/O statements, Type conversions

INTRODUCTION TO COMPUTERS:

Basic Definitions:

Data: it is a collection of raw facts.

Information: it is a processed data(meaningful data). It is the result of processing the


data.

Input: the data and information entering (given by user) into a computer.

Output: the resultant information obtained by a computer.

Instruction: It is to process the given data.


Program: is a sequence of instructions that can be executed by the computer to solve the given
problem.

Computer:

The term computer is derived from the latin word “compute” which means to calculate or to
manipulate. A Computer is an electronic device capable of performing computations and making
logical decisions at speeds millions and even billions of times faster than human beings can.

Basically computer is an electronic device which takes input from the user processes the
given data and produces the output.

COMPUTER : A computer is a electronic device which accepts data as input, process it according to
instructions given, and displays the output.

CAPABILITIES OF A COMPUTER

1. HUGE DATA STORAGE:-a computer can store any amount of data and instructions in
its memory.
2. INPUT AND OUTPUT: a computer receives data and instructions from the user and
displays it after the execution.
3. PROCESSING: it process the data entered by the user.

BLOCK DIAGRAM OF COMPUTER :


1.Input

 All the data received by the computer goes through the input unit. The input unit
comprises different devices like a mouse, keyboard, scanner, etc.
 In other words, each of these devices acts as a mediator between the users and the
computer.
 The data that is to be processed is put through the input unit.
 The computer accepts the raw data in binary form. It then processes the data and
produces the desired output.
The 3 major functions of the input unit are-
 Take the data to be processed by the user.
 Convert the given data into machine-readable form.
 And then, transmit the converted data into the main memory of the computer. The sole
purpose is to connect the user and the computer. In addition, this creates easy
communication between them.

2. CENTRAL PROCESSING UNIT:


Central Processing Unit or the CPU, is the brain of the computer. It works the same way a human
brain works. As the brain controls all human activities, similarly the CPU controls all the tasks.
Moreover, the CPU conducts all the arithmetical and logical operations in the computer.
Now the CPU comprises of two units, namely – ALU (Arithmetic Logic Unit) and CU (Control
Unit). Both of these units work in sync. The CPU processes the data as a whole.
Let us see what particular tasks are assigned to both units.

ALU – Arithmetic Logic Unit


The Arithmetic Logic Unit is made of two terms, arithmetic and logic. There are two primary
functions that this unit performs.
1. Data is inserted through the input unit into the primary memory. Performs the basic arithmetical
operation on it. Like addition, subtraction, multiplication, and division. It performs all sorts of
calculations required on the data. Then sends back data to the storage.
2. The unit is also responsible for performing logical operations like AND, OR, Equal to, Less than,
etc. In addition to this it conducts merging, sorting, and selection of the given data.

CU – Control Unit
The control unit as the name suggests is the controller of all the activities/tasks and operations.
All this is performed inside the computer.
The memory unit sends a set of instructions to the control unit. Then the control unit in turn
converts those instructions. After that these instructions are converted to control signals.

These control signals help in prioritizing and scheduling activities. Thus, the control unit
coordinates the tasks inside the computer in sync with the input and output units.

Memory Unit
All the data that has to be processed or has been processed is stored in the memory unit. The
memory unit acts as a hub of all the data. It transmits it to the required part of the computer
whenever necessary.
The memory unit works in sync with the CPU.
This helps in faster accessing and processing of the data.
Thus making tasks easier and quicker.

There are two types of computer memory-


1. Primary memory – This type of memory cannot store a vast amount of data. Therefore,
it is only used to store recent data. The data stored in this is temporary. It can get erased
once the power is switched off. Therefore, is also called temporary memory or main
memory.

RAM stands for Random Access Memory. It is an example of primary memory. This
memory is directly accessible by the CPU. It is used for reading and writing purposes.
For data to be processed, it has to be first transferred to the RAM and then to the CPU.

2. Secondary memory – As explained above, the primary memory stores temporary data.
Thus it cannot be accessed in the future. For permanent storage purposes, secondary
memory is used. It is also called permanent memory or auxiliary memory. The hard disk
is an example of secondary memory. Even in a power failure data does not get erased
easily.

Output
There is nothing to be amazed by what the output unit is used for.
All the information sent to the computer once processed is received by the user through the
output unit.
Devices like printers, monitors, projectors, etc. all come under the output unit.
The output unit displays the data either in the form of a soft copy or a hard copy. The printer is
for the hard copy. The monitor is for the display. The output unit accepts the data in binary form
from the computer. It then converts it into a readable form for the user.

COMPONENTS OF COMPUTER :

The major components of computer are HARDWARE&SOFTWARE.

HARDWARE:

It is a general term used to represent the physical and tangible components of the computer itself i.e. those
components which can be touched and seen. It includes
(1) Input devices
(2) Output devices
(3) Central processing Unit
(4) Storage devices

SOFTWARE:

It is a general term to describe all the forms of programs associated with a computer. Without
software, a computer is like a human body with out a soul.

It is a general term to describe all the forms of programs associated with a computer. Without
software, a computer is like a human body without a soul.

The classifications of software are :-

 System software
 Application software

System software includes :-

i) Operating system
ii) Language Translators

OPERATING SYSTEMis the interface between the user and the computer hardware.

Ex: MS-DOS, Solaris ,Unix , Linux.

LANGUAGE TRANSLATOR is a software that accepts input in one language and convert them into
another language.

The types of translators are :

 Compiler
 Assembler
 Interpreter

Application software is a set of programs that allows the computer to help users in solving problems.

Ex:- MS-OFFICE

Operating system

An operating system acts as an interface between the software and different parts of
the computer or the computer hardware. The operating system is designed in such a
way that it can manage the overall resources and operations of the computer.

Examples of Operating Systems are Windows, Linux, Mac OS, etc.

Functions of the Operating System


 Resource Management: The operating system manages and allocates memory, CPU
time, and other hardware resources among the various programs and processes running
on the computer.
 Process Management: The operating system is responsible for starting, stopping, and
managing processes and programs. It also controls the scheduling of processes and
allocates resources to them.
 Memory Management: The operating system manages the computer’s primary
memory and provides mechanisms for optimizing memory usage.
 Security: The operating system provides a secure environment for the user,
applications, and data by implementing security policies and mechanisms such as
access controls and encryption.
 File Management: The operating system is responsible for organizing and managing
the file system, including the creation, deletion, and manipulation of files and
directories.
 Device Management: The operating system manages input/output devices such as
printers, keyboards, mice, and displays. It provides the necessary drivers and interfaces
to enable communication between the devices and the computer.
 Networking: The operating system provides networking capabilities such as
establishing and managing network connections, handling network protocols, and
sharing resources such as printers and files over a network.
Types of Operating Systems
 Single-User Operating Systems: Single-User Operating Systems are designed to
support a single user at a time.
Examples include Microsoft Windows for personal computers and Apple macOS.
 Multi-User Operating Systems: Multi-User Operating Systems are designed to
support multiple users simultaneously.
Examples include Linux and Unix.
 Embedded Operating Systems: Embedded Operating Systems are designed to run on
devices with limited resources, such as smartphones, wearable devices, and household
appliances.
Examples include Google’s Android and Apple’s iOS.
 Batch Operating System: A Batch Operating System is a type of operating system that
does not interact with the computer directly. There is an operator who takes similar jobs
having the same requirements and groups them into batches.
 Time-sharing Operating System: Time-sharing Operating System is a type of
operating system that allows many users to share computer resources (maximum
utilization of the resources).
 Distributed Operating System: Distributed Operating System is a type of operating
system that manages a group of different computers and makes appear to be a single
computer. These operating systems are designed to operate on a network of computers.
They allow multiple users to access shared resources and communicate with each other
over the network.
Examples include Microsoft Windows Server and various distributions of Linux designed
for servers.
 Network Operating System: Network Operating System is a type of operating system
that runs on a server and provides the capability to manage data, users, groups, security,
applications, and other networking functions.

TYPES OF PROGRAMMING LANGUAGES

 A language is meant for communication purpose

 Natural language like English, Hindi, Telugu etc., are generally used by human beings to
communicate with each other.

 With these languages we can express or exchange our ideas, feelings and emotions.

 Similarly a computer language is used for communication between human being and the computer.

A program language can be defined as a language used for expressing a set of computer instructions
called program
MACHINE LANGUAGE

Machine language instruction format consist of two parts:

OP code and operand

OP CODE OPERAND

(OPERATION CODE) (ADDRESS/LOCATION)

Ex:

OP CODE ADDRESS MEANING

00000101 00010101 transfer contents of memory location 25 to accumulator

00000001 00010110 add contents of memory location 26 to accumulator

00000110 00010111 transfer contents of memory location 27 to accumulator


Advantages of machine Language:

1.Computer understands only the machine language

2.Programs run very fast

Limitations of Machine Language:

1.Programmer has to remember the following

a)Binary equivalent to the OP code

b)Binary address of the memory location being used

2.Programmer written in machine language are very lengthy

3.Difficult to correct /modify programs

4.Machine language is machine dependent. That is program written for a particular computer has
to be changed for using on a different computer.

ASSEMBLY LEVEL LANGUAGE:

Each instruction of assembly level language contains

a) symbolic operation code and


b) symbolic address

Ex:

ADD is mnemonic op code for addition

SUB is mnemonic op code for subtraction


LOAD is mnemonic op code for loading

STORE is mnemonic op code for storing

Suppose to add two number stored in locations B and C and store the result in storage
location D

assemble language program as follows:

LOAD B load the contents of B into accumulator

ADD C add the contents of C to accumulator

STORE D store the result (contents of accumulator )into storage location D

Advantages of assembly Language:

1.No need of remembering all binary OP codes and address of memory location

2.Program correction /modification is relatively easier

3.Less time is required in writing a program than machine language

4.Language is simple when compared with machine language

Limitations of assembly Language:

1.Execution of program takes more time as it has to be converted into machine language

2.Assembly language is machine dependent.

HIGH LEVEL LANGUAGES(HLL)


These are English like languages that are close to our native language.

Ex: BASIC, COBOL, FORTAN, PASCAL, C etc.,

Suppose to add two number stored in locations B and C and store the result in storage
location D

Pascal : D:=B+C;

Cobol : ADD B to C GIVING D

C : D=B+C

Advantages of High level Language:

1.The High level Language are easier to use and understand than the machine languages and the
assembly language

2.A High level Language is more expensive than the low level language and hence the programs
written in HLL are much more compact and self explanatory than their low level counterparts

3. High level Language are provide a better documentation than low level languages.

4. High level Language are machine independent

5. 2.Program correction /modification is much easier than low level languages.

Limitations of High level Language:

1.Less efficient as they take more execution time when compared to low level languages

2.The programmer cannot completely connect the total power available at hardware level .
ASSEMBLER, COMPILER AND INTERPRETER

If the program written in a language other than machine language of computer,the the computer
cannot understand it. Hence , the programs written in other languages must be translated into the
machine language of the computer before they executed . The translation process can be done
through a special software (system program) known as language processors.

The language processor are of 3 types

1. ASSEMBLER 2. COMPILER 3. INTERPRETER.

Assembler

An assembler is program which translates an assembly language program into the machine
language. It gives one machine language instruction for each assembly language instruction. It
also produces error messages .

Ex: 8085 assembler,8086 assembler

1. Compiler

A compiler is a program which translates a high level language program into machine language
of the host computer. It translates all the instructions of HLL program at a time. A compiler also
produces the error messages that occurs during translation. Once a program is error free , then
the compiled software is not needed in the memory because the machine code itself can be used
again and again.

Ex: Pascal complier , C Complier, COBOL Complier.

2. Interpreter
A interpreter is a program which translate s a high level language program into machine
language of the host computer. It translates each instruction and executes it immediately. If there
is any error in any line ,it shows the error message at the same time and program execution
cannot continue until the error is rectified. Once a program is error free ,the memory is
unnecessarily occupied by interpreter as it has to reside for every run.

Ex: GWBASIC interpreter.

Differences between Compiler and Interpreter

Compiler Interpreter
Popular for developed programs. Popular in program development environment.
Converts entire code at a time. Converts the code line by line.
Creates a permanent object file. No object file is created.
Reports all the errors at a time. It stops at the first error in program.

NUMBER SYSTEM

A number system of base (or radix), r is a system that uses distinct symbols for r digits. To determine the
quantity that the number represents, it is necessary to multiply each digit by an integer power of r
and then form the sum of all weighted digits.

They are of four types:

1. Decimal number system.


2. Binary number system.

3. Octal number system.

4. Hexa decimal number system.

Decimal number system:

The decimal number employs the radix – 10.

Ex:- 724.5(10) is represented as

7 2 4 . 5

102 101 100 10-1

= 7*102 + 2*101 + 4*100 + 5*10-1 = 700+20+4+0.5

Binary number system:

The binary number system uses the radix 2. The two digit symbols used are 0 and 1.

Ex:- 1101(2) is represented as

1 1 0 1 =1*8 + 1*4 + 0*2 +1*1 = 13(10)

23 22 21 20

Octal number system:

The octal number system uses the radix 8. The eight numbers used in octal system are 0-7.(i.e,
0,1,2,3,4,5,6,7).

Ex:- 34.6(8)
3 4 . 6

81 80 8-1

= 8 * 3 + 1 * 4 + 6 * 0.125 = 24 + 4 + 0.75 = 28.75(10).

Hexa decimal number system:

The hexa decimal number system uses the radix 16. The sixteen numbers used in hexa decimal system are
0-F.(i.e., 0,1,2,3,4,5,6,7,8,9,A-10,B-11,C-12,D-13,E-14,F-15).

Ex:- F3(16)

F 3 = 15 * 16 + 3 * 1 = 240 + 3 = 243(10).

161 160

CONVERSIONS

Decimal to Binary:

1) 36 2 | 36

2 | 18 - 0

2|9 -0

2|4 -1

2|2 -0

|1 -0
So binary equalent of 36(10) is ( 1 0 0 1 0 0 )(2)

2) 41 2 | 41

2 | 20 - 1

2 | 10 - 0

2| 5 -1

2|2 -1

|1 -0

So binary equalent of 41(10) is ( 1 0 1 0 0 1)(2)

Floating point to Binary:

1) 36.12(10) 2 | 36

2 | 18 - 0

2|9 -0

2|4 -1

2|2 -0
|1 -0

For decimal value 0.12

0.12 * 2 = 0.24

0.24 * 2 = 0.48

0.48 * 2 = 0.96 so binary value for decimal place is taken till

0.96 * 2 = 1.92 1.92 – i.e., ( 0 0 0 1 )

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

0.92 * 2 = 1.84

0.84 * 2 = 1.68

So binary equalent of 36.12(10) is ( 1 0 0 1 0 0 . 0 0 0 1)(2)

2) 14. 625(10) 2 | 14

2| 7 -0

2| 3 -0

| 1 -1

0.625 * 2 = 1.25

0.25 * 2 = 0.50

0.5 * 2 = 1.0 so binary value for decimal place is taken till


Last – i.e., ( 1 0 1 )

So binary equalent of 14.625(10) is ( 1 1 0 0 . 1 0 1)(2)

Binary to Decimal:

1) (1 0 0 1 0 0 )(2)

1 0 0 1 0 0

25 24 23 22 21 20

1 * 32 + 0 + 0 + 1 * 4 + 0 + 0 = 32 + 4 = 36(10).

2) (1 0 0 0 0 1 )(2)

1 0 0 0 0 1

25 24 23 22 21 20

1 * 32 + 0 + 0 + 0 + 0 + 1 * 1 = 32 + 1 = 33(10) .

Octal number to Binary number:

Convert each number to Binary format using 3 Binary digits.

1) 72(8) - ( 1 1 1 0 1 0)(2)

2) 64(8) - ( 1 1 0 1 0 0)(2)

Hexa Decimal number to Binary number:

Convert each number to Binary format using 4 Binary digits.

1) AF(16) - ( 10 15 ) - (1010 1 1 1 1 )(2)


2) A3(16) - ( 10 3 ) - (1010 0 0 1 1 )(2)

Hexa Decimal number to Decimal number:

1) 30(16) - 3 * 161 + 0 = 48 + 0 = 48(10)

2) B65F(16) - 11 * 163 + 6 * 162 + 5 * 161 + 15 * 160 = 46687(10)

Octal number to Decimal number:

1) 630(8) - 6 * 82 + 3 * 81 + 0 + 4 * 8-1 = 384 + 24 + 0 + 0.5 = 408.5(10)

Binary number to Octal number:

1) (101 100 011 010 111 . 111 100 000 110 )(2) = 54327.7406(8)

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

5 4 3 2 7 7 4 0 6

2) ( 11 100 . 1 001 )(2) = 34.11(8)

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

3 4 1 1

Binary number to Hexa Decimal number:

1) ( 0101 1111 0001 1010 . 1110 0011 )(2) = 5F1A . E3(16)

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

5 F 1 A E 3
2) ( 101 1010 1110 . 1100 0010 )(2) = 5AE . C2(16)

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

5 A E C 2

Algorithm:
■ An algorithm is a set of well-defined instructions in sequence to solve a problem.

Qualities of a good algorithm

■ Input and output should be defined precisely.

■ Each step in the algorithm should be clear and unambiguous.

■ Algorithms should be most effective among many different ways to solve a


problem.

■ An algorithm shouldn't include computer code. Instead, the algorithm should be


written in such a way that it can be used in different programming languages.
The problem solving techniques involves the following steps:

1. Define the problem

2. Formulate the mathematical model

3. Develop an algorithm

4. Write the code for the problem

5. Test the program.

Pseudocode& Algorithm
Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.
Pseudocode:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
Detailed Algorithm
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart
(Dictionary) A schematic representation of a sequence of operations, as in a
manufacturing process or computer program.
(Technical) A graphical representation of the sequence of operations in an information
system or program.
Information system flowcharts show how data flows from source documents through the
computer to final distribution to users.
Program flowcharts show the sequence of instructions in a single program or subroutine.
Different symbols are used to draw each type of flowchart.
A Flowchart
 shows logic of an algorithm
 emphasizes individual steps and their interconnections
e.g. control flow from one action to the next

Name Symbol Use in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program


Example 2-Algorithm, Flowchart
Write an algorithm and draw a flowchart to convert the length in feet to
centimeters.

Algorithm :

Input: length(ft) Output: length(cm)

Step1) Input the length in feet (Lft)

Step2) Calculate the length in cm (Lcm) by multiplying LFT with 30

Step3) Print length in cm (LCM)

Pseudocode:

Function LengthCovert(length) :

Input Lft

Lcm  Lft x 30

Print (Lcm)
Example3: Write an algorithm, Pseudocode and draw a flowchart
that will read the two sides of a rectangle and calculate its area.
Algorithm:

Input: width(w), length(L) Output : Area(A)

Step1) Input the width (W) and Length (L) of a rectangle

Step2) Calculate the area (A) by multiplying L with W

Step3) Print A
Pseudocode:

Function Area( length,width ):

Input W,L

AL x W

Print (A)
Algorithm to find all the roots of a quadratic equation:

Step 1. Start

Step 2. Read the coefficients of the equation, a, b and c from the user.

Step 3. Calculate discriminant = (b * b) – (4 * a * c)

Step 4. If discriminant > 0:

4.1: Calculate root1 = ( -b + sqrt(discriminant)) / (2 * a)

4.2: Calculate root2 = ( -b - sqrt(discriminant)) / (2 * a)

4.3: Display "Roots are real and different"

4.4: Display root1 and root2

Step 5: Else if discriminant = 0:

5.1: Calculate root1 = -b / (2 *a)

5.2: root2 = root1

5.3: Display "Root are real and equal"

5.4: Display root1 and root2

Step 6. Else:

6.1: Calculate real = -b / (2 * a)

6.2:Calculate imaginary = sqrt(-discriminant) / (2 * a)


6.3: Display “Roots are imaginary”

6.4: Display real, "±" , imaginary, "i"

Step 7. Stop
C Language Evolution:
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of
AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee


Features of C Language

C is the widely used 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
10. Extensible

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.

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 inbuilt functions
and hence the 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.
Structure and execution of a C program

Documentation section
It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. It is represented as:

//name of a program

Or

/*

Overview of the code

*/

Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and will
not interfere with the specified code.

Preprocessor section

The preprocessor section contains all the header files used in a program. It informs the system to
link the header files to the system libraries. It is given by:

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

The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled.

The #include<stdio.h> consists of the contents of the standard input output files, which
contains the definition of stdin, stdout, and stderr.
Whenever the definitions stdin, stdout, and stderr are used in a function, the statement
#include<stdio.h> need to be used.

There are various header files available for different purposes.

For example, # include <math.h>. It is used for mathematic functions in a program.

Define section
The define section comprises of different constants declared using the define keyword. It is given
by:

#define a = 2

Global declaration

The global section comprises of all the global declarations in the program. It is given by:

float num = 2.54;


int a = 5;
char ch ='z';
The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 4 bytes

We can also declare user defined functions in the global variable section.

Main function
main() is the first function to be executed by the computer. It is necessary for a code to include
the main().

It is like any other function available in the C library. Parenthesis () are used for passing
parameters (if any) to a function.

The main function is declared as:

main()

We can also use int or main with the main ().

1. The void main() specifies that the program will not return any value.

2. The int main() specifies that the program can return integer type data.

int main()

Or

void main()

Main function is further categorized into local declarations, statements, and expressions.

Local declarations

The variable that is declared inside a given function or block refers to as local declarations.

main()

int i = 2;
i++;

Statements

The statements refers to if, else, while, do, for, etc. used in a program within the main function.

Expressions

An expression is a type of formula where operands are linked with each other by the use of
operators. It is given by:

a - b;

a +b;

User defined functions

The user defined functions specified the functions specified as per the requirements of the
user.

For example, color(), sum(), division(), etc.

The program (basic or advance) follows the same sections as listed above.

Return function is generally the last section of a code. But, it is not necessary to include. It is
used when we want to return a value. The return function returns a value when the return type
other than the void is specified with the function.

Return type ends the execution of the function. It further returns control to the specified calling
function. It is given by:

1. return;
Or

1. return expression ;

For example,

return 0;

Examples
Let's begin with a simple program in C language.

Example 1: To find the sum of two numbers given by the user

It is given by:

1. /* Sum of two numbers */


2. #include<stdio.h> // preprocessor section that contains header files
3. int main() // main section
4. {
5. int a, b, sum; //local statements
6. printf("Enter two numbers to be added ");
7. scanf("%d %d", &a, &b);
8. // calculating sum
9. sum = a + b; //expressions
10. printf("%d + %d = %d", a, b, sum);
11. return 0; // return the integer value in the sum
12. }
Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed into an
executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the preprocessor, and then the
preprocessor expands this code. After expanding the code, the expanded code is passed to
the compiler.

Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler
converts the pre-processed code into assembly code.

Assembler
The assembly code is converted into object code by using an assembler. The name of
the object file generated by the assembler is the same as the source file. The
extension of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'.

If the name of the source file is 'hello.c', then the name of the object file would be
'hello.obj'.

Linker
Mainly, all the programs written in C use library functions. These library functions
are pre-compiled, and the object code of these library files is stored with '.lib' (or '.a')
extension. The main working of the linker is to combine the object code of library
files with the object code of our program. Sometimes the situation arises when our
program refers to the functions defined in other files; then linker plays a very
important role in this.

It links the object code of these files to our program. Therefore, we conclude that the
job of the linker is to link the object code of our program with the object code of the
library files and other files.

The output of the linker is the executable file.


The name of the executable file is the same as the source file but differs only in their
extensions.

In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file
can be named as 'a.out'.

For example, if we are using printf() function in a program, then the linker adds its
associated code in an output file.

Loader
Loader is responsible for loading the binary code into system's primary memory
(RAM) and its execution. After completing the execution, the output is shown on
console.

Let's understand through an example.

hello.c

#include <stdio.h>

int main()

printf("Hello javaTpoint");

return 0;

Now, we will create a flow diagram of the above program:


In the above flow diagram, the following steps are taken to execute a program:

o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded
source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code
would be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly code
into object code.
o After the creation of an object code, the linker creates the executable file. The loader
will then load the executable file for the execution.
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 value


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

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

constants, strings, and data values are called 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 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 Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

⇒ The addition operator can be used with numerical data types and character data type. When
it is used with numerical values, it performs mathematical addition and when it is used with
character data type values, 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.
Operato Exampl
r Meaning e

< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE

> Returns TRUE if the first value is larger than second value 10 > 5 is
otherwise returns FALSE TRUE

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

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

== Returns TRUE if both values are equal otherwise returns 10 == 5


FALSE is FALSE

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


returns FALSE TRUE

Logical Operators (&&, ||, !)


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

Operato
r Meaning Example

&& Logical AND - Returns TRUE if all conditions 10 < 5 && 12


are TRUE otherwise returns FALSE > 10 is FALSE

|| Logical OR - Returns FALSE if all conditions are 10 < 5 || 12 >


FALSE otherwise returns TRUE 10 is TRUE

! Logical NOT - Returns TRUE if condition is !(10 < 5 && 12


FLASE and returns FALSE if it is TRUE > 10) 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 Example

++ Increment - Adds one to existing value int a = 5;


a++; ⇒ a = 6

-- Decrement - Subtracts one from existing value int a = 5;


a--; ⇒ a = 4

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

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

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

Operato Exampl
r Meaning e

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

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

-= Subtract right-hand side value from left-hand side variable A -= B


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

*= Multiply right-hand side value with left-hand side variable A *= B


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

/= Divide left-hand side variable value with right-hand side A /= B


Operato Exampl
r Meaning e

variable value and store the result ⇒A=


into the left-hand side variable A/B

%= Divide left-hand side variable value with right-hand side A %=


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

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

Operato
r Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16
(10000)
Operato
r Meaning Example

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


⇒ 29
(11101)

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it A^B
is 1 ⇒ 13
(01101)

~ the result of Bitwise once complement is negation of the bit ~A


(Flipping) ⇒6
(00110)

<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100
)

>> the Bitwise right shift operator shifts all the bits to the right by A >> 2
the specified number of positions ⇒6
(00110)
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.
Example Programs 1:
// C program to print Integer data types.
#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;
// U or u is Used for Unsigned int in C.
int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

printf("Integer value with positive data: %d\n", a);


printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",
c);
printf("Integer value with an long int data: %ld", d);

return 0;
}

Example Programs 2:
// C program to print Integer data types.
#include <stdio.h>

int main()
{
char a = 'a';
char c;

printf("Value of a: %c\n", a);

a++;
printf("Value of a after increment is: %c\n", a);

// c is assigned ASCII values


// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;

printf("Value of c: %c", c);

return 0;
}

Example Program 3:
// C Program to demonstrate use
// of Floating types
#include <stdio.h>

int main()
{
float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);

return 0;
}

Example Program 4:
// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);

return 0;
}
Size of Data Types in C
The size of the data types in C is dependent on the size of the architecture, so we cannot
define the universal size of the data types. For that, the C language provides the sizeof()
operator to check the size of the data types.
// C Program to print size of
// different data type in C
#include <stdio.h>

int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);

printf("The size of int data type : %d\n", size_of_int);


printf("The size of char data type : %d\n",
size_of_char);
printf("The size of float data type : %d\n",
size_of_float);
printf("The size of double data type : %d",
size_of_double);

return 0;
}

Expressions and evaluation


Expressions are the combination of variables, operands, and operators. The result
would be stored in the variable once the expressions are processed based on the
operator's precedence.

Expression Example:

c=a+b

a-b+c

a+b-(a*c)
Types of Expressions in C

 Arithmetic expressions

 Relational expressions

 Logical expressions

 Conditional expressions
Arithmetic Expressions:

The arithmetic expression is evaluated in specific order considering the


operator's precedence, and the result of an expression will be based on the
type of variable.

From the given above arithmetic expressions example, let's consider the values of
operands to be a=2,b=3, and c=4.

After substitution of values into the given expression, we get:

Z = 2 + 3 - (2 * 4)

Below given steps are in order of precedence in which the operators of an


expression must be evaluated.
Step1: First, Priority is given to the parenthesis, so whatever is inside the
parenthesis will be evaluated first, a*c (2*4 = 8).

Step 2: The next level of precedence is given to + and - operator, so next a+b (2+3
= 5) is evaluated

Step 3: a+b will be subtracted from a*c i.e; 5 - 8 = -3.

Step 4: The final value after evaluation of an arithmetic expression will be stored
into the variable Z, according to the example value three is stored into the variable
Z that is z = -3

Look at the below-given figure to understand the arithmetic expressions evaluation


in a better way.
Example Program Using Arithmetic Expressions:

#include <stdio.h>

void main()

int a=2,b=3,c=4,z;

z=a+b-(a*c);

printf("Result= %d",z);

Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken
or not.
o In relational expressions, a numeric value cannot be compared with the
string value.
o The result of the relational expression can be either zero or non-zero value.
Here, the zero value is equivalent to a false and non-zero value is equivalent
to true.

Relational Description
Expressio
n

x%2 = = 0 This condition is used to check whether the x is an even number


or not. The relational expression results in value 1 if x is an even
number otherwise results in value 0.

a!=b It is used to check whether a is not equal to b. This relational


expression results in 1 if a is not equal to b otherwise 0.

a+b = = x+y It is used to check whether the expression "a+b" is equal to the
expression "x+y".

a>=9 It is used to check whether the value of a is greater than or equal


to 9.

#include <stdio.h>
int main()
{
int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}

Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero
value.
o It is a complex test condition to take a decision.

Logical Description
Expression
s

( x > 4 ) && ( It is a test condition to check whether the x is greater than 4 and
x<6) x is less than 6. The result of the condition is true only when
both the conditions are true.

x > 10 || y It is a test condition used to check whether x is greater than 10


<11 or y is less than 11. The result of the test condition is true if
either of the conditions holds true value.

! ( x > 10 ) It is a test condition used to check whether x is not greater than


&& ( y = = 10 and y is equal to 2. The result of the condition is true if both
2) the conditions are true.

Example Program on && operator


#include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}

Example Program on && operator


#include <stdio.h>
int main()
{
int x = 4;
int y = 9;
if ( (x <6) || (y>10))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}

Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is
true otherwise 0.
o A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator

Suppose exp1, exp2 and exp3 are three expressions.


The general syntax of conditional expression is:

Exp1? Exp2: Exp3

From the given above expressions, the first expression (exp1) is conditional, and if
the condition is satisfied, then expression2 will be executed; otherwise,
expression3 will be performed.

Example:

2<3? 2 : 3

a*b>c ? true : false

From the given below conditional expressions example, let's consider the values of
operands to be a=5, b=3, and c=1.
After substitution of values into the given expression, we get:

Z = (5 * 3) < 1 ? ‘true’ : ‘false’

Below given steps are in order of precedence in which the operators of an


expression must be evaluated.

Step 1: First, it evaluates the expression1 a*b (5*3=15).

Step 2: Next, it checks whether the condition is satisfied, a*b < c (15 > 1), false.

Step 3: Since the condition is false, expression3 will be executed and return the
value one as an output stored in the variable Z.

Look at the below-given figure to understand the evaluation of the conditional


expressions in a better way.

Let's understand through a simple example.


#include <stdio.h>

void main()

int a=5, b=3, c=1,z;

z = (5 * 3) < 1 ? 1 : 0;

printf("Result = %d",z);

Output:

What is Evaluation, Precedence and Association in C language?

Expressions are evaluated by the ‘C’ compiler based on precedence and associativity
rules.

If an expression contains different priority operators, then the precedence rules are
considered.
Here, 10*2 is evaluated first since ‘*’ has more priority than ‘- ‘and ‘=’

If an expression contains same priority, then associativity rules are considered i.e. left
right (or right to left).
DECLARATION OF VARIABLES

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

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

syntax:

data type variable_list;

The example of declaring the variable is given below:

int a;

float b;

char c;

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

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

1. int a=10,b=20;//declaring 2 variable of integer type

2. float f=20.8;

3. char c='A';

Rules for defining variables

✔ A variable can have alphabets, digits, and underscore.


✔ A variable name can start with the alphabet, and underscore only. It can't start with a
digit.

✔ Except underscore, No special character is allowed within the variable name.( every
character other than alphabets, digits is a special character)

✔ A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

✔ int a;

✔ int _ab;

✔ int a30;

Invalid variable names:

✔ int 2;

✔ int a b;

Variable Declaration in C

✔ variable declaration provides assurance to the compiler that there exists a variable

with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs
actual variable definition at the time of linking the program.

Declaring Variable as Constant

The values of some variable may be required to remain constant through-out the program. We
can do this by using the qualifier const at the time of initialization.

Example:

const int class_size = 40;

The const data type qualifier tells the compiler that the value of the int variable class_size may
not be modified in the program.

// Program to illustrate the declaration of variables


in C
#include <stdio.h>
int main()
{
// declaring alpha variable with value 10.
int alpha = 10;
// declaring beta variable with value 20.
int beta = 20;
// declaring c variable without initializing it.
int c=0;
// Checking the initial value of c variable.
printf("The initial value of c is %d\n", c);
c= alpha + beta;
// printing C variable value.
printf("The sum of alpha and beta is %d", c);
return 0;
}

#include <stdio.h>
int main() {
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
Assignment statements:

An Assignment statement is a statement that is used to set a value to


the variable name in a program.

Assignment statement allows a variable to hold different types of values


during its program lifespan. Another way of understanding an
assignment statement is, it stores a value in the memory location which
is denoted by a variable name.

Syntax
The symbol used in an assignment statement is called as an operator.
The symbol is ‘=’.

Note: The Assignment Operator should never be used for Equality


purpose which is double equal sign ‘==’.

The Basic Syntax of Assignment Statement in a programming


language is :

variable = expression ;

where,
variable = variable name

expression = it could be either a direct value or a math


expression/formula or a function call

Few programming languages such as Java, C, C++ require data type to


be specified for the variable, so that it is easy to allocate memory space
and store those values during program execution.

data_type variable_name = value ;

Example –

int a = 50 ;

float b ;

a = 25 ;

b = 34.25f ;

Assignment Statement Forms


1. Basic Form

This is one of the most common forms of Assignment Statements. Here


the Variable name is defined, initialized, and assigned a value in the
same statement. This form is generally used when we want to use the
Variable quite a few times and we do not want to change its value very
frequently.

int RollNo = 25 ;

printf("%d",RollNo);

Standard I/O statements:

There are some library functions which are available for transferring the information
between the computer and the standard input and output devices.
These functions are related to the symbolic constants and are available in the header
file.

Some of the input and output functions are as follows:

i) printf
This function is used for displaying the output on the screen i.e the data is moved
from the computer memory to the output device.

Syntax:
printf(“format string”, arg1, arg2, …..);

In the above syntax, 'format string' will contain the information that is formatted. They
are the general characters which will be displayed as they are .
arg1, arg2 are the output data items.
Example: Demonstrating the printf function
printf(“Enter a value:”);

 printf will generally examine from left to right of the string.


 The characters are displayed on the screen in the manner they are encountered until it
comes across % or \.
 Once it comes across the conversion specifiers it will take the first argument and
print it in the format given.

ii) scanf
scanf is used when we enter data by using an input device.

Syntax:
scanf (“format string”, &arg1, &arg2, …..);

The number of items which are successful are returned.

Format string consists of the conversion specifier. Arguments can be variables or array
name and represent the address of the variable. Each variable must be preceded by an
ampersand (&). Array names should never begin with an ampersand.

Example: Demonstrating scanf


int avg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):
 scanf works totally opposite to printf. The input is read, interpret using the
conversion specifier and stores it in the given variable.
 The conversion specifier for scanf is the same as printf.
 scanf reads the characters from the input as long as the characters match or it will
terminate. The order of the characters that are entered are not important.
 It requires an enter key in order to accept an input.

iii) getch
This function is used to input a single character. The character is read instantly and it
does not require an enter key to be pressed. The character type is returned but it does
not echo on the screen.

Syntax:
int getch(void);
ch=getch();

where,
ch - assigned the character that is returned by getch.

iv) putch
this function is a counterpart of getch. Which means that it will display a single
character on the screen. The character that is displayed is returned.

Syntax:
int putch(int);
putch(ch);
where,
ch - the character that is to be printed.

v) getche
This function is used to input a single character. The main difference between getch
and getche is that getche displays the (echoes) the character that we type on the
screen.

Syntax:
int getch(void);
ch=getche();

vi) getchar
This function is used to input a single character. The enter key is pressed which is
followed by the character that is typed. The character that is entered is echoed.

Syntax:
ch=getchar;

vii) putchar
This function is the other side of getchar. A single character is displayed on the screen.

Syntax:
putchar(ch);

viii) gets and puts


They help in transferring the strings between the computer and the standard input-
output devices. Only single arguments are accepted. The arguments must be such that
it represents a string. It may include white space characters. If gets is used enter key
has to be pressed for ending the string. The gets and puts function are used to offer
simple alternatives of scanf and printf for reading and displaying.

Example:

#include <stdio.h>
void main()
{
char line[30];
gets (line);
puts (line);
}

Type conversions:
Type conversion occurs when an expression has a mixed data types. At this time,
the compiler will try to convert from lower to higher type, because converting from
higher to lower may cause loss of precision and value. C has following rules for
type conversion.
● Integer types are lower than floating-point types.
● Signed types are lower than unsigned types.
● Short whole-number types are lower than longer types.
● The hierarchy of data types is as follows: double, float, long, int, short, char.
Conversion Type Casting

Result type of arithmetic expression depends on operand types inside it. When an
expression is consisted of various data types, result type is set by defined casting
rules. There are two ways of casting data types in C:

·Automatic (implicit)

·Given (explicit)

Implicit Casting (automatic transformation) works in a way that a variable


(operand) of data type that is smaller in length, transforming internally to variable
of data type with longer length. It may sound mixed up, but here is an example:

short int ->int ->unsigned int ->long int ->unsigned long int ->float ->double -
>long double

Explicit Casting (given transformation): When we want to convert the value of a


variable from one type to another we can use type casting. Type casting does not
change the actual value of variable. C allows programmers to perform typecasting
by placing the type name (type casting operator) in parentheses and placing this in
front of the value or variable. Explicit casting of data types has higher priority than
automatic transformation. General declaration of explicitcast (cast operator):
(data_type) operand Operand can be variable or expression.

For example:

main()

float a;

a = (float)5 / 3;

gives result as 1.666666 . This is because the integer 5 is converted to floating point value before
division and the operation between float and integer results in float.

main()

int a = 5000, b = 7000 ;

long int c = a * b ;

}
Here two integers are multiplied and the result is truncated and stored in variable c
of type long int. But this would not fetch correct result for all. To get a more
desired output the code is written as long int c = (long int) a * b;

You might also like