C ppt slides

41
Objectives To review basic computer systems concepts To be able to understand the different computing environments and their components To review the history of computer languages To be able to list and describe the classifications of computer languages To understand the steps in the development of a computer program To review the system development life cycle Chapter 1 Chapter 1 Introduction to Computers Introduction to Computers

description

c intro

Transcript of C ppt slides

  • Objectives To review basic computer systems concepts To be able to understand the different computing environments and their components To review the history of computer languages To be able to list and describe the classifications of computer languages To understand the steps in the development of a computer program To review the system development life cycle Chapter 1Introduction to Computers

  • 1-1 Computer SystemsToday computer systems are found everywhere. Computers have become almost as common as televisions. But what is a computer? A computer is a system made of two major components: hardware and software.Computer HardwareComputer SoftwareTopics discussed in this section:

  • FIGURE 1-1 A Computer System

  • FIGURE 1-2 Basic Hardware Components

    McGraw-HillThe McGraw-Hill Companies, Inc., 2000

    Computer -- Hardware

    Key boardMouse Input Devices

    MonitorPrinter Output Devices

    Secondary Storage Devices

    Input Storage AreaProgram Storage Area Output Storage AreaWorking Storage Area Primary or Main Memory (RAM)

    Register 1Arithmeticand Logic UnitRegister 2Register NMicro Processor

    Computer Science: A Structured Programming Approach Using C

  • FIGURE 1-3 Types of Software

  • 1-2 Computing EnvironmentsIn 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. In this section we describe several different environments.Personal Computing EnvironmentTime-Sharing EnvironmentClient/Server Environment Distributed ComputingTopics discussed in this section:

  • FIGURE 1-5 Personal Computing Environment

  • FIGURE 1-6 Time-sharing Environment

  • FIGURE 1-7 The Client/Server Environment

  • FIGURE 1-8 Distributed Computing

  • 1-3 Computer LanguagesTo 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 LanguagesSymbolic Languages High-Level LanguagesTopics discussed in this section:

  • FIGURE 1-9 Computer Language Evolution

  • Machine Language Assembly Language High-Level LanguageThe only language the computer can understand is machine language (binary language).

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

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

    12345678910111213141516 entry main,^m sub12 #12,sp jsb C$MAIN_ARGS moveb $CHAR_STRING_CON pusha1 -8(fp) pusha1 (r2) calls #2,SCANF pusha1 -12(fp) pusha1 3(r2) calls #2,SCANF mull3 -8(fp),-12(fp),- pusha 6(fp) calls #2,PRINTF clrl r0 ret

    12345678910111213141516 00000000 00000100 000000000000000001011110 00001100 11000010 0000000000000010 11101111 00010110 0000000000000101 11101111 10111110 000000000000101111111000 10101101 11011111 0000000000010010 01100010 11011111 000000000001010111101111 00000010 11111011 000000000001011111110100 10101101 11011111 000000000001111000000011 10100010 11011111 000000000010000111101111 00000010 11011111 000000000010010001111110 11110100 1010110111111000 10101110 11000101 000000000010101100000110 10100010 11111011 000000000011000111101111 00000010 11111011 0000000000110100 01010000 11010100 0000000000111011 00000100 0000000000111101

    12345678910#includeint main(void){ int n1, n2,product; printf(Enter two numbers : ); scanf(%d %d,&n1,&n2); product = n1 * n2; printf(%d,product); return 0;}

    Computer Science: A Structured Programming Approach Using C

  • 1-4 Creating and Running ProgramsIn this section, 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 ProgramsTopics discussed in this section:

  • FIGURE 1-10 Building a C Program

  • 1-5 System DevelopmentWeve now seen the steps that are necessary to build a program. In this section, we discuss how we go about developing a program. This critical process determines the overall quality and success of our program. If we carefully design each program using good structured development techniques, our programs will be efficient, error-free, and easy to maintain.System Development Life CycleProgram DevelopmentTopics discussed in this section:

  • FIGURE 1-11 Waterfall Model

  • Program Development Steps

    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)CompilationTranslate 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+bThere is a syntax error in this statement, since, each and every statement in C language ends with a semicolon (;).

    4.b)ExecutionThe 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 terminates 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 ouz

    Computer Science: A Structured Programming Approach Using C

  • Executing a C programcompilesSyntaxErrors?YesObject machine code010110 100.01011 101C-compiler#includeint main(){ .TextEditorprog1.cprog1.objLinkerExecutable machine code00101010.01010101addsTranslators 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.machine code of library fileInputprog1.exeNoC-RuntimeExecutesFeedsRuntime or Logic Errors ?YesOutput

  • PseudocodeEnglish-like statements that follow a loosely defined syntax and are used to convey the design of an algorithm.Note

  • Structure of C programDocumentation SectionLinkage SectionDefinition SectionGlobal Declaration Section

    Main Function Section

    Local Declaration Part Executable Code Part

    Sub Program Section

    Function1() Function2() FunctionN()

  • C-Language Keywords(C99)auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while_Bool _Imaginary restrict_ComplexinlineCharacter Set of C-LanguageAlphabets : A-Z and a-zDigits : 0-9Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | \ { } [ ] : ; < > , . ? /White Spaces : space , Horizontal tab, Vertical tab, New Line Form Feed.

  • C-TokensTokens : The smallest individual units of a C- program are called Tokens. Key words, Identifiers, Constants, Operators, Delimiters.Key words : have a predefined meaning and these meanings cannot be changed. All keywords must be written in small letters (except additional c99 keywords).Identifiers : names of variables, functions, structures, unions, macros, labels, arrays etc., Rules for define identifiers : a) First character must be alphabetic character or under score b) Second character onwards alphabetic character of digit or under score. c) First 63 characters of an identifier are significant. d) Cannot duplicate a key word. e) May not have a space or any other special symbol except under score. f) C language is Case-sensitive.

  • C-TokensConstants : fixed values that do not change during execution of a program. Boolean constants : 0 ( false) and 1 (true) Character constants : only one character enclosed between two single quotes ( except escape characters ). wide character type - wchar_t - for Unicode characters. Integer constants : +123, -3454 , 0235 (octal value), 0x43d98 ( hexa - decimal value) 54764U, 124356578L, 124567856UL Float constants : 0.2 , 876.345, .345623 , 23.4E+8, 47.45e+6 String Constants : Hello world , Have a nice day! Complex Constants : real part + imaginary part * I ex : 12.3 + 3.45 * IOperators : a symbol, which indicates an operation to be performed. Operators are used to manipulate data in program.Delimiters : Language Pattern of c-language uses special kind of symbols: (colon, used for labels) ; (semicolon terminates statement ) ( ) parameter list [ ] ( array declaration and subscript ), { } ( block statement ) # ( hash for preprocessor directive ) , (comma variable separator )

  • Data Types ( pre defined )Type Typical Size in Bits Minimal Rangechar 8 127 to 127unsigned char 8 0 to 255signed char 8 127 to 127int 16 or 32 32,767 to 32,767unsigned int 16 or 32 0 to 65,535signed int 16 or 32 Same as intshort int 16 32,767 to 32,767unsigned short int 16 0 to 65,535signed short int 16 Same as short intlong int 32 2,147,483,647 to 2,147,483,647long long int 64 (263) to 263 1 (Added by C99)signed long int 32 Same as long intunsigned long int32 0 to 4,294,967,295unsigned long long int 64 264 1 (Added by C99)float 32 3.4e-38 to 3.4e+38double 64 1.7e-308 to 1.7e+308long double 80 3.4e-4932 to 1.1e+4932void--data type that not return any value

  • Conversion Specifiers CodeFormat%a Hexa decimal output in the form of 0xh.hhhhp+d(C99 only)%sString of characters (until null zero is reached )%cCharacter%dDecimal integer%fFloating-point numbers%eExponential notation floating-point numbers%gUse the shorter of %f or %e%uUnsigned integer%oOctal integer%xHexadecimal integer%iSigned decimal integer%pDisplay a pointer%nThe associated argument must be a pointer to integer, This sepecifier causes the number of characters written in to be stored in that integer.%hdshort integer%ldlong integer%lflong double%%Prints a percent sign (%)

  • Back Slash ( Escape Sequence) CharactersCode Meaning\b Backspace\f Form feed\n New line\r Carriage return\t Horizontal tab\" Double quote\' Single quote\ \ Backslash\v Vertical tab\a Alert\? Question mark\N Octal constant (N is an octal constant)\xN Hexadecimal constant (N is a hexadecimal constant)

  • Increment and Decrement Operatorsprefix increment (++a) postfix increment (a++) prefix decrement(- -a) postfix decrement (a- -)Before evaluation of expression Evaluation of expressionAfter evaluation of expressionand before leaving the statementExecutes all Prefix OperationsExecutes all Postfix Operations/* prefix operators */#includeint 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)/* prefix and postfix operators */#includeint 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 */#includeint 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 = 119 ( 12 * 7 + 5 * 7)

  • Bitwise Logical Operators& -- Bitwise AND

    | -- Bitwise OR

    ^ -- Bitwise XOR

    ~ -- Bitwise NOTBitwise AND

    A (42) : 00000000 00101010B (15) : 00000000 00001111-----------------------------------& (10) : 00000000 00001010-----------------------------------Bitwise OR

    A (42) : 00000000 00101010B (15) : 00000000 00001111-----------------------------------| (47) : 00000000 00101111-----------------------------------Bitwise XOR

    A (42) : 00000000 00101010B (15) : 00000000 00001111-----------------------------------& (37) : 00000000 00100101-----------------------------------Bitwise NOT

    A (42) : 00000000 00101010-----------------------------------~ (-43) : 11111111 11010101-----------------------------------

    ABA & BA | BA ^ B~A111100100110010111000001

    Computer Science: A Structured Programming Approach Using C

  • BITWISE SHIFT OPERATORSBitwise Left Shift ( )(positive values)A (43) : 00000000 00101011-----------------------------------A >> 2 : 00000000 00001010-----------------------------------Bitwise Right Shift ( >> )(negetive values)A (-44) : 11111111 11010100-----------------------------------A >> 2 : 11111111 11110101-----------------------------------Note : Right shift operator fills the left vacant fields with zeros for positive numbers, with ones for negative numbers.TYPE CONVERSION1.bool2.char3.short int4.int5.long int 6.long long int 7.float8.double9.long doubleOppositeToGravityGravity...(forcible)(natural)Explicit Type Conversion(casting)Implicit Type Conversion(automatic)...(forcible)(automatic)

  • Precedence and Associativity of OperatorsPrecdence GroupOperatorsAssociativity(Highest to Lowest )(param) subscript etc., ( ) [ ] >. L RUnary operators- + ! ~ ++ (type) * & sizeof R LMultiplicative* / % L RAdditive+ L RBitwise shift> L RRelational< >= L REquality= = != L RBitwise AND& L RBitwise exclusive OR^ L RBitwise OR| L RLogical AND && L RLogical OR| | L RConditional?: R LAssignment= += = *= /= %= &= ^= R L|= =Comma, L R

  • Principles of Programming - NI 2005*Statement has two parts : DeclarationThe part of the program that tells the compiler the names of memory cells in a programExecutable statementsProgram lines that are converted to machine language instructions and executed by the computer

    Principles of Programming - NI 2005

  • Principles of Programming - NI 2005*The printf functionUsed to send data to the standard output (usually the monitor) to be printed according to specific format.General format:printf(string literal);A sequence of any number of characters surrounded by double quotation marks.printf(format string, variables);Format string is a combination of text, conversion specifier and escape sequence.

    Principles of Programming - NI 2005

  • Principles of Programming - NI 2005*The printf function contExample:printf(Thank you);printf (Total sum is: %d\n, sum);%d is a placeholder (conversion specifier)marks the display position for a type integer variable\n is an escape sequencemoves the cursor to the new line

    Principles of Programming - NI 2005

  • Each statement in C needs to be terminated with semicolon (;)

    Example:#include

    void main(void){printf(I love programming\n);printf(You will love it too once );printf(you know the trick\n);}

  • Principles of Programming - NI 2005*Escape Sequence

    Principles of Programming - NI 2005

    Escape Sequence

    Effect

    \a

    Beep sound

    \b

    Backspace

    \f

    Formfeed (for printing)

    \n

    New line

    \r

    Carriage return

    \t

    Tab

    \v

    Vertical tab

    \\

    Backslash

    \

    sign

    \o

    Octal decimal

    \x

    Hexadecimal

    \O

    NULL

  • Principles of Programming - NI 2005*Placeholder / Conversion Specifier

    Principles of Programming - NI 2005

    No

    Conversion Specifier

    Output Type

    Output Example

    1

    %d

    Signed decimal integer

    76

    2

    %i

    Signed decimal integer

    76

    3

    %o

    Unsigned octal integer

    134

    4

    %u

    Unsigned decimal integer

    76

    5

    %x

    Unsigned hexadecimal (small letter)

    9c

    6

    %X

    Unsigned hexadecimal (capital letter)

    9C

    7

    %f

    Integer including decimal point

    76.0000

    8

    %e

    Signed floating point (using e notation)

    7.6000e+01

    9

    %E

    Signed floating point (using E notation)

    7.6000E+01

    10

    %g

    The shorter between %f and %e

    76

    11

    %G

    The shorter between %f and %E

    76

    12

    %c

    Character

    7

    13

    %s

    String

    76'

  • The scanf functionRead data from the standard input device (usually keyboard) and store it in a variable.

    General format:scanf(Format string, &variable);

    Notice ampersand (&) operator :C address of operatorit passes the address of the variable instead of the variable itselftells the scanf() where to find the variable to store the new value

  • The scanf function contExample :int age;printf(Enter your age: );scanf(%d, &age);

    Common Conversion Identifier used in printf and scanf functions.

    printfscanfint%d%dfloat%f%fdouble%f%lfchar%c%cstring%s%s

  • *The scanf function contIf you want the user to enter more than one value, you serialise the inputs.

    Example:

    float height, weight;

    printf(Please enter your height and weight:);scanf(%f%f, &height, &weight);

    *CnDSAditya Engineering College