Share PDF

Search documents:
  Report this document  
    Download as PDF   
      Share on Facebook

Unit-1: Introduction, Problem solving and Basics of C

UNIT-1

INTRODUCTION TO COMPUTERS

1.1 COMPUTER SYSTEMS

A computer is a system made of two major components: hardware and software. The computer hardware is the physical equipment. The software is the collection of programs (instructions) that allow the hardware to do its job.

Computer

System

Hardware

Software

1.1.1 Computer Hardware

The hardware component of the computer system consists of five parts: input devices, central processing unit (CPU), primary storage, output devices, and auxiliary storage devices.

The input device is usually a keyboard where programs and data are entered into the computers. Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio input unit.

pg. 1

Unit-1: Introduction, Problem solving and Basics of C

The central processing unit (CPU) is responsible for executing instructions such as arithmetic calculations, comparisons among data, and movement of data inside the system. Today’s computers may have one, two, or more CPUs.

Primary storage, also known as main memory, is a place where the programs and data are stored temporarily during processing. The data in primary storage are erased when we turn off a personal computer or when we log off from a time-sharing system.

The output device is usually a monitor or a printer to show output. If the output is shown on the monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy.

Auxiliary storage, also known as secondary storage, is used for both input and output. It is the place where the programs and data are stored permanently. When we turn off the computer, or programs and data remain in the secondary storage, ready for the next time we need them.

1.1.2Computer Software

Computer software is divided in to two broad categories: system software and application software .System software manages the computer resources .It provides the interface between the hardware and the users. Application software, on the other hand is directly responsible for helping users solve their problems.

Software

 

 

System

 

 

Application

 

 

software

 

 

software

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

System

System

General

Application

Operating

 

 

support

Developmen

Purpose

Specific

Systems

 

 

 

 

 

 

 

 

 

 

Fig: Types of software

System Software:

System software consists of programs that manage the hardware resources of a computer and perform required information processing tasks. These programs are divided into three classes: the operating system, system support, and system development.

pg. 2

Unit-1: Introduction, Problem solving and Basics of C

The operating system provides services such as a user interface, file and database access, and interfaces to communication systems such as Internet protocols. The primary purpose of this software is to keep the system operating in an efficient manner while allowing the users access to the system.

System support software provides system utilities and other operating services. Examples of system utilities are sort programs and disk format programs. Operating services consists of programs that provide performance statistics for the operational staff and security monitors to protect the system and data.

The last system software category, system development software, includes the language translators that convert programs into machine language for execution, debugging tools to ensure that the programs are error free and computer –assisted software engineering (CASE) systems.

Application software:

Application software is broken in to two classes: general-purpose software and application –specific software. General purpose software is purchased from a software developer and can be used for more than one application. Examples of general purpose software include word processors, database management systems, and computer aided design systems. They are labeled general purpose because they can solve a variety of user computing problems.

Application –specific software can be used only for its intended purpose.

A general ledger system used by accountants and a material requirements planning system used by a manufacturing organization are examples of application-specific software. They can be used only for the task for which they were designed they cannot be used for other generalized tasks.

The relationship between system and application software is shown in the following figure.

pg. 3

Unit-1: Introduction, Problem solving and Basics of C

1.2 PROBLEM SOLVING

1.2.1 Computer Languages

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



1940’s

Machine level Languages



1950’s

Symbolic Languages



1960’s

High-Level Languages

Machine Languages:

In the earliest days of computers, the only programming languages available were machine languages. Each computer has its own machine language, which is made of streams of 0’s and 1’s.

Instructions in machine language must be in streams of 0’s and 1’s because the internal circuits of a computer are made of switches transistors and other electronic devices that can be in one of two states: off or on. The off state is represented by 0; the on state is represented by 1.

The only language understood by computer hardware is machine language.

Symbolic Languages:

In early 1950’s Admiral Grace Hopper, A mathematician and naval officer developed the concept of a special computer program that would convert programs into machine language. The early programming languages simply mirror to the machine languages using symbols of mnemonics to represent the various machine language instructions because they used symbols, these languages were known as symbolic languages.

Computer does not understand symbolic language it must be translated to the machine language. A special program called assembler translates symbolic code into machine language. Because symbolic languages had to be assembled into machine language they soon became known as assembly languages.

Symbolic language uses symbols or mnemonics to represent the various, machine language instructions.

High Level Languages:

Symbolic languages greatly improved programming effificiency; they still required programmers to concentrate on the hardware that they were using. Working with symbolic languages was also very tedious because each machine instruction has to be individually coded. The desire to improve programmer efficiency and to change the focus from the computer to the problem being solved led to the development of high-level language.

High level languages are portable to many different computers, allowing the programmer to concentrate on the application problem at hand rather than the intricacies of the computer. High-level languages are designed to relieve the programmer from the details of the assembly language. High level languages share one thing with symbolic languages;

pg. 4

Unit-1: Introduction, Problem solving and Basics of C

they must be converted into machine language. The process of converting them is known as compilation.

The first widely used high-level languages, FORTRAN (FORmula TRANslation) was created by John Backus and an IBM team in 1957; it is still widely used today in scientific and engineering applications. After FORTRAN was COBOL (Common Business-Oriented Language). Admiral Hopper was played a key role in the development of the COBOL Business language.

C is a high-level language used for system software and new application code.

1.2.2 Creating and Running Programs

Computer hardware understands a program only if it is coded in its machine language. It is the job of the programmer to write and test the program .There are four steps in this process:

Writing and Editing the program

Compiling the program

Linking the program with the required library modules

Executing the program.

Writing and Editing Programs:

The software used to write programs is known as a text editor. A text editor helps us enter, change, and store character data. Depending on the editor on our system, we could use it to write letters, create reports, or write programs. The main difference between text processing and program writing is that programs are written using lines of code, while most text processing is done with character and lines.

Text editor is a generalized word processor, but it is more often a special editor included with the compiler. Some of the features of the editor are search commands to locate and replace statements, copy and paste commands to copy or move statements from one part of a program to another, and formatting commands that allow us to set tabs to align statements.

After completing a program, we save our file with .c extension to disk. This file will be input to the compiler; it is known as a source file.

Compiling Programs:

The code in a source file stored on the disk must be translated into machine language; this is the job of the compiler. The c compiler is two separate programs: the preprocessor and the translator.

The preprocessor reads the source code and prepares it for the translator. While preparing the code, it scans for special instructions known as preprocessor commands. These commands tell the preprocessor to look for special code libraries, make substitutions in the code, and in other ways prepare the code for translation into machine language. The result of preprocessing is called the translation unit.

After the preprocessor has prepared the code for compilation, the translator does the actual work of converting the program into machine language. The translator reads the translation unit and writes the resulting object module to a file that can then be combined

pg. 5

Unit-1: Introduction, Problem solving and Basics of C

with other precompiled units to form the final program. An object module is the code in machine language. The output of the compiler is machine language code, but it is not ready to run; that is, it is not executable because it does not have the required C and other functions included.

Linking Programs:

A C program is made up of many functions. We write some of these functions, and they are a part of our source program. There are other functions, such as input/output processes and, mathematical library functions that exist elsewhere and must be attached to our program. The linker assembles all of these functions, ours and systems into our final executable program.

Executing Programs:

Once program has been linked, it is ready for execution. To execute a program we use an operating system command, such as run, to load the program into primary memory and execute it. Getting the program into memory is the function of an operating system program known as the loader. It locates the executable program and reads it into memory. When everything is loaded, the program takes control and it begins execution.

In a typical program execution, it reads data for processing, either from the user or from a file. After the program processes the data, it prepares the output. At output can be to the user’s monitor or to a file. When the program has finished its job, it tells the operating system, which then removes the program from memory.

pg. 6

Unit-1: Introduction, Problem solving and Basics of C

1.2.3 ALGORITHM /PSEUDOCODE

Pseudocode:

Pseudo code is an artificial and informal language that helps programmers develops algorithms. Pseudocode is similar to everyday English, it is convenient and user friendly although it is not an actual computer programming language. Psuedocode programs are not actually executed on computer rather they merely help the programmer “think out” a program before attempting to write it in a programming language such as C.

Algorithm:

An algorithm was developed by an Arab mathematician. It is chalked out step-by-step approach to solve a given problem. It is represented in an English like language and has some mathematical symbols like ->, >, <, = etc. To solve a given problem or to write a program we approach towards solution of the problem in a systematic, disciplined, non-adhoc, step-by-step way is called Algorithmic approach. Algorithm is a penned strategy (to write) to find a solution.

Properties of an Algorithm:

Finiteness: An algorithm terminates after a finite numbers of steps.

Definiteness: Each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion.

Input: An algorithm accepts zero or more inputs

Output: An algorithm should produce at least one output.

Effectiveness: It consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time.

Example: Algorithm/pseudo code to add two numbers

Step 1: Start

Step 2: Read the two numbers in to a, b

Step 3: c=a+b

Step 4: write/print c

Step 5: Stop.

1.2.4 FLOW CHART

A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm. Flow charts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals and small circles. These symbols are connected by arrows called flow lines.

(or)

The diagrammatic representation of way to solve the given problem is called flow chart.

pg. 7

Unit-1: Introduction, Problem solving and Basics of C

The following are the most common symbols used in drawing flowcharts:

Name

Symbol

Operation

Description

 

Oval

 

Terminal

start/stop/begin/end.

Parallelogram

 

Input/output

Making data available

 

 

 

For processing

(input) or

 

 

 

recording of the process

 

 

 

information (output).

Document

 

Print Out

show data output in

 

 

 

the form of document.

Rectangle

 

Process

any processing to be

 

 

 

Done .A process changes or

 

 

 

moves data. An

assignment

 

 

 

operation.

 

Diamond

 

Decision

Decision or switching

 

 

 

type of operations.

 

Circle

Connector

Used to connect

 

 

Different parts of flowchart.

Arrow

Flow

Joins two symbols

 

 

and also represents flow of

 

 

execution.

1.2.5 PROGRAM DEVELOPMENT STEPS

Program Development is a multistep process that requires that we understand the problem, develop a solution, write the program, and then test it. When we are given the assignment to develop a program, we will be given a program requirements statement and the

pg. 8

Unit-1: Introduction, Problem solving and Basics of C

design of any program interfaces. We should also receive an overview of the complete project so that we will take the inputs we are given and convert them to the outputs that have been specified. This is known as program design.

1. Understand the Problem

The first step in solving any problem is to understand it. By reading the requirements statements carefully, we fully understand it, we review our understanding with the user and the systems analyst to know the exact purpose.

2. Analysis

The method of solutions to solve the problem can be identified. We also judge that which method gives best results among different methods of solution.

3. Design

Algorithms and flow charts will be prepared. 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.

a. Compilation

The process of translating the program into machine code 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 (;).

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.

pg. 9

Unit-1: Introduction, Problem solving and Basics of C

1.3 BASICS OF C

1.3.1 History of C

C language facilitates a very efficient approach to the development and implementation of computer programs. C was invented and first implemented by Dennis Ritchie on a DEC PDP- 11 that used the UNIX operating system. C is the result of a development process that started with an older language called BCPL. BCPL was developed by Martin Richards, and it influenced a language called B, which was invented by Ken Thompson. B led to the development of C in the 1970s.

C Is a Middle-Level Language

C is often called a middle-level computer language, because it combines the best elements of high-level languages with the control and flexibility of assembly language.

1.3.2 Important features of C Language

C is a system programming language which provides flexibility for writing compilers, operating systems, etc.

It can also be used for writing the application programs for scientific, engineering and business applications.

C is famous for its portability, meaning that program written in C for one computer can be easily loaded to another computer with little or no changes.

C supports variety of data types like integers, float point numbers, characters, etc.

C is a procedure oriented language which is most suited for structured programming practice.

It provides a rich set of built in functions

Programs written in C are found to execute faster than compared to other languages.

1.3.3 Structure of a C program

The program written in C language follows this basic structure. The sequence of sections should be as they are in the basic structure. A C program should have one or more sections but the sequence of sections is to be followed.

Documentation section

Linking section

Definition section

Global declaration section

Main function section

{

Declaration section Executable section

}

Sub program or function section

pg. 10

Unit-1: Introduction, Problem solving and Basics of C

Documentation Section:

It comes first and is used to document the use of logic or reasons in your program. It can be used to write the program's objective, developer and logic details. The documentation is done in C language with /* and */ . Whatever is written between these two are called comments.

Linking Section:

This section tells the compiler to link the certain occurrences of keywords or functions in your program to the header files specified in this section.

Ex: #include <stdio.h>

Definition Section:

It is used to declare some constants and assign them some value.

Ex: #define MAX 25

Here #define is a compiler directive which tells the compiler whenever MAX is found in the program replace it with 25.

Global Declaration Section:

Here the variables which are used throughout the program (including main and other functions) are declared so as to make them global (i.e. accessible to all parts of program)

Ex: int i; main( )

{

………

}

Main Function Section: It tells the compiler where to start the execution from. main( )

{

point from execution starts

}

main function has two sections

i)Declaration section: In this the variables and their data types are declared.

ii)Executable section: This has the part of program which actually performs the task we need.

Sub Program or Function Section:

This has all the sub programs or the functions which our program needs.

Simple ‘C’ program:

/* simple program in c */ #include<stdio.h> main()

{

pg. 11

Unit-1: Introduction, Problem solving and Basics of C

printf(“welcome to c programming”); } /* End of main */

Characteristics of C language:

1.C language is simple to learn and simple to use.

2.C programs are efficient in terms of the execution speed.

3.C language contain many built-in functions.

4.C programs are portable from one environment to another environment.

5.C language supports modular programming

6.C language is also called as middle level language because it can be used to create high level programs and also low level programs such as assembly programs.

7.C language is case sensitive.

8.C language is widely used for developing system software.

The character set of ‘C’ language:

It contains the following four types of characters.

1.Alphabets: A-Z, a-z

2.Digits: 0-9

3.Special symbols: ‘C’ language consists of the following set of symbols used while writing the ‘C’ programs.

Symbol

Meaning

Symbol

Meaning

Symbol

Meaning

{

Opening curly

‘

apostrophe

^

Caret or exclusive

 

brace

 

 

 

OR

}

Closing curly

“

Double quotation

&

Ampersand

 

brace

 

mark

 

 

(

Opening

~

Negation or tilde

*

Asterisk

 

parenthesis

 

 

 

 

)

Closing

!

Exclamation

+

Plus

 

parenthesis

 

 

 

 

[

Opening square

#

Pound or number

-

Minus or hyphen

 

bracket

 

or hash

 

 

]

Closing square

%

mod

/

Forward slash

 

bracket

 

 

 

 

.

Dot or period

;

Semi-colon

\

Backward slash

?

Question Mark

:

Colon

>

Greater than

|

Pipe

,

Comma

<

Lesser than

_

Underscore

=

Assigns to

 

 

 

 

 

 

 

 

4.White spaces: these are the characters that are invisible to the user while typing the program. Examples include blank spaces, horizontal tabs, vertical tabs, new line character, carriage return, form feed.

pg. 12

Unit-1: Introduction, Problem solving and Basics of C

C tokens:

A ‘C’ token is the smallest individual unit in a ‘C’ program. ‘C’ tokens are divided into the following categories:

1.Keywords

2.Identifiers

3.Constants

4.Special symbols

5.Operators

1.Keywords:

Keywords are the reserved words which are predefined by the developers of C language. Every keyword will have a special meaning and purpose that cannot be changed by the programs. There are 32 keywords in C language as given below

auto

break

case

char

const

continue

default

do

double

else

enum

extern

Float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

 

2.Identifiers:

Identifiers are the names given to data variables, functions and other types of objects in a language. While chosing a name, the following rules must be considered.

1.The first character in the name should be either an alphabet or an underscore.

2.The other characters in the name can be alphabets, digits and underscore.

3.Names should not contain blank spaces and hyphens.

4.Keywords should not be used as names.

Example:

Valid

Invalid

xyz

my name

x12

1xy

_x52

Continue

my_name

2yz

 

 

3. Constants:

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

pg. 13

Unit-1: Introduction, Problem solving and Basics of C

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 */

078

/* Illegal: 8 is not an octal digit */

032UU

/* Illegal: cannot repeat a suffix */

Following are other examples of various type of Integer literals:

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. You can represent floating point literals either in decimal form or exponential form. While representing using decimal form, you 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.

Here are some 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.

pg. 14

Unit-1: Introduction, Problem solving and Basics of C

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

There are certain characters in C when they are proceeded by a back slash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here you 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

Following is the example to show few escape sequence characters:

#include <stdio.h>

int main()

{

printf("Hello\tWorld\n\n");

return 0;

}

When the above code is compiled and executed, it produces following result:

Hello World

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, and universal characters.

You can break a long lines 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, dear"

pg. 15

Unit-1: Introduction, Problem solving and Basics of C

"hello, \

dear"

"hello, " "d" "ear"

.

4. Special symbols:

There are several special symbols used in C language. Some symbols are given below ()- used to represent functions

[]-used to represent arrays {}-used to represent blocks

5. Operators:

Operator is a symbol which is used to perform a particular operation on data items. The data items on which the operations are performed are called as operands.

A valid combination of operators and operands is called as an expression.

Types of operators:

C language provides the following types of operators.

1.Arithmetic operators

2.Assignment operators

3.Relational operators

4.Logical operators

5.Bitwise operators

6.Increment/Decrement operators

7.Conditional operator

8.Special operators

1.Arithmetic operators:

C language supports or contains the following five types of arithmetic operations.

Operator

Name

Purpose

 

 

 

+

plus

Addition

-

minus

Subtraction

*

Asterisk

Multiplication

/

slash

Division

%

percentile

Modulo division

pg. 16

Unit-1: Introduction, Problem solving and Basics of C

The operator + can be used as both unary and binary operator. When it is used as unary operator, it represents the sign of the operand. When it is used as binary operator, it represents the addition operation.

Example:

Unary plus

Binary plus

x=+10

x=y+z

The operator - can be used as both unary and binary operator. When it is used as unary operator, it represents the sign of the operand. When it is used as binary operator, it represents the subtraction operation.

Example:

Unary minus

Binary minus

x= -10

x=y-z

The operator * can be used as both unary and binary operator. When it is used as unary operator, it represents pointer operation. When it is used as binary operator, it represents the multiplication operation.

Example:

Unary *

Binary *

x=*p

x=y*z

The operator / can be used as binary operator only. It represents division operation and returns the quotient of the division operation.

Example:

Binary division

x=y/z

if y=10, z=3 then x=3

The operator % can be used as binary operator only. It represents modulo division operation and returns the remainder of the division operation.

Example:

Binary modulo division

x=y%z

if y=10, z=3 then x=1

Unary operator: An operator which applies on only one operand is called an unary operator. Example: +x , -y etc

Binary operator: An operator which operates on two operands is called a binary operator. Example: a+b , x-y etc..

Ternary operator:An operator which operates on three operands is called a ternary operator.

Example : conditional operator

2. Assignment operator:

Assignment operator is a binary operator. The purpose of assignment operator is to store the value of right hand side of assignment operator into the operand on left hand side.

pg. 17

 

 

Unit-1: Introduction, Problem solving and Basics of C

Example:

 

 

 

Given values

Return value

 

 

x=10

x=10

 

 

y=5

y=5

 

 

a=x

a=10

 

 

b=x+y

b=15

 

The left hand side of an assignment operator must always be a single operand. The right hand side of an assignment operator can be a value, an operand or an expression.

Short hand assignment operators:

If the operand on L.H.S of an assignment operator is same as the operand on R.H.S, then short hand assignment operators can be used to represent that expression. The general form of short hand assignment operator is given below.

Example:

Given values

Return value

x+=5

x=x+5

x-=5

x=x-5

x*=5

x=x*5

x/=5

x=x/5

3. Relational operators:

There are 6 types of relational operators in C language.

Operator

Name

Purpose

 

 

 

<

less than

 

>

greater than

 

<=

less than or equal to

Compare any two

>=

greater than or equal to

quantities

= =

is equal to

 

 

 

 

!=

is not equal to

 

Any relational expression can return either true or false (1 or 0).

Example:

Given values

Return value

If a=10, b=20

 

a<b

True(1)

a>b

False(0)

a<=b

True(1)

a>=b

False(0)

a= =b

False(0)

a!=b

True(1)

4. Logical operators:

Logical operators are mainly used to combine relational expressions that forms a compound relational expression.

pg. 18

Unit-1: Introduction, Problem solving and Basics of C

There are 3 types of logical operators in C language.

Operator

Name

 

 

&&

logical AND

| |

logical OR

!

logical NOT

The logical AND is a binary operator which behaves according to the following truth table.

x

y

x&&y

T

T

T

T

F

F

F

T

F

F

F

F

Example:

Given values

Return value

If a=10, b=20, x=20, y=15

 

then

 

(a<b)&&(b<x)

False(0)

(a<x)&&(b>y)

True(1)

The logical OR is a binary operator which behaves according to the following truth table.

x

y

x| |y

T

T

T

T

F

T

F

T

T

F

F

F

Example:

Given values

Return value

If a=10, b=20, x=20, y=15

 

then

 

(a>b)||(x>y)

True(1)

(a>x)||(b<y)

False(0)

The logical NOT is an unary operator which is used to negate the truth value of a relational expression. The behavior of logical NOT operator is given in the following truth table.

 

 

x

!x

 

 

 

T

T

 

 

 

F

T

 

Example:

 

 

 

 

Given values

 

 

Return value

 

If a=10, b=20, x=20, y=15

 

 

then

 

 

 

 

!(a<b)

 

 

False(0)

 

!(x<y)

 

 

True(1)

pg. 19

Unit-1: Introduction, Problem solving and Basics of C

5. Bitwise operators:

Bitwise operators are used to perform operations on data items at bit level. C language provides the following types of bitwise operators given in the table.

Operator

Name

 

 

&

bitwise AND

||

bitwise OR

^

Exclusive OR

~

1’s complement/ negation

<<

left shift

>>

right shift

6. Increment / Decrement operators:

The increment operator (++) is used to add a quantity ‘1’ to the operand. Increment operators are divided into two types as given below.

Example:

Pre increment

Post increment

If ++x

If x++

Then x=x+1

Then x=x+1

When increment operators are combined with an assignment operator, then the behavior of preincrement will differ from post increment.

Example:

Pre increment

Return value

Post increment

Return value

If a=10, b=++a

 

If a=10, b=a++

 

Then

 

Then

 

1. a=a+1;

a=11

1. b=a;

b=10

2. b=a;

b=11

2. a=a+1;

a=11

The decrement operator (--) is used to subtract a quantity ‘1’ to the operand. Decrement operators are divided into two types as given below.

pg. 20

Unit-1: Introduction, Problem solving and Basics of C

Example:

Pre decrement

Post decrement

If - -x

If x- -

Then x=x-1

Then x=x-1

When decrement operators are combined with an assignment operator, then the behavior of predecrement will differ from post decrement.

Example:

Pre decrement

Return value

Post decrement

Return value

If a=10, b=--a

 

If a=10, b=a--

 

Then

 

Then

 

1. a=a-1;

a=9

1. b=a;

b=10

2. b=a;

b=9

2. a=a-1;

a=9

7. Conditional operator:

Conditional operator (?:) is a ternary operator which operates on three operands. The general syntax of conditional operator is given below.

(operand1) ? (operand2) : (operand3);

Here operand1 is generally a relational expression which returns either true or false. If operand1 is true, then operand2 will be executed. If operand1 is false, then operand3 will be executed.

The main purpose of a conditional operator is to evaluate simple conditions.

Example:

 

 

Given values

Return value

 

 

If x=10, y=20 and

 

 

 

C=(x<y)?(return x): (return y)

 

 

 

then

 

 

 

C

10

8. Special operators:

 

There are 2 types of special operators in C language.

 

1.

Comma operator

 

2.

sizeof() operator

 

The comma operator is used to combine several statements to form a compound statement.

Example:

Given values

Using comma operator

int a;

int a, b, c=20, x=5;

int b;

 

pg. 21

Unit-1: Introduction, Problem solving and Basics of C

int c=20; int x=5;

When more than one expression is combined using comma operator then the result of last expression will be returned by the comma operator.

Example:

Given values

Return value

If c=(a=10, b=20, a+b)

 

Then c

30

If c=(a=10, b=20, a-b, a+b)

 

Then c

30

The sizeof() operator is used to find the number of bytes required for a data item or variable.

compiler

int

float

char

16-bit

2

4

1

32-bit

4

4

1

Operator precedence and Associativity:-

Precedence is used to determine the order in which different operators in a compound expression are evaluated.

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

Example: consider the compound expression 2+3*4

Here multiplication operator (*) has the highest precedence and hence will be evaluated first. Therefore the above expression is equal to 2+(3*4)=14.

Associativity can be either Left to Right Associativity (or) Right to left Associativity.

Left to Right Associativity:

Expressions are evaluated by starting at left side and moving towards the right.

Right to Left Associativity:

Expressions are evaluated by starting at right side and moving towards the left.

Precedence levels of various operators are given in the following table along with their associativity with the same level operators.:

Precedence

Category

Operator

Operation

Associativity

1

Highest

( )

Functional call

 

 

precedence

[]

Array subscript

 

 

 



C indirect component selector

LR

 

 

::

C scope resolution

 

 

 

.

C direct component selector

 

2

Unary

!

Logical NOT

 

 

 

~

Bitwise (One’s) complement

 

pg. 22

Unit-1: Introduction, Problem solving and Basics of C

 

 

+

Unary plus

 

 

 

-

Unary minus

 

 

 

++

Increment

 

 

 

--

Decrement

RL

 

 

&

Address of

 

 

 

*

Indirection

 

 

 

sizeof( )

Sizeof

 

3

 

*

Multiplication

 

 

 

/

Division

LR

 

 

%

Modulus

 

4

Binary

+

Addition

LR

 

 

-

Subtraction

 

5

Shift

<<

Left shift

LR

 

 

>>

Right shift

 

6

Relational

<

Less than

 

 

 

>

Greater than

 

 

 

<=

Less than or equal to

LR

 

 

>=

Greater than or equal to

 

7

Equality

==

Equal to

LR

 

 

!=

Not equal to

 

8

Bitwise

&

Bitwise AND

LR

 

AND

 

 

 

9

Bitwise

^

Bitwise XOR

LR

 

XOR

 

 

 

10

Bitwise OR

|

Bitwise OR

LR

11

Logical

&&

Logical AND

LR

 

AND

 

 

 

12

Logical OR

||

Logical OR

LR

13

Conditional

?:

Conditional

RL

14

Assignment

=

Simple assignment

 

 

 

*=

Assign product

 

 

 

/=

Assign quotient

 

 

 

%=

Assign remainder

 

 

 

+=

Assign sum

 

 

 

-=

Assign difference

RL

 

 

&=

Assign bitwise AND

 

 

 

^=

Assign bitwise XOR

 

 

 

|=

Assign bitwise OR

 

 

 

>>=

Assign left shift

 

 

 

<<=

Assign right shift

 

15

Comma

,

Evaluation

LR

pg. 23

Unit-1: Introduction, Problem solving and Basics of C

Data types in C language:

The data types in ‘c’ language can be broadly classified into the following categories.

1.Primary data types

2.Derived data types

3.User defined data types

4.Empty data type

1.Primary data types (or) primitive data types (or) fundamental data types (or) basic data types (or) scalar data types (or) pre defined data types :

There are four kinds of primary data types in ‘c’ language.

1.int

2.float

3.char

4.double

int:

The “int” data type is used to store the integer values. The size of integer is either 2 bytes or 4 bytes based on the compiler. If the size of integer is 2 bytes, then its range will be -2^15 to 2^15-1. If the size of integer is 4 bytes, then its range will be -2^31 to 2^31-1.

Integer variables are declared by using the syntax int variablename;

Example: int x; float:

The “float” data type is used to store the real values. The size of integer is 4 bytes. The range of float data type will be 3.4*10^-38 to 3.4*10^38.

Float variables are declared by using the syntax

float variablename;

Example:float x; char:

The “char” data type is used to store a single character at a time. All the characters in ‘c’ language are represented using ASCII code. Therefore, the characters in ‘c’ language are also treated as integers. The size of char is 1 byte. The range of char data type will be -2^7 to 2^7-1.

Character variables are declared by using the syntax char variablename;

Example: char x;

double:

The “double” data type is used to store the real values. The size of integer is 8 bytes. The range of float data type will be 1.7*10^-38 to 1.7*10^38. It is an extension of float data type.

double variables are declared by using the syntax double variablename;

Example:double x;

pg. 24

Unit-1: Introduction, Problem solving and Basics of C

Datatype

Size(in bytes)

range

int

2 bytes or 4 bytes (varies from one compiler to

-32767 to +32767

 

another).

 

 

 

 

float

4 bytes or one word.

-3.4e38 to +3.4e38 with 6

 

 

digits of precision.

 

 

 

double

8 bytes or two words.

-1.7e308 to +1.7e308 with 10

 

 

digits of precision

 

 

 

char

1 byte.

-127 to +127

 

 

 

void

0 bytes.

Valueless

 

 

 

Derived data types:

There are 4 kinds of data types in ‘C’ language.

1.Arrays

2.Pointers

3.Structures

4.Unions

Arrays :

Arrays are the derived data types in C language which can store multiple data items at a time. All the data items are stored in physically continuous memory locations.

A

9

4

10

20

12

 

 

 

 

 

 

 

1000

1001

1002

1003

1004

Pointers :

Pointers are derived data types which can store the address of generic variables. Pointer can also be used to access the value of a variable indirectly.

Example: int *p,a=5; p=&a;

printf(“%d %d”,a, *p);

here, the value of ‘a’ is 5 and also the value of ‘*p’ is 5.

Structures , Unions:

These are the derived data types which can store multiple data items of different data types. All the data items in a structure are stored in physically continuous memory locations.

Example: struct employee

{

char name[10]; int id;

float salary; };

pg. 25

Unit-1: Introduction, Problem solving and Basics of C

User defined data types:

There are 2 kinds of user defined data types in ‘C’ language.

1.typedef

2.enum

typedef: typedef is used to define a new data type for the existing data types. Example: long int x,y;

typedef long int li; li x,y;

enum: enum is used to treat strings as numeric data. Example: enum day{Sunday, Monday,……, saturday}

Datatype

Size(in bytes)

range

 

 

 

char / signed char

1

-127 to +127

 

 

 

unsigned char

1

0 to 255

 

 

 

int / signed int / short int/ signed

2

-32767 to +32767

short int

 

 

 

 

 

unsigned int / unsigned short int

2

0 to 65535

 

 

 

long int / signed long int

4

-2,147,483,648 to +2,147,483,647

 

 

 

unsigned long int

4

0 to 4,294,967,295

 

 

 

float

4

-3.4e38 to +3.4e38 with 6 digits of

 

 

precision.

 

 

 

double

8

-1.7e308 to +1.7e308 with 10 digits of

 

 

precision.

 

 

 

long double

10

-1.7e4932 to +1.7e4932 with 10 digits

 

 

of precision.

 

 

 

TYPE CONVERSION:

In an expression that involves two different data types ,such as multiplying an integer and a floating point number to perform these evaluations ,one of the types must be converted.

We have two types of conversions

1.Implicit Type Conversion 2.Explicit Type Conversion

IMPLICIT TYPE CONVERSION:

When the types of the two operands in a binary expression are different automatically converts one type to another .This is known as implicit type conversion .

pg. 26

Unit-1: Introduction, Problem solving and Basics of C

EXPLICIT TYPE CONVERSION:

Explicit type conversion uses the unary cast operator ,to convert data from one type to another. To cast data from one type to another ,we specify the new type in parentheses before the value we want converted.

For example ,to convert an integer ,a , to a float, we code the expression like (float) a

pg. 27