5 introduction-to-c

50
INTRODUCTION TO C PRGRAMMING

Upload: rohit-shrivastava

Post on 13-Apr-2017

258 views

Category:

Healthcare


0 download

TRANSCRIPT

Page 1: 5 introduction-to-c

INTRODUCTION TO C PRGRAMMING

Page 2: 5 introduction-to-c

About C Developed in 1972 By Dennis Ritchie at AT

& T Bell Lab in USAMany ideas took from BCPL and B

languages so gave name C.Structured programming is possible by

using FunctionsExtension is easily possible by introducing

new librariesIn 1989, C is accepted by ANSI (American

national standardization institute)

2

Page 3: 5 introduction-to-c

Why C if we have C++,C# and Java 1. Very difficult to learn C++,C# and Java

without knowing C.2. Major parts of OS like Windows,UNIX, Linux

and Device drivers etc. are still in C because performance wise C is better than other.

3. C programs are comparatively time and memory efficient that’s why programs related to Mobile Devices, microwave ovens, washing machine etc. written in C.

4. Professional 3D games also written in C because of speed.

3

Page 4: 5 introduction-to-c

First C Program

4

/* First C Program */

Page 5: 5 introduction-to-c

Original C Compiler IDE

5

Page 6: 5 introduction-to-c

Console Screen or Result screen

6

Page 7: 5 introduction-to-c

Preprocessor Directive The text inside /* and */ is called comment or documentation. The statement starting with # (hash sign) is called pre-processor statement. The #include is a "preprocessor" directive that tells the compiler to put

code from the header called stdio.h into our program before actually creating the executable.

By including header files, you can gain access to many different functions--both the printf and scanf functions are included in stdio.h.

getch has its prototype in conio.h header file. stdio.h is a header file which has:

o Prototype or declaration only of the library functionso Predefined constantsNote: Header file does not contain the code of library functions. It

only contains the header or prototype.

 

7

Page 8: 5 introduction-to-c

main Function A program may contain many functions, but it

essentially contains a main function. The return type of main function is kept int

type. A program should return value.o 0 (zero) in case of normal termination.Non-zero

in case of abnormal termination, i.e. termination due to some error.

Page 9: 5 introduction-to-c

Pre-processing:o Pre-processing statements are processed first o All the statements starting with #(hash) sign are

preprocessing statementso eg. #include and #define

Compilation: The syntactical validity of the complete program is checkedo If there is no error the compiler generates the object

code (.obj) Linking: Symbolic Links are resolved in this phase

o A function call is called symbolic link o A function can be user defined or ready made function

in the libraryo The linker substitutes the name of the function with the

address of the first instruction of the function Execution: The Instruction of object code are

executed one by one.

Steps of Program Execution

Page 10: 5 introduction-to-c

Steps of Program Execution Pre-processing Compilation

Linking Loading Execution

Alt + F9

Ctrl+ F9

Page 11: 5 introduction-to-c

Types of Errors Syntax error: When there is the violation of

the grammatical ( Syntax) rule. Detected at the compilation time.o Semicolon not placedo Standard Construct not in proper formato Identifier not declared

Linker Error: When definition or code of a program is not found.o Path of header not properly definedo Library file not foundo The function name is misspelled

Page 12: 5 introduction-to-c

Types of Errors Cont... Runtime error: It is generated during execution phase.

Due to mathematical or some operation generated at the run time.o Division by zeroo Square root of negative numbero File not foundo Trying to write a read only file

Logical Error: Produced due to wrong logic of program. Tough to identify and even tougher to remove.o Variables not initializedo Boundary case errors in loopso Misunderstanding of priority and associativity of

operators

Page 13: 5 introduction-to-c

Types of Statements in C Prog. Preprocessing Statements: Also called compiler

directives. The purpose depends on the type of commands.o # include statement inserts a specified file in our

programo They don't exist after compilation

Declarative Statements: Used to declare user identifier i.e. to declare data types for example: int a, b;o These statements do not exist in the object code.

Page 14: 5 introduction-to-c

Types of Statements in C Prog. Cont...

Executable Statements: The statements for which the executable or binary code is generated. Foro Input/Output Statements like printf(), scanf()o Assignment Statements. The syntax is

lvalue=rvalueo Conditional Statements like if(a>b) max =a; else

max=b;o Looping Statements. Also called Iterative

statements or repetitive statements.Forwhile do while

o Function Call like y=sin(x);

Page 15: 5 introduction-to-c

Types of Statements in C Prog. Cont...

Special Statements: There are four special statementsobreakocontinueo returnoexit

Page 16: 5 introduction-to-c

Keywords & Identifiers Every C word is classified as either a

keyword or an identifier. Keywords: The meaning of some words is

reserved in a language which the programmer can use in predefined manner. Theses are called keywords or reserve words. For example: do, while, for, if, break, etc…

Identifiers refers to the names of variables , function, structure and array.

Examples: main, printf, average, sum etc.

Page 17: 5 introduction-to-c

32 -Reserved Words (Keywords) in C

auto breakcase charconst continuedefault dodouble elseenum externfloat forgoto if

int longregister returnshort signedsizeof staticstruct switchtypedef unionunsigned voidvolatile while

Page 18: 5 introduction-to-c

Rules of Making Identifier or variable

Rule1. Identifier name can be the combination of alphabets (a – z and A - Z), digit

(0 -9) or underscore (_). E.g. sum50, avgUpto100 etc. Rule 2. First character must be either alphabet or underscore E.g. _sum, class_strength,height are valid 123sum, 25th_var are invalidRule 3. Size of identifier may vary from 1 to 31 characters but some compilersupports bigger size variable name also.Rule-4. No space and No other special symbols(!,@,%,$,*,(,),-,+,= etc) except

underscore are allowed in identifier name. Valid name:  _calulate, _5,a_, __ etc. Invalid name: 5@, sum function, Hello@123 etc.Rule 5. Variable name should not be a keyword or reserve wordInvalid name: interrupt, float, asm, enum etc.

Page 19: 5 introduction-to-c

Rule 6: Name of identifier cannot be exactly same as of name of function or the name of other variable within the scope of the function.

What will be output of following program? #include<stdio.h> int sum(); int main(){  int sum;    sum=sum();  printf("%d",sum);    return 0;

} int sum(){

int a=4,b=6,c;c=a+b;

return c;}Output: Compiler error

19

Page 20: 5 introduction-to-c

What Are Variables in C?Variables are named memory location. It may be

used for storing a data value. A variable may take different values at different time during execution. Example int avg,length etc.

Naming Convention for Variables:C programmers generally agree on the following

conventions for naming variables.1. Use meaningful identifierseg for storing sum use variable name sum 2. Separate “words” within identifiers with underscores or

mixed upper and lower case. Examples: surfaceArea, surface_Area

surface_area etc

Page 21: 5 introduction-to-c

Case SensitivityC is case sensitive

It matters whether an identifier, such as a variable name, is uppercase or lowercase.

Example:areaAreaAREAArEa

are all seen as different variables by the compiler.

Page 22: 5 introduction-to-c

Identify valid variable name John X1 _ Group one Int_type Price$ char (area) 1ac i.j if

22

ValidValidValidInvalid- no white space allowed ValidInvalid- no special symbol allowed other than _Invalid- no keyword allowedInvalid- no special symbol allowed other than _Invalid- numeral cant be 1st characterInvalid- . Is special symbolInvalid- no keyword allowed

Page 23: 5 introduction-to-c
Page 24: 5 introduction-to-c

The C Character Set

A character denotes any alphabet, digit or special symbol used to represent information.

Figure 1 shows the valid alphabets,numbers and special symbols allowed in C.

Page 25: 5 introduction-to-c

Constants and Variables The alphabets, numbers and special symbols when properlycombined form constants, variables and keywords.A constant is an entity that doesn’t change whereas a

variable is an entity that may change.In any program we typically do lots of calculations. The

results of these calculations are stored in computers memory. Like human memory the computer memory also consists of millions of cells. The calculated values are stored in these memory cells. To make the retrieval and usage of these values easy these memory cells (also called memory locations) are given names. Since the value stored in each location may change the names given to these locations are called variable names.

Page 26: 5 introduction-to-c

Example of Variable and Constant

Here 3 is stored in a memory location and a name x is given to it.Then we are assigning a new value 5 to the same memory location x. This would overwrite the earlier value 3, since a memory location can hold only one value at a time. Since the location whose name is x can hold different values at different times x is known as a variable. As against this, 3 or 5 do not change, hence are known as constants.

Page 27: 5 introduction-to-c

Types of C ConstantsC constants can be divided into two major categories:(a) Primary Constants(b) Secondary ConstantsThese constants are further categorized as shown in

Figure

Page 28: 5 introduction-to-c

Integer ConstantsRules for Constructing Integer Constants1. An integer constant must have at least one digit.2. It must not have a decimal point.3. It can be either positive or negative.4. If no sign precedes an integer constant it is assumed to be5. positive.6. No commas or blanks are allowed within an integer constant.7. The allowable range for integer constants is -32768 to 32767. Ex. 426 +782 -8000 -760525,000, 67 000 are invalid integers

28

Page 29: 5 introduction-to-c

Real or Floating Point Constants Rules for Constructing Real Constants Real constants are often called Floating Point constants.

The real constants could be written in two forms—Fractional form and Exponential form.

Following rules must be observed while constructing realconstants expressed in fractional form:1. A real constant must have at least one digit.2. It must have a decimal point.3. It could be either positive or negative.4. Default sign is positive.5. No commas or blanks are allowed within a real constant. Ex.: +325.34, 426. , -32.76 , -48.5792, +.5

29

Page 30: 5 introduction-to-c

Exponential Form of Real constants

Used if the value of the constant is either too small or too large. In exponential form of representation, the real constant is represented in two parts: The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’

is called exponent. Rules:1. The mantissa part and the exponential part should be separated by a letter e.2. The mantissa part may have a positive or negative sign.3. Default sign of mantissa part is positive.4. The exponent must have at least one digit, which must be a5. positive or negative integer. Default sign is positive.6. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.Ex.: +3.2e-5, 4.1e8, -0.2e+3, -3.2e-57500000000 will be 7.5E9 or 75E8

30

Page 31: 5 introduction-to-c

Character ConstantRules for Constructing Character Constants1. A character constant is a single alphabet, a single

digit or asingle special symbol enclosed within single inverted

commas. 2. Both the inverted commas should point to the left.For example, ’A’ is a valid character constant

whereas ‘A’ is not.3. The maximum length of a character constant

can be 1 character.Ex.: 'A‘, 'I‘, '5‘, '='

31

Page 32: 5 introduction-to-c

Declaring VariablesBefore using a variable, you must give the compiler

some information about the variable; i.e., you must declare it.

The declaration statement has following format <Data Type> <Variable name>Data type will indicate the type of variable just like

variable may integer type so data type int will be used.

Examples of variable declarations: int length ; float area ;

char ch;

Page 33: 5 introduction-to-c

Declaring Variables (con’t)When we declare a variable

Space is reserved in memory to hold a value of the specified data type

That space is associated with the variable name.That space is associated with a unique address.If we are not initializing variable than space has no known

value(garbage value).Visualization of the declaration

int a ;

a

2000

3718

int

Page 34: 5 introduction-to-c

Declaring Variables (con’t)

meatballs

FE07

garbage

int

Page 35: 5 introduction-to-c

Notes About VariablesYou must not use a variable until you

somehow give it a value.You can not assume that the variable will

have a value before you give it one.Some compilers do, others do not! This is

the source of many errors that are difficult to find.

Assume your compiler does not give it an initial value!

Page 36: 5 introduction-to-c

Using Variables: InitializationVariables may be be given initial values, or

initialized, when declared. Examples:

int length = 7 ;

float diameter = 5.9 ;

char initial = ‘A’ ;

7

5.9

‘A’

length

diameter

initial

Page 37: 5 introduction-to-c

Data TypesTo deal with some data, we have to mention its type

(i.e. whether the data is integral, real, character or string etc.) So data types are used to tell the types of data.

Data Types Categories

Page 38: 5 introduction-to-c

Fundamental or Primitive Data Types

Page 39: 5 introduction-to-c

Data Types Range

Page 40: 5 introduction-to-c

Data Types Format Specifier

Page 41: 5 introduction-to-c

Sample C Program#include<stdio.h>#include<conio.h>void main(){int a;char b;float c;a=10;b=‘A’;c=50;printf(“b=%c ,a=%d,c= %f”,b,a,c);getch();} Output:

456372000 2001 2002 2003 2004 2005

b-12

3000 3001 3002 3003 3004 3005c

000056424000 4001 4002 4003 4004 4005

a

Page 42: 5 introduction-to-c

Sample C Program#include<stdio.h>#include<conio.h>void main(){int a;char b;float c;a=10;b=‘A’;c=50;printf(“b=%c ,a=%d,c= %f”,b,a,c);getch();} Output:

102000 2001 2002 2003 2004 2005

bA

3000 3001 3002 3003 3004 3005c

50.000000 4000 4001 4002 4003 4004 4005

a

Page 43: 5 introduction-to-c

Sample C Program(Modified-1)#include<stdio.h>#include<conio.h>void main(){int a;char b;float c;a=10;b=‘AB’;c=50;printf(“b=%c ,a=%d,c= %f”,b,a,c);getch();} Output:

102000 2001 2002 2003 2004 2005

bA

3000 3001 3002 3003 3004 3005c

50.000000 4000 4001 4002 4003 4004 4005

a

Page 44: 5 introduction-to-c

Sample C Program(modified-2)#include<stdio.h>#include<conio.h>void main(){int a;char b;float c;a=10;b=‘ABC’;c=50;printf(“b=%c ,a=%d,c= %f”,b,a,c);getch();} Output:

Page 45: 5 introduction-to-c

Sample C Program(modified-2)#include<stdio.h>#include<conio.h>void main(){int 5a;char b;float c;5a=10;b=‘A’;c=50;printf(“b=%c ,a=%d,c= %f”,b,5a,c);getch();} Output:

Page 46: 5 introduction-to-c

Sample C Program(Modified-3)#include<stdio.h>#include<conio.h>void main(){int a;char b;float c;a=32769;b=‘A’;c=50;printf(“b=%c ,a=%d,c= %f”,b,a,c);getch();} Output:

-327672000 2001 2002 2003 2004 2005

bA

3000 3001 3002 3003 3004 3005c

50.000000 4000 4001 4002 4003 4004 4005

a

Page 47: 5 introduction-to-c

Range of Unsigned int

Page 48: 5 introduction-to-c

Overflow in Unsigned intIf number is X where X is greater than 65535

thenNew value = X % 65536 If number is Y where Y is less than 0 thenNew value = 65536– (Y% 65536) (Take Y without

sign)Example:unsigned int X=67777;unsigned int Y= -10;X=2241Y=65526

Page 49: 5 introduction-to-c

Rang of int

Page 50: 5 introduction-to-c

Range of int If number is X where X is greater than 32767 thenp = X % 65536if p <=32767 then New value = pelse New value = p - 65536If number is Y where Y is less than -32768 thenp = Y % 65536 (Take Y without sign)If p <= 32767 then New value = -pelse New value = 65536 -pExample:int X=32768; =-32768int Y= -65537; = -1