C Language Basics

You might also like

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

UNIT-I

Introduction to Computers
Computer Systems

The term computer is derived from the word compute.A computer is an electronic device that accepts
data and instructions as an input from the user then processes the data and provides useful
information ,known as output.

A computer is a system made of two major components:

 Computer Hardware

 Computer Software

A Computer System:

Hardware:Phisical components of system is called as hardware.

Software :The set of instructions or programs is known as software.


COMPUTER-HARDWARE

block diagram of computer system


Central Processing Unit(CPU):It is the brain of the computer that is responsible for controlling and
executing program instructions.

Monitor:It is a display screen ,which shows information in visual form as output.

Keyboard and Mouse:These are used for receiving inputs from the user.

CHARACHTERISTICS:

Speed:The computer is a fastest electronic device that can solve large and complex problems in few
seconds.The speed of a computer generally depend on its hardware configurations.

Storage:A computer can store huge amounts of data.The storage area of computer system categorized
into 1.Main Memory 2 Secondary Memory.

Accuracy:A computer carries out calculations with great accuracy.

Reliability:A computer produces results with no error.The computers are regarded as trustworthy
machines.

Versatility:Computers perform varied tasks and can be used for many different purposes.

Deligence:Computers can perform repetitive calculations any number of timeswith the same level of
accuracy.

INPUT DEVICES: They are used for accepting the data .

Example:

Keyboard: A standard keyboard includes alphanumeric keys,function keys,cursor movement keys,spacebar


keys,escake key,numeric keypad and special keys.

Mouse: The mouse allows the user to select elements on the screen on the screen,such as
tools,icons,buttons,by pointing and clicking them.The mouse also known as a pointing device.

Scanner:A scanner is an input device that converts documents and images as the digitized images
understandable by the computer.The types of scanners are:1.Flatbed scanner 2.Drum Scanner 3.Slide Scanner
4.handheld Scanner.

PROCESSOR: It is used to perform the calculations and data processing on data that is through the input
device.It is also known as CPU.

The CPU consists of Control Unit(CU) and ALU.CU atores the instruction set ,which specifies the operations to
be performed by the computer.CU transfers the data and the instructions to the ALU for an arithmetic
operation.ALU performs arithmetical and logical operations.

Apart from CU and ALU,CPU seeks help from the following hardware devices to process data.
1.Motherboard: It refers to a device used for connecting the CPU with the input and output devices.The
componenets on the motherboard are connected to all parts of a computer and are kept insulated from each
other.These are:

a)Bus:Electrical pathways that transfer data and instructions among different parts of the computer.

b)System Clock:It is used for synchronizating the activities performed by the computer.The faster the system
clock ,the faster is the processing speed of the computer.

c)Microprocessor:CPU component that performs the processing and controls the activities performed by the
different parts of the computer.

d)ROM:It is a chip that contains the permanent memory of the computer that stores information ,which can
not be modified by the user.

Random Access Memory(RAM):It is known as primary memroty.It stores data and programs,until the
computer is used.It is a chip that cab be connected to the RAM slots in the motherboard.

Video Card:It is an interface between the monitor and CPU and used to display graphics.

Sound Card:It is a circuit board placed on the motherboard and is used to enhance the sound capabilities of
computer.

OUTPUT DEVICES:They are use for providing the output of program that is obtained after operations specified
in a program.

Example: Monitor,printer.

Monitor:It is the most commonl used output device that produces visual displays generated by the computer.

The monitor is also known as a screen.The monitors classified as Cathode ray Tube(CRT) monitors and Liquid
Crystal Display(LCD) monitors.

CRT monitors are large,occupy,more space in the computer.

LCD monitors are thin,light weight and occupy less space.

Printer:It is an output device that is used to produce a hardcopy of the electronic text displayed on the
screen,in the form of paper.The performance of printer is measured in terms of dots per inch(DPI) and pages
per minut(PPI).The greater the DPI parameter of a printer,the better is the quality of the output generated by
it.

Printers types are 1.Dot Matrix Printers 2.Inkjet Printers 3.Laser Printers.

Speaker:The speaker is an electromechanical tranducer that converts an electrical signal into sound.They are
attached to a computer as output devices.

Plotter:It is commonly used output device that is connected to a computer to print large documents such as
engineering or constructional drawings.
Plotters types are 1.Drum plotter 2.Flat bed Plotter 3.Inkjet Plotter 4.Electrstatic Plotter.

MEMORY:It is for storing the input data.Memory can be primary memory and seconday memory.

Primary memory includes Random Access Memory(RAM) and Secondary memory includes harddisks and
floppy disks.

Primary Memory:It is available in the computer as a built-in-unit of the computer.The primary memory is
represented as a set of locations with each location occupying 8 bits.each bit in the memory is identified a
unique address.

ROM(Read Only Memory):It is used store data and instructions,even when the computer is turned off.It is
permanent memory of the computer where the contents cannot be modified by an end user.

RAM(Random access Memory):It is the read/write memory unit in which the information is retained only as
long as there is a regular power supply.When the power supply is interrupted or switched off,the information
stored in the RAM is lost.Ram is a volatile memory.

Cache memory:It is used to store the data and the related application that was last processed by the CPU.The
cache memory is always is placed between CPU and the memory of the computer.

Secondary Memory:It is a memory which represents the external storage devices that are connected to the
computer.The devices can be classified as:

1.Magnetic Storage Device:Floppy Disk,Hard Disk, Magnetic tapes.

2.Optical Storage Device:CD-ROM,CD-RW,DVD-ROM.

3.Magnetic Optical Storage Device:Sony MiniDisc,Maxoptix T5-2600.

4.Universal Serial Bus(USB):It is also known as pen drive.

Types of Software

Computing Environments
In the early days of computers, there was only one environment, the mainframe computer hidden in a
central computing department. With the advent of minicomputers and personal computers, the
environment changed with computers on virtually every desktop. several different environments are:
 Time-Sharing Environment

 Client/server Environment

 Distributed Computing

Personal Computing Environment

A personal computer is a general-purpose computer whose size, capabilities and original sale price make it useful for
individuals, and is intended to be operated directly by an end-user with no intervening computer operator.All of the
computer hardware components are tied together in our personal computer.

Time-sharing Environment:

All computing must be done by the central computer.Central computer must control the shared resources,it
must manage the shared data and printing and it must do the computing.These computer are may be
minicomputers or central mainframes.
The Client/Server Environment

A client/server computing environment splits the computing function between a central computer and user’s
computers.In this environment ,the users microcomputers or workstations are called the clients.Central
computer ,which may be powerful minicomputer or microcomputer is known as server.

Distributed Computing

This environment provides a seamless integration of computing functions between servers and clients.The
Internet provides connectivity to different servers throughout the world.This environment provides a
reliable,scalable and highly available network.

Computer Languages
To write a program for a computer, we must use a computer language. Over the years computer languages
have evolved from machine language to natural languages.

Machine Languages

Symbolic Languages

High-Level Languages

Creating and Running Programs

Here we explain the procedure for turning a program written in C into machine language. The process
is presented in a straightforward, linear fashion, but you should recognize that these steps are
repeated many times during development to correct errors and make improvements to the code.
Writing and Editing Programs
Compiling Programs
Linking Programs
Executing Programs.

Building a C Program

PROGRAM DEVELOPMENT

1) Statement of Problem

a) Working with existing system and using proper questionnaire, the problem should be explained
clearly.

b) What inputs are available, outputs are required and what is needed for creating workable solution
should be understood clearly.

2) Analysis

a) The method of solutions to solve the problem can be identified.

b) We also judge that which method gives best results among different methods of solution.

3) Designing

a) Algorithms and flow charts will be prepared.

b) Keep focus on data, architecture, user interfaces and program components.

4) Implementation

The algorithms and flow charts developed in the previous steps are converted into actual programs in
the high level languages like C.
4. A) Compilation

Translate the program into machine code. This process is called as Compilation. Syntactic errors are
found quickly at the time of compiling the program. These errors occur due to the usage of wrong
syntaxes for the statements.

Eg: x=a*y+b

There is a syntax error in this statement, since, each and every statement in C language ends with a
semicolon (;).

4. B) Execution

The next step is Program execution. In this phase, we may encounter two types of errors.

Runtime Errors: these errors occur during the execution of the program and terminate the program
abnormally.

Logical Errors: these errors occur due to incorrect usage of the instructions in the program. These
errors are neither detected during compilation or execution nor cause any stoppage to the program
execution but produces incorrect output.

Problem Solving
Problems that can be solved through a computer may range in size and complexity. since computer do
not posses any common sense and cannot make any unplanned decisions, the problem whether it is
simple or complex ,has to broken into well defined set of solution steps for the computer to
implement.

Problem solving is the process of solving a problem in a computer system by following a sequence of
steps.

Algorithm: An algorithm is sequence of steps written in the form of English phrases that specify the tasks
that are performed while solving a problem. It involves identifying the variable names and types that would be
used for solving the problem

Pseudo code: is much similar to algorithms .It uses generic syntax for describing the steps that are
performed for solving a problem along with the statements written using generic syntax, pseudo code can also
use English phrases for describing action.

Flow chart: Flowchart is the graphical representation of the flow of control and logic in the solution of a
problem or the flowchart is a pictorial representation of an algorithm
ALGORITHM TO FIND ADDITION OF TWO NUMBERS

STEP 1: ACCEPT FIRST INTEGER AS INPUT (NUM1)

STEP2: ACCEPT SECOND INTEGER AS INPUT (NUM2)

STEP 3: CALCULATE THE SUM OF TWO

INTEGERS (SUM=NUM1+NUM2)

STEP 4: DISPLAY SUM AS RESULT

ALGORITHM TO FIND GIVEN NUMBER IS EVEN OR ODD

Step 1: START

Step 2: ENTER a NUMBER (n)

Step 3: IF (n%2=0) then GOTO step 4

Else goto Step 5

Step 4: Print number is even

Step 5: Print number is odd

Step 6: STOP

ALGORITHM TO FIND GIVEN YEAR IS LEAP OR NOT

STEP 1: ENTER Year as Input

STEP 2: IF (year %4==0 and year%100! =0)

STEP 3: print "it is a leap year";

else

STEP 4: IF (year%400==0)

STEP 5: print "it is a leap year";

else

STEP 6: print "it is not a leap year";


Flowchart for addition of two numbers.

Flow chart to find given number is Even or Odd

PSEDUCODE FOR ADDITION TWO NUMBERS

BEGIN

DEFINE: Integer n1,n2

RREAD: Integer n1

READ: Integer n2

SET: r=n1+n2

DISPLAY: r

END
PSEDOCODE TO FIND average of three numbers

BEGIN

DEFINE: Integer m1.m2.m3

DEFINE: Real avg

DISPLAY: “Enter three marks”

READ: m1.m2.m3

COMPUTE: avg=m1+m2+m3/3

DISPLAY: avg

END

PSEDOCODE TO FIND EVEN OR ODD

BEGIN

DEFINE: Integer n

DISPLAY: “Enter number”

READ: n

IF: n% 2==0

DISPLAY: “Even Number”

ELSE

DISPLAY: “Odd Number”

END IF

END
Flow chart symbols

Flowchart to find whether a number even or odd:


MACHINE LANGUAGE:

The only language the computer can understand is machine language (binary language).

HIGH LEVEL LANGUAGE:

A high level language is English like language where one instruction typically translates into a series of
machine-language instructions.

LOW LEVEL LANGUAGE:

A low level language corresponds closely to machine code so that a single low-level language
instruction translates to a single machine language instruction.

Structure of C program
Documentation Section

Linkage Section

Definition Section

Global Declaration Section

Main Function Section

Local Declaration Part

Executable Code Part

Sub Program Section

Function1()

Function2()

……………

FunctionN()

Documentation section: It consists of a set of comment lines giving the name of the program, the
author and other details.

Link Section: It provides instructions to the compiler to link functions from system library.

Definition section: It defines all symbolic constants.

Global Declaration section: Some variables are used in more than one function .Such variables are
called global variables.
Main() Function section:

Every C program have one main () function. This section contains two parts, declaration part and
executable part.

The declaration part declares all the variables used in the executable part. There is at least one
statement in the executable part. These two parts must appear between the opening and the closing
braces. The program execution begins at opening brace and ends at closing brace.

The closing brace of the main function is the logical end of the program .All statements in the
declaration and executable part ends with semicolon.

Subprogram Section:

It contains all user defined functions that are called in the main function.

All sections, except the main function section may be absent when they are not required.

C Character Set:

A programming language is designed to help process certain kinds of data containing of numbers,
characters and strings and to provide useful output known as information

The task of processing data is accomplished by executing a sequence of precise instructions called a
program.

These instructions are formed using certain symbols and words accordingly to some rigid rules known
as syntax rules.

Every program instruction must confirm precisely to the syntax rules of the program.

The characteristics in C are grouped into the following categories.

1. Letters.

Uppercase(A-Z), Lower Case(a-z)

2. Digits:- 0..9

3.Special characters:-

, & . ^ ; * : - ? + ‘ < > “ # ! | \(backslash) /(slash) ~ {} [] () $ % etc.

4.White Spaces:

Blank Space.

Horizontal tab

Vertical tab.

New Line
Form Feed

Trigraph characters:

Many non- English keywords do not support all the special characters. ANSI C introduces the
concept of trigraph sequences to provide a way to enter certain characters that are not available on
some keyboards. Each trigraph sequence consists of three characters (two question marks followed by
another character).

Trigraph Characters:

Trigraph Sequence Translation Character

??= #

??( [

??/ \

??) ]

??‘ ^

??< {

??! | (Vertical Bar)

??> }

??- ~ (Tilde)

C Tokens: Tokens are individual words and punctuation marks in passage of text. In C, program the
smallest individual units are known as C Tokens. C has six types of Tokens.
Keywords:
keywords are the words that convey a special meaning to the c compiler. The keywords cannot be used
as variable names because by doing so.

auto do float register static volatile

break double for return struct while

case default goto switch typedef

char else if short Union

const enum int signed Unsigned

continue extern long sizeof void

Identifiers:
Identifiers are used as the general terminology for the names of variables, functions and arrays. These
are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter
or the underscore(_) as a first character.

There are certain rules that should be followed while naming c identifiers:

They must begin with a letter or underscore (_).

They must consist of only letters, digits, or underscore. No other special character is allowed.

It should not be a keyword.

It must not contain white space.

It should be up to 31(63-C99) characters long as only first 31 characters are significant.

Examples:

Name Remark

_ a9 Valid

void Invalid as it is a keyword

a_b valid

x* Invalid

ab Invalid –blank space not allowed.


Constants:
The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.

The constants are treated just like regular variables except that their values cannot be modified after
their definition.

Integer literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals:

212 /* Legal */

215u /* Legal */

0xFeeL /* Legal */

85 /* decimal */

0213 /* octal */

0x4b /* hexadecimal */

30 /* int */

30u /* unsigned int */

30l /* long */

30ul /* unsigned long */

Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. We
can represent floating point literals either in decimal form or exponential form.

While representing using decimal form, we must include the decimal point, the exponent, or both and
while representing using exponential form; you must include the integer part, the fractional part, or
both. The signed exponent is introduced by e or E.

Examples of floating-point literals:

3.14159 /* Legal */

314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */

.e55 /* Illegal: missing integer or fraction */

Character constants

Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char
type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t').

There are certain characters in C when they are preceded by a backslash they will have special meaning
and they are used to represent. Here, we have a list of some of such escape sequence codes:

Escape sequence Meaning

\\ \ character

\‘ ' character

\“ " character

\? ? Character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

String literals

String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences.

We can break a long line into multiple lines using string literals and separating them using whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello,how are you“


Defining Constants

There are two simple ways in C to define constants:

Using #define preprocessor.

Using const keyword.

The #define Preprocessor

Syntax:

#define identifier value;

Program using #define

#include <stdio.h>

#define LENGTH 10

#define WIDTH 5

int main()

int area;

area = LENGTH * WIDTH;

printf("value of area : %d", area);

return 0;

The const Keyword


we can use const prefix to declare constants with a specific type as follows:

const type variable = value;

Example :

#include <stdio.h>

void main()

const int LENGTH = 10;

const int WIDTH = 5;


int area; area = LENGTH * WIDTH; printf("value of area : %d", area);

Variables:
A variable is nothing but a name given to a storage area that our programs can manipulate.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-
sensitive.

TYPE DESCRIPTION

char Typically a single octet (one byte). This is an integer type.

int The most natural size of integer for the machine

Float A single-precision floating point value

double A double-precision floating point value

void Represents the absence of type.

Variable Definition in C:
A variable definition means to tell the compiler where and how much to create the storage for the
variable. A variable definition specifies a data type and contains a list of one or more variables of that
type as follows:

type variable_list;

Here, type must be a valid C data type .variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here:

Examples:

int i, j, k;

char c, ch;

float f, salary;

double d;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows:

type variable_name = value;


Examples are:

extern int d = 3, f = 5; // declaration of d and f.

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

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

Data Types:
In the C programming language, data types refer to an extensive system used for declaring variables or
functions of different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.

The types in C can be classified as follows:

1. Basic Types:

They are arithmetic types and consist of the three types:

Integer types and (b) floating-point types) character.

2. Enumerated Type

They are again arithmetic types and they are used to define variables that can only be assigned certain
discrete integer values throughout the program.

3. The type void:

The type specifier void indicates that no value is available.

4. Derived Data types:

They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function
types.

Data Types :

Type Storage size Value range


char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 byte 1.2E-38 to 3.4E+38
double 8 byte 2.3E-308 to 1.7E+308
long double 10 byte 3.4E-4932 to 1.1E+4932

Operators:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of operators:

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators.

Arithmetic Operators.

1 + Addition or Unary plus

2 - Subtraction or Unary Minus

3 * Multiplication

4 / Division

5 % Modulus

/* Program to demonstrate the working of arithmetic operators in C. */

#include

void main()

int a=9,b=4,c;

c=a+b;

printf("a+b=%d\n",c);

c=a-b;

printf("a-b=%d\n",c);

c=a*b;
printf("a*b=%d\n",c);

c=a/b;

printf("a/b=%d\n",c);

c=a%b;

printf("Remainder when a divided by b=%d\n",c);

Increment and decrement operators


 In C, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and – subtracts 1 to
operand respectively.

Difference between ++ and -- operator


 as postfix and prefix When i++ is used as prefix(like: ++var), ++var will increment the value of var and
then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and
then only increment it.

Assignment Operators.
The most common assignment operator is =. This operator assigns the value in right side to the left
side.

Operator Example Equals to

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

Operator Example Equals to

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b
Relational Operator:
Relational operators checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0.

Operator Meaning Example

== Equal to 4==2(false)

> Greater than 4>2,returns 1.

< Less than 4<2,returns 0.

>= Greater than or equal to 4>=2,returns 1.

<= Less than or equal to 4<=2,returns 0.

!= Not equal to 4!=2,returns 1.

Logical Operators:
Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:

Operator Meaning Example

&& Logical AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.

|| Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true.

! Logical NOT If c=5 then, !(c==5) returns false.

Conditional Operator
Conditional operator takes three operands and consists of two symbols? And:. Conditional operators
are used for decision making in C.

For example: c=(c>0)? 10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators.
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise Complement

<< Left Shift

>> Right Shift

Other Operators

Comma Operator:
Comma operators are used to link related expressions together.

For example:

int a,c=5,d;

The sizeof operator


It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.

Address Operator: & Returns the address of an variable

Indirection Operator: * Pointer to a variable

Program:
#include <stdio.h>

int main()

int a;

float b;
double c;

char d;

printf("Size of int=%d bytes\n",sizeof(a));

printf("Size of float=%d bytes\n",sizeof(b));

printf("Size of double=%d bytes\n",sizeof(c));

printf("Size of char=%d byte\n",sizeof(d));

return 0;

Precedence and Associativity.


Precedence is used to determine the order in which different operators in a complex expression
are evaluated. Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression.

SNO Operator Associativity

1 (expr) [index] -> . Left ==> Right

2 ! ~ ++ -- (type) Right  Left


sizeof
Unary operator: + - *
&

3 * / % Left ==> Right

4 + - Left ==> Right

5 << >> Left ==> right

6 < <= > >= Left ==> Right

7 == != Left ==> Right

8 Binary operator: & Left ==> Right

9 Binary operator: ^ Left ==> Right

10 Binary operator: | Left ==> Right


11 && Left ==> Right

12 || Left ==> Right

13 expr ? true_expr : false_expr Right  Left

14 += -= *= /= <<= Right  Left


&= ^= |= %= >>=
=

15 , Left ==> Right

Executing a C program.

Translators: are system software used to convert high-level language program into machine-language code.

Compiler : Coverts the entire source program at a time into object code file, and saves it in secondary
storage permanently. The same object machine code file will be executed several times, whenever needed.
Interpreter : Each statement of source program is translated into machine code and executed immediately.
Translation and execution of each and every statement is repeated till the end of the program. No object code
is saved. Translation is repeated for every execution of the source program.

Increment and Decrement Operators


 prefix increment (++a)

 postfix increment (a++)

 prefix decrement(- -a)

 postfix decrement (a- -)

 /* prefix operators */

#include<stdio.h>

void main()

int a = 7, b = 12, c;

c = b * (++a) + 5 * (++a);

printf(“ a = %d”, a);

printf(“\n b = %d”,b);

printf(“\n c = %d”,c);

Output:

a=9

b = 12

c = 153 ( 12 * 9 + 5 * 9)

If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated.

If ++ is before the operand, as in ++a, the increment takes place before the expression is evaluated.
 /* prefix and postfix operators */

#include<stdio.h>

void main()

int a = 7, b = 12, c;

c = b * (a++) + 5 * (++a);

printf(“ a = %d”, a);

printf(“\n b = %d”,b);

printf(“\n c = %d”,c);

}
Output:

a=9

b = 12

c = 136 ( 12 * 8 + 5 * 8) .

 /* postfix operators */

#include<stdio.h>

int main() {

int a = 7, b = 12, c;

c = b * (a++) + 5 * (a++);

printf(“ a = %d”, a);

printf(“\n b = %d”,b);

printf(“\n c = %d”,c);

}
• C Program to find area and circumference of circle

#include<stdio.h>

void main()

int rad;

float pi=3.14,area,ci;

printf("\n Enter radius of circle: ");

scanf("%d",&rad);

area = pi * rad * rad;

printf("\n Area of circle : %f ",area);

ci = 2 * pi * rad;

printf("\n Circumference : %f ",ci);

Type Conversion:
The type conversion or type casting refers to the process of changing an entity of one type into
another.

There are two types of conversion.

1.Implicit conversion.

2.Explicit Conversion

• Implicit Conversion:

It is an automatic type conversion. In a mixed type expression ,data of one or more sub types can be
converted to a super type as needed at runtime. So the program will run correctly.

Ex: double a;

long b;

int c;

If(a>b) a=c;
If (c>b) b=c;

If(a==b) a+=2’

Although a, b, c belong to different data types, they will be automatically converted to equal data types
each time.

Data can be lost when floating point representations are converted to integral representations as the
fractional components of the floating point values will be truncated.

Conversely, converting from an integral representation to a floating point one can also lose precision,
since the floating point may be unable to represent the integer exactly.

• Explicit Conversion

The explicit conversion can be made possible to convert one data type to another by forcefully and it is
different from the implicit conversion.

Syntax: variable1=(data type) variable2

int a=10;

float (a);

Now float(a) will contain 10.000000.

• Example2:

double d=6.5;

double b=8.5;

int result=(int)(d)+(int)(b)

result is 14 not 15.

• Input & Output in C


We have two methods for providing data to the program.

1.Assigning the data to the variables in a program.

2.By using the input/output statements several functions are available for input/output operations in
C.These functions are collectively known as the standard I/O library.

1.Unformatted input/output Statements.

2.Formatted input/output Statements.

1. Unformatted Functions
Input functions:

getc() getchar() gets() getch() getche()

Output Functions:

putc() putchar() puts()

2. Formatted Functions

Input Functions:

scanf() fscanf()

Output Functions:

printf() fprintf()

getchar():

A single character can be given to the computer string using C input library function getchar().

Syantax:

char variable=getchar();

Example:

char x;

x=getchar();

The getchar() functions is written in standard I/O libray.It reads a single character from
standard input device

putchar():

The putchar() function is used to display one character at a time on the standard output device.

Syntax:

putchar(character variable);

Example

char x;

putchar(x);

getc():
getc() function is used to accept a single character from the standard input device.

Syntax:

character varavle=getc();

Example

char c;

c=getc();

putc():

putc() is used to display a single character.

Syantax:

putc(character variable);

Example:

char c;

putc(c);

Note: The getc() and putc() functions are often used in file processing

gets() and puts()

The gets() function is used to read the string from the standard input device.

Syntax:

gets(string);

The puts() function is used to display the string.

Syntax:

puts(string) ;

Program using gets() and puts()

#include<stdio.h>

#include<conio.h>

void main()

char name[25];
puts(“ENTER NAME”);

gets(name);

puts(“Display name”);

puts(name);
}

getch() and getche()

The getch() reads a single character directly from the keyboard without echoing to the screen.

The getche() reads a single character from the keyboard and echoes it to the current text window.

Syntax:

int getch(void);

int getche(void);

CHARACTER TEST FUNCTIONS


The C language provides many of character test functions that are used to test the character taken from the
Input.

FORMATTED I/O STATEMENTS

SNO FUNCTION TEST

1 isalnum(ch) Is ch an alphanumeric character

2 isalpha(ch) Is ch an alphabetic character

3 isdigit(ch) Is ch is digit

4 islower(ch) Is ch a lowercase letter

5 isupper(ch) Is ch a uppercase letter

6 isspace(ch) Is ch a blank space

7 toupper(ch) Convert ch to uppercase letter

8 tolower(ch) Convert ch to lowercase letter

Formatted I/O refers to input and output that has been arranged in a particular format using these
statements, the user must specify the type of data that is going to be accessed.
INPUT OUTPUT

scanf() printf()

fscanf() fprintf()

The scanf() function:


Input data can be entered into the computer using the standard input ‘C’ library function called
scanf().This function is used to enter any combination of input.

The scanf() function is used to read information from the standard input devices( keyboard).scanf()
starts with a string argument and may contain additional arguments.

Syntax:

scanf(“control string”,&var1,&var2,--&varn);

The control string consists of character groups. each character group must begin with a percentage
sign ‘%’.The character group contains percentage sign, followed by conversion character.

var1,var2--- are the arguments or variables in which the data is going to be accepted.

Example:

int n;

scanf(“%d”,&n);

CONTROL STRING

It is the type of data that the user going to accept via the input statements, this can be formatted and
always preceded with a ‘%’ sign

SNO FORMAT CODE MEANING

1 %c SINGLE CHARACTER

2 %d DECIMAL INTEGER

3 %s STRING

4 %f FLOAT

5 %ld LONG INTEGER

6 %u UNSIGNED INTEGER
7 %o OCTAL INTEGER

8 %x HEXADECIMAL INTEGER

9 %e FLOAT

10 %h SHORT INTEGER

CONVERSION SPECIFIERS

CODE FORMAT

%a Hexa decimal output in the form of 0xh.hhhhp+d(C99 only)

%s String of characters (until null zero is reached )

%c Character

%d Decimal integer

%f Floating-point numbers

%e Exponential notation floating-point numbers

%g Use the shorter of %f or %e

%u Unsigned integer

%o Octal integer

%x Hexadecimal integer

%i Signed decimal integer

%p Display a pointer

%n The associated argument must be a pointer to integer, This sepecifier causes the
number of characters written in to be stored in that integer

%hd short integer

%ld long integer

%lf long double

%% Prints a percent sign (%)


Each variable name must be preceded by an ampersand (&).The symbol gives the meaning “ADDRESS
OF” the variable.

The scanf() control string consists of ‘%’ at the beginning and type indicator at the end.Apart from that
it can have *,a maximum field width indicator and a type indicator modified.

Example:

%10.2f

%10d

Note: The * is used to supress input

Example:

%*d.

If input consists of 6 values and we want to ignore the middle 3 values we can write:

scanf(“%d%d%*d%*d%*d%d”,&a,&b,&c,);

So,if our input is 10 20 30 40 50 60 It will get values 10 to a, 20 to b ,30 to c.

RULES:

1.The control string must be preceded with sign and must be within quotations.i.e the address of the
variable should be passed.

2.If there is a number of input data items ,items must be separated by commas and must be preceded
with(&) sign except for string input.

3.The control string and the variables going to input should match with other.

4.It must have termination with semicolon.

5.The scanf() reads the data values until the blank space in numeric input or maximum number of
character have been read,or an error is detected.

THE PRINTF() FUNCTION:


Output data or result of an operation can be displayed from the computer to a standard output device
using the library function printf().This function is used to output any combination data.

Syntax:

printf(“control string”,var1,var2,-- varn);

Example: printf(“RESULT=%d”,n);
Field width plays an important role in printf statements while producing reports in a formatted
manner. Field width indicates the least number of columns that will be located to the output.

Example:

i=29;

Its field width is %4d

OUTPUT:

SPACE SPACE 2 9

If the value is more than specified columns, field width is ignored and number of column used is equal
to the number of column required by the arguments.

Example:

i=12345;

5 columns are required and used even if %4d specified also.

Control Statements
In a program all the instructions are executed sequentially by default. In some situation we may have
to change the execution order of statements based on condition or to repeat a set of statements until
certain conditions are met .In such situations conditional and control statements are very useful.

C language provides 3 types of control statements.


1) Sequential statements: In which instructions are executed in sequence.

Example:

i=i+1;

j=j+1;

These statements are executed one by one.

2) Selection statements: Here the sequence of the instructions are determined by using the result of
the condition.

Example:

if(x>y)
i=i+1;

else

j=j+1

3) Iteration Structure: In which statements are repeatedly executed .These forms program loops.

Example:

for(i=0;i<=9;i++)

i=i+1;

where the statement i=i+1 will be executed 10 times.

If Statement:

The if staement is a decision making statement.It is used to control the flow of execution of statements
and also used to test logically whether the condition is true or false .It is always used in conjunction
with condition .The statement is used when a question require answer.

Syntax1:

if(condition)

statement;

Syntax2:

if(condition)

statements;

If the condition is true, then the statements are executed. The statements may be a single or group of
statements.

If-else Statement:

It is two way decision making statement and always used in conjunction with condition .It is used to
control the flow of execution and also used to carry out the logical test and then pickup one of the two
possible actions on the logical test.
It is used to execute some statements when the condition is true and execute some other statements,
when the condition is false.

Syntax:

if(condition)

statements;

else

statements;

Nested if-else Statement:

When a series of if-else statements are occurred in a program. we can write an entire if-else statement
in another if-else statement called nesting and the statement is called nested if.

Syntax: if(condition)

{ if(condition)

{ statement2;

else {

statement3; }

} else

statement1;

If–else ladder:
Nested if statements can become complex if there are more than 3 alternatives and indentation is not
consistent, it may be different for us to determine the logical structure of the if statement. In this
situation we can use the nested if as the else if ladder.

Syantax: if(condition1)

{ staement1;

else if(condition2)

{ statement2;

else if(condition3)

{ staement3;

else { default statement;

Flowchart:

simple if:

• /* check a citizen is eligible for voting */


#include<stdio.h>

int main()
{

int age;

printf(“Enter the age : ”);

scanf(“%d”,&age);

if(age >= 18)

printf(“Eligible for voting…”);

getch();

IF-ELSE FLOW CHART

/* print a number is even or odd */


#include<stdio.h>

int main()

int number;

printf(“Enter a number : “);

scanf(“%d”, &number);

if((number %2) == 0)
printf(“%d is even number.”,number);

else

printf(“%d is odd number.”,number);

• /* check whether a year is leap year or not */


#include<stdio.h>

void main()

int year;

printf("Enter the year ?");

scanf("%d",&year);

if((year %100) == 0)

if((year % 400) == 0)

printf("%d is leap year.",year);

else

printf("%d is not leap year.",year);


}

else

if((year % 4) == 0)

printf("%d is leap year.",year);

else

printf("%d is not leap year.",year);

getch();

/* program to print the grade of student */


#include<stdio.h>

voidmain()

int marks;

printf("Enter marks ? ");

scanf("%d", &marks);
if(marks >= 75)

printf("Distinction");

else if(marks >= 60)

printf("First class");

else if(marks >= 50)

printf("Second class");

else if(marks >= 35)

printf("Third class");

else

printf("Failed");

/* Write a C program toe find the roots of a quadratic equation. */


#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

float a,b,c,root1,root2;

clrscr();

printf("\n Enter values of a,b,c for finding roots of a quadratic eq:\n");

scanf("%f%f%f",&a,&b,&c);

/*checking condition*/

if(b*b>4*a*c)

root1=-b+sqrt(b*b-4*a*c)/2*a;

root2=-b-sqrt(b*b-4*a*c)/2*a;

printf("\n*****ROOTS ARE*****\n");
printf("\n root1=%f\n root2=%f",root1,root2);

else

printf("\n Imaginary Roots.");

getch();

SWITCH CASE:
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.

SYNTAX:
switch(expression)

case constant-expression : statement(s); break;

case constant-expression : statement(s); break;

/* you can have any number of case statements */

default : statement(s);

The following rules apply to a switch statement:

 The expression used in a switch statement must have an integral or enumerated type, or be of
a class type in which the class has a single conversion function to an integral or enumerated
type.

 You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.

 The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.

 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.

 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.

• /* program to simulate a simple calculator */


#include<stdio.h>

void main()

float a,b;

char opr;

printf("Enter number1 operator number2 : ");

scanf("%f %c %f",&a,&opr,&b);

switch(opr)

case '+':
printf("Sum : %f",(a + b));

break;

case '-':

printf("Difference : %f",(a - b));

break;

case '*':

printf("Product : %f",(a * b));

break;

case '/':

printf("Quotient : %f",(a / b));

break;

default:

printf("Invalid Operation!");

/* Write a C program, which takes two integer operands and one operator form the
user, performs the operation and then prints the result. (Consider the operators +,-,*,
/, % and use Switch Statement) */
#include<stdio.h>

#include<conio.h>

void main()

int a,b,res,ch;

clrscr();

printf("\t *********************");

printf("\n\tMENU\n");

printf("\t********************");

printf("\n\t(1)ADDITION");
printf("\n\t(2)SUBTRACTION");

printf("\n\t(3)MULTIPLICATION");

printf("\n\t(4)DIVISION");

printf("\n\t(5)REMAINDER");

printf("\n\t(0)EXIT");

printf("\n\t********************");

printf("\n\n\tEnter your choice:");

scanf("%d",&ch);

if(ch<=5 & ch>0)

printf("Enter two numbers:\n");

scanf("%d%d",&a,&b);

switch(ch)

case 1:

res=a+b;

printf("\n Addition:%d",res);

break;

case 2:

res=a-b;

printf("\n Subtraction:%d",res);

break;

case 3:

res=a*b;

printf("\n Multiplication:%d",res);

break;
case 4:

res=a/b;

printf("\n Division:%d",res);

break;

case 5:

res=a%b;

printf("\n Remainder:%d",res);

break;

case 0:

printf("\n Choice Terminated");

exit();

break;

default:

printf("\n Invalid Choice");

getch();

LOOPS:
There may be a situation, when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated execution
paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:
FOR LOOP
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax:

The syntax of a for loop in C programming language is:

for ( init; condition; increment )

statement(s);

Here is the flow of control in a for loop:

The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of
the loop does not execute and flow of control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
for loop terminates.
• FLOWCHART

FORLOOP

/* check whether a number is prime or not */


#include<stdio.h>

int main()

int n,i,factors = 0;

printf("Enter a number : ");

scanf("%d",&n);

for(i = 1; i <= n; i++)

{
if((n % i)==0) ++factors;

if (factors == 2)

printf("%d is prime number.",n);

else

printf("%d is not prime number.",n);

/* Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user. */
#include <stdio.h>

void main()

int no,counter,counter1,check;

clrscr();

printf("<-----------------------PRIME NO. SERIES------------------------>");

printf("\n\n\n\t\t\tINPUT THE VALUE OF N: ");

scanf("%d",&no);

printf("\n\nTHE PRIME NO. SERIES B/W 1 TO %d : \n\n",no);

for(counter = 1; counter <= no; counter++)

check = 0;

//THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.

for(counter1 = counter-1; counter1 > 1 ; counter1--)

if(counter%counter1 == 0)

{
check++; // INCREMENT CHECK IF NO. IS NOT A PRIME NO.

break;

if(check == 0)

printf("%d\t",counter);

getch();

/* Write a C program to calculate the following Sum:

Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! */
#include <stdio.h>

#include <math.h>

void main()

int counter,f_coun;

float sum=0,x,power,fact;

clrscr();

printf("<-----------------------PROGRAM FOR SUM OF EQ. SERIES----------------------->");

printf("\n\n\tEQUATION SERIES : 1- X^2/2! + X^4/4! - X^6/6! + X^8/8! - X^10/10!");

printf("\n\n\n\tENTER VALUE OF X : ");

scanf("%f",&x);

for(counter=0, power=0; power<=10; counter++,power=power+2)

fact=1;

//CALC FACTORIAL OF POWER VALUE


for(f_coun=power; f_coun>=1; f_coun--)

fact *= f_coun;

//EQ. FOR SUM SERIES

sum=sum+(pow(-1,counter)*(pow(x,power)/fact));

printf("SUM : %f",sum);

getch();

Program to display 10 numbers


#include <stdio.h>

int main ()

for( int a = 0; a <=9; a = a + 1 )

printf("value of a: %d\n", a);

/* The total distance travelled by vehicle in ’t’ seconds is given by distance =


ut+1/2at2 where 'u' and 'a' are the initial velocity (m/sec.) and acceleration
(m/sec2). Write C program to find the distance travelled at regular intervals of time
given the values of 'u' and 'a'. The program should provide the flexibility to the user to
select his own time intervals and repeat the calculations for different values of 'u' and
'a'.*/
#include <stdio.h>

#include <math.h>

void main()

int tim_intrval, counter,time;


float accl, distance=0, velos;

clrscr();

printf("PROGRAM FOR CALC TOTAL DISTANCE TRAVELED BY A VECHIAL”);

printf("\n\n\n\t\t\tNO OF TIME INTERVALS : ");

scanf("%d",&tim_intrval);

for(counter = 1; counter <= tim_intrval; counter++)

printf("\n\t\t\tAT T%d TIME(sec) : ",counter);

scanf("%d",&time);

printf("\t\t\tVELOCITY AT %d sec (m/sec) : ",time);

scanf("%f",&velos);

printf("\t\t\tACCLERATION AT %d sec (m/sec^2): ",time);

scanf("%f",&accl);

distance += (velos*time + (accl*pow(time,2))/2);

printf("\n\n\n\tTOTAL DISTANCE TRAVELLED BY VEHICLE IN %d INTERVALS OF TIME :


%f",tim_intrval,distance);

getch();

/*Write a C program to read in two numbers, x and n, and then compute the sum of this geometric
progression:1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the program computes
1+5+25+125.Print x, n, the sum Perform error checking. For example, the formula does not make
sense for negative exponents - if n is less than 0. Have your program print an error message if n<0,
then go back and read in the next pair of numbers of without computing the sum.Are any values of x
also illegal ? If so, test for them too. */

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

int s_sum,i,x,n;

clrscr();
printf("Enter the values for x and n:");

scanf("%d %d",&x,&n);

if(n<=0 || x<=0)

printf("Value is not valid\n");

else

printf("Value is valid\n");

s_sum=1;

for(i=1;i<=n;i++)

s_sum=s_sum+pow(x,i);

printf("Sum of series=%d\n",s_sum);

getch();

WHILE LOOP
A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.

Syntax:

The syntax of a while loop in C programming language is:

while(condition)

statement(s);

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop

FLOW CHART

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed

/* Write a C program to find the sum of individual digits of a positive integer.*/

#include<stdio.h>

#include<conio.h>

void main()

int num, k=1, sum=0;

clrscr();

printf("Enter the number whose digits are to be added:");

scanf("%d",&num);

while(num!=0)

k=num%10;

sum=sum+k;

k=num/10;

num=k;

}
printf("Sum of the digits:%d",sum);

getch();

PROGRAM TO DIPLAY 10 NUMBERS

#include <stdio.h>

void main ()

int a = 0;

while( a <=10 )

printf("value of a: %d\n", a);

a++;

DO WHILE:
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming language checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.

Syntax:

The syntax of a do...while loop in C programming language is:

do

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
PROGRAM TO DISPLAY 10 NUMBERS

#include <stdio.h>

int main ()

int a = 0;

do

printf("value of a: %d\n", a);

a = a + 1;

while( a < 9 );

C Programming break and continue Statement


There are two statements built in C, break; and continue; to interrupt the normal flow of control of a
program. Loops perform a set of operation repeatedly until certain condition becomes false but, it is
sometimes desirable to skip some statements inside loop and terminate the loop immediately without
checking the test expression. In such cases, break and continue statements are used.

break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The break
statement is used with conditional if statement.

Syntax of break statement

break;

continue Statement

It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements
are used.

Syntax of continue Statement

continue;

goto Statement

In C programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.

Syntax of goto statement

goto label; ............. ............. label: statement;

In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code/s after it.

You might also like