43
1 Introduction to C Programming

Pengantar C

Embed Size (px)

DESCRIPTION

Pengantar C

Citation preview

  • *Introduction to C Programming

  • Why use C?Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities

  • C Programming LanguageDeveloped by Dennis Ritchie at Bell Laboratories in 1972 based upon the B programming language.It was then used widely in Unix systems.The C Language spread like wild fire, over various hardware platforms, all over the IT world, to such an extend that variations and incompatibilities started creeping up. Therefore there was a need for a standard code so that any programs written in C can be compiled by any compilers.In 1983, the X3J11 Technical Committee came up with the draft proposal for the ANSI system, which was approved in 1989 and referred to as theANSI/ISO 9899 : 1990 or simply the ANSI C, which is now the global solution.

  • Why C Still Useful?C provides:Efficiency, high performance and high quality s/wsflexibility and powermany high-level and low-level operations middle levelStability and small size codeProvide functionality through rich set of function librariesGateway for other professional languages like C C++ Java

    C is used:System software Compilers, Editors, embedded systemsdata compression, graphics and computational geometry, utility programsdatabases, operating systems, device drivers, system level routinesthere are zillions of lines of C legacy codeAlso used in application programs

  • Development with CFour stagesEditing: Writing the source code by using some IDE or editorPreprocessing or libraries: Already available routines compiling: translates or converts source to object code for a specific platform source code -> object codelinking: resolves external references and produces the executable module

    Portable programs will run on any machine but..

    Note! Program correctness and robustness are most important than program efficiency

  • How does it all fit together?C CodeBinary codeCompiler & LinkerProcessorOutput deviceSoftware side(done when we compile the program)Hardware side(realtime)Hard drive

  • C Standard LibraryTwo parts to learning the C worldLearn C itselfTake advantage of rich collection of existing functions called C Standard LibraryAvoid reinventing the wheelSW reusability

  • Basics of C EnvironmentC systems consist of 3 partsEnvironmentLanguageC Standard LibraryDevelopment environment has 6 phasesEditPre-processorCompileLinkLoadExecute

  • Basics of C Environment

  • Basics of C Environment

  • Simple C Program/* A first C Program*/

    #include void main() { printf("Hello World \n"); }

  • Simple C ProgramLine 1: #include

    As part of compilation, the C compiler runs a program called the C preprocessor. The preprocessor is able to add and remove code from your source file. In this case, the directive #include tells the preprocessor to include code from the file stdio.h. This file contains declarations for functions that the program needs to use. A declaration for the printf function is in this file.

  • Simple C ProgramLine 2: void main()

    This statement declares the main function. A C program can contain many functions but must always have one main function.A function is a self-contained module of code that can accomplish some task. Functions are examined later. The "void" specifies the return type of main. In this case, nothing is returned to the operating system.

  • Simple C ProgramLine 3: {

    This opening bracket denotes the start of the program.

  • Simple C ProgramLine 4: printf("Hello World From About\n");

    Printf is a function from a standard C library that is used to print strings to the standard output, normally your screen. The compiler links code from these standard libraries to the code you have written to produce the final executable. The "\n" is a special format modifier that tells the printf to put a line feed at the end of the line. If there were another printf in this program, its string would print on the next line.

  • Simple C ProgramLine 5: } This closing bracket denotes the end of the program.

  • C Standard Header Files you may want to useStandard Headers you should know about: stdio.h file and console (also a file) IO: perror, printf, open, close, read, write, scanf, etc.stdlib.h - common utility functions: malloc, calloc, strtol, atoi, etcstring.h - string and byte manipulation: strlen, strcpy, strcat, memcpy, memset, etc.ctype.h character types: isalnum, isprint, isupport, tolower, etc.errno.h defines errno used for reporting system errorsmath.h math functions: ceil, exp, floor, sqrt, etc.signal.h signal handling facility: raise, signal, etcstdint.h standard integer: intN_t, uintN_t, etctime.h time related facility: asctime, clock, time_t, etc.

  • The PreprocessorThe C preprocessor permits you to define simple macros that are evaluated and expanded prior to compilation.

    Commands begin with a #. Abbreviated list:#define : defines a macro#undef : removes a macro definition#include : insert text from file#if : conditional based on value of expression#ifdef : conditional based on whether macro defined#ifndef : conditional based on whether macro is not defined#else : alternative#elif : conditional alternativedefined() : preprocessor function: 1 if name defined, else 0 #if defined(__NetBSD__)

  • Preprocessor: MacrosUsing macros as functions, exercise caution:flawed example: #define mymult(a,b) a*bSource: k = mymult(i-1, j+5);Post preprocessing: k = i 1 * j + 5;better: #define mymult(a,b) (a)*(b)Source: k = mymult(i-1, j+5);Post preprocessing: k = (i 1)*(j + 5);Be careful of side effects, for example what if we did the followingMacro: #define mysq(a) (a)*(a)flawed usage:Source: k = mysq(i++)Post preprocessing: k = (i++)*(i++)Alternative is to use inlineed functionsinline int mysq(int a) {return a*a};mysq(i++) works as expected in this case.

  • Preprocessor: Conditional CompilationIts generally better to use inlineed functionsTypically you will use the preprocessor to define constants, perform conditional code inclusion, include header files or to create shortcuts#define DEFAULT_SAMPLES 100#ifdef __linuxstatic inline int64_t gettime(void) {...}#elif defined(sun)static inline int64_t gettime(void) {return (int64_t)gethrtime()}#elsestatic inline int64_t gettime(void) {... gettimeofday()...}#endif

  • Escape Sequence\nnew line\ttab\rcarriage return\aalert\\backslash\double quote

  • Arithmetic in CC operationAlgebraic CAddition(+)f+7f+7Subtraction (-)p-cp-cMultiplication(*)bmb*mDivision(/)x/y, x , x yx/yModulus(%) r mod sr%s

  • Memory conceptsEvery variable has a name, type and valueVariable names correspond to locations in computer memoryNew value over-writes the previous value Destructive read-inValue reading called Non-destructive read-out

  • 2. A Simple C Program

    CommentsText surrounded by /* and */ is ignored by computerUsed to describe useful program information (description, author, date)#include Preprocessor directiveTells computer to load contents of a certain library header file allows standard input/output operations

  • 2.A Simple C Program

    int main()C++ programs contain one or more functions, exactly one of which must be mainParenthesis used to indicate a functionint means that main "returns" an integer valueBraces ({ and }) indicate a blockThe bodies of all functions must be contained in braces

  • 2.A Simple C Program

    printf( "Welcome to C!\n" );Instructs computer to perform an actionSpecifically, prints the string of characters within quotes ( )Entire line called a statementAll statements must end with a semicolon (;)Escape character (\)Indicates that printf should do something out of the ordinary\n is the newline character

  • 2.A Simple C Program

    return 0;A way to exit a functionreturn 0, in this case, means that the main() function terminates normally and returns to the Windows operating system.Right brace }Indicates end of main has been reachedLinkerWhen a function is called, linker locates it in the libraryInserts it into object programIf function name is misspelled, the linker will produce an error because it will not be able to find function in the library

  • Good programming practicesIndentation

    #include int main() { printf("Hello World!\n"); return 0;}

    #include int main() {printf("Hello World!\n");return 0;}

    C Course, Programming club, Fall 2008*

    C Course, Programming club, Fall 2008

  • Good programming practices contd..Variables namesNot too short, not too longAlways start variable names with small lettersOn work breakCapitalize: myVariable, ORSeparate: my_variableC Course, Programming club, Fall 2008*

    C Course, Programming club, Fall 2008

  • Good programming practices contd...Put comments#include int main() { /* this program adds two numbers */ int a = 4; //first number int b = 5; //second number int res = 0; //result res = a + b;}C Course, Programming club, Fall 2008*

    C Course, Programming club, Fall 2008

  • Good programming practicesYour code may be used by somebody elseThe code may be longShould be easy to understand for you and for othersSaves lot of errors and makes debugging easierSpeeds up program developmentC Course, Programming club, Fall 2008*

    C Course, Programming club, Fall 2008

  • Enter first integer45Enter second integer72Sum is 117 3. Another Simple C Program

  • 3.Another Simple C Program

    As beforeComments, #include and mainint integer1, integer2, sum;Declaration of variablesVariables: locations in memory where a value can be storedint means the variables can hold integers (-1, 3, 0, 47)Variable names (identifiers)integer1, integer2, sum Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ )Case sensitiveDeclarations appear before executable statementsIf an executable statement references and undeclared variable it will produce a syntax (compiler) error

  • 3Another Simple C Program:

    scanf( "%d", &integer1 );Obtains a value from the userscanf uses standard input (usually keyboard)This scanf statement has two arguments%d - indicates data should be a decimal integer&integer1 - location in memory to store variable& is the address of the variable name in scanf statementsWhen executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key

  • *3Another Simple C Program:

    = (assignment operator)Assigns a value to a variableIs a binary operator (has two operands)sum = variable1 + variable2;sum gets variable1 + variable2;Variable receiving value on leftprintf( "Sum is %d\n", sum );Similar to scanf%d means decimal integer will be printedsum specifies what integer will be printedCalculations can be performed inside printf statementsprintf( "Sum is %d\n", integer1 + integer2 );

  • *4. Variable ConceptsVariables Variable names correspond to locations in the computer's memoryEvery variable has a name, a type, a size and a valueWhenever a new value is placed into a variable (through scanf, for example), it replaces (and destroys) the previous valueReading variables from memory does not change themA visual representation

  • *5. ArithmeticArithmetic calculationsUse * for multiplication and / for divisionInteger division truncates remainder7 / 5 evaluates to 1Modulus operator(%) returns the remainder 7 % 5 evaluates to 2Operator precedenceSome arithmetic operators act before others (i.e., multiplication before addition)Use parenthesis when neededExample: Find the average of three variables a, b and cDo not use: a + b + c / 3 Use: (a + b + c ) / 3

  • *5 ArithmeticArithmetic operators:

    Rules of operator precedence:

    C operation

    Arithmetic operator

    Algebraic expression

    C expression

    Addition

    +

    f + 7

    f + 7

    Subtraction

    -

    p c

    p - c

    Multiplication

    *

    bm

    b * m

    Division

    /

    x / y

    x / y

    Modulus

    %

    r mod s

    r % s

    Operator(s)

    Operation(s)

    Order of evaluation (precedence)

    ()

    Parentheses

    Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right.

    *, /, or %

    Multiplication,Division, Modulus

    Evaluated second. If there are several, they areevaluated left to right.

    + or -

    Addition

    Subtraction

    Evaluated last. If there are several, they are evaluated left to right.

  • *6.Decision Making: Equality and Relational OperatorsExecutable statementsPerform actions (calculations, input/output of data)Perform decisionsMay want to print "pass" or "fail" given the value of a test gradeif control structureSimple version in this section, more detail laterIf a condition is true, then the body of the if statement executed0 is false, non-zero is trueControl always resumes after the if structureKeywordsSpecial words reserved for CCannot be used as identifiers or variable names

  • 1. Declare variables

    2. Input

    2.1 if statements

    3. Print*6.Decision Making: Equality and Relational Operators

  • *Enter two integers, and I will tell you the relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7 Enter two integers, and I will tell you the relationships they satisfy: 22 1222 is not equal to 1222 is greater than 1222 is greater than or equal to 12 6.Decision Making: Equality and Relational OperatorsProgram Output

  • *6.Decision Making: Equality and Relational Operators

    Standard algebraic equality operator or relational operator

    C equality or relational operator

    Example of C condition

    Meaning of C condition

    Equality Operators

    =

    ==

    x == y

    x is equal to y

    not =

    !=

    x != y

    x is not equal to y

    Relational Operators

    >

    >

    x > y

    x is greater than y

    =

    x >= y

    x is greater than or equal to y

  • *7Keywords Of CThese are reserved words and should not be used forvariable names:

    Keywords

    auto

    double

    int

    struct

    break

    else

    long

    switch

    case

    enum

    register

    typedef

    char

    extern

    return

    union

    const

    float

    short

    unsigned

    continue

    for

    signed

    void

    default

    goto

    sizeof

    volatile

    do

    if

    static

    while

    ********