C progaming 4 chapters

download C progaming 4 chapters

of 100

  • date post

    22-Mar-2016
  • Category

    Documents

  • view

    220
  • download

    4

Embed Size (px)

description

 

Transcript of C progaming 4 chapters

  • *Programming Methodology I in C/C++ CHAPTER IFirst ProgramBasic Input and Output

  • *Overviewwriting program for todays examplesHello, World a first programHello, World line by lineBasic rules for C Tips for good programming styleBasic Input/Output

  • *Processes of Creating C ProgramEditingCompilingLinking Executing

  • *EditingC source code Used Editor or called IDE to create source fileSource file extension is *.c

  • *CompilingComplier convert source code into computer language (Binary 0 1)Detect and report errorsOut put called Object Code (extension *.Obj)ALT+F9 (Compile)

  • *LinkingAdd require code module from program LibraryLibraries supplied as part of C.Output is a executable fileFile extension *.exe

  • *ExecutingThe execution stage is where your program, having completed all the previous processes successfully.Ctrl+F9 (Run Program)

  • *Hello, World/* Hello, World program */#include

    int main(){printf(Hello, World!\n);return 0;}

  • *Hello, World: Line by Line/* Hello, World program *//* */ marks a comment blockCan go anywhere inside a programAnything in comments is ignored by the compilerExtremely useful for including explanatory information

  • *Hello, World: Line by Line#include #include a C preprocessor command that lets you include the code from another file (such as a library)stdio.h the standard input-output library#include -- allows you to use code from the standard input library, printf() code function

  • *Hello, World: Line by Lineint main() { ... }Code is contained in functions (also called procedures)Curly brackets mark the start and endEvery program needs an entry point (somewhere to start running)The main() function is the entry point for C programs (Start running program)

  • *Hello, World: Line by Lineint main() { ... return 0; }The main() function should always be defined with int or void before it. int main() indicates that main() returns an integer valuevoid main() indicates that main() returns no value (nothing)Traditional UNIX rule: if everything goes well in the program, main() should return 0.

  • *Hello, World: Line By Lineprintf(Hello, World!\n);return 0;Lines of code that will be executed by the program when it is runShould be able to figure out what each line does!A line of code is terminated by a semicolon ( ; )Execution goes in order (top-down)

  • *Hello, World: Line by Lineprintf(Hello, World!\n);Prints out the message Hello, World!printf()A function from stdio.hUsed to print messages out to the screenTo use a function, you type in its name, and put any information that the function needs (its arguments) inside the parentheses after the name

  • *Hello, World: Line by LineHello, World!\nA single letter, number, punctuation mark, etc. is a characterA series of characters grouped together is a stringSome special kinds of characters exist\t tab character\n newline character

  • *Review of Hello, World/* Hello, World program */#include

    int main(){printf(Hello, World!\n);return 0;}

  • *Important Basic Rules for CLines of code end with a semicolonStrings are enclosed inside double-quotesFunctions start and end with curly bracketsWhitespace doesnt matter

  • *Hello, World Revisited/* Hello, World program */#include int main(){printf(Hello, World!\n);return 0;}Works exactly the same as before

  • *Hello, World Revisited/* Hello, World program */#include int main(){printf(Hello, World!\n);return 0;}Also works exactly the same as before

  • *Hello, World Revisited/* Hello, World program */#include int main(){printf(Hello, World!\n)return 0;}Doesnt work at allCan you see why?

  • *Hello, World Revisited/* Hello, World program */#include int main(){printf(Hello, World!\n);return 0;}Works fineBut bad style no indentation!Important for code to be easy to read

  • *Programming StylePut brackets on separate lines by themselves (some variations on this)After each open bracket, increase indentation level by one tabAfter each close bracket, decrease indentation level by one tabLeave blank lines between sectionsDont let lines get too long

  • *Basic Input/Output OverviewTypes of input and outputBasic output with printf()Basic input with scanf()Memorize this for now more understanding will come later

  • *Types of Input/OutputInput from the keyboard (standard input)Output to the screen (standard output)Input from/output to a fileInput/output over a network connectionInput from/output to another programWell be focusing on stdin/stdout for now

  • *Basic output with printfprintf() sends the message you pass into it to standard output automaticallyMessages can be just a plain string (Hello, World!\n)Use spaces/tabs/newlines in printf() to make your output nicerBuild up output with multiple calls to printf to make your code nicer

  • *Good printf Example#include int main(){printf(===================\n);printf( Hello, World! \n);printf(===================\n);

    return 0;}

  • *Bad printf Example#include int main(){printf(===================\n Hello, World! \n===================\n);return 0;}Unreadable hard to see what output will beThe output will get messed up if you put this into notepad (long lines will be wrapped)

  • *Basic Input with scanfA little trickier than printfNeed somewhere for the program to store the users inputTwo-step processSet aside a place for the input to be storedGet the input

  • *Basic Input example#include int main(){int a;scanf(%d, &a);

    return 0;}a is the name of the place where the input will be stored%d tell scanf that the input is a number

  • *Flowchartshelp programmer in solving problem, its used a graphical. Flowchart symbolTerminator: Terminator: Show where to Start (Begin) and End (stop) the program (Usually used at the beginning and the end of flowchart.)

  • *FlowchartProcess: Process: Showing the action in a program. example: x/3; x=5;Selection:Selection: Conditional expression doing with True or False. Input/Output:Input/Out put: Output or input data from/in process

  • *FlowchartData Flow:Data Flow: Indicate the flows of data from one symbol to another.

    Connector: Connector: Combine or Connect one Flowchart to another.

  • *Example Flowchart Flowchart for calculating gross wage

    A sequence of instruction

    start

    inputrate of pay

    inputhours worked

    calculategross wage

    outputgross wage

    stop

  • *Example FlowchartFlowchart showing selection

    No

    Yes

    calculategross with overtime

    start

    hours>40?

    inputrate of pay

    inputhours worked

    calculategross wage without overtime

    outputgross wage

    stop

  • *Example FlowchartFlowchart showing repetition

    No

    Yes

    increase counter by 1

    start

    counter=5?

    inputrate of pay

    inputhours worked

    calculategross wage

    outputgross wage

    stop

    set counter to zero

  • *Example FlowchartFlowchart showing selection and repetition

    No

    Yes

    calculategross with overtime

    increase counter by 1

    start

    counter=5?

    inputrate of pay

    inputhours worked

    calculategross without overtime

    outputgross wage

    stop

    hours>40?

    set counter to zero

  • *Programming Methodology in C/C++ CHAPTER IIIProgram ElementsPart 2: Constants, Operators and Expression

  • *ConstantLike variables, constants are data storage locations. Constants don't change value. You must initialize a constant when you create it, and you cannot assign a new value later.

    Two type of constants in C/C++:Literal ConstantsSymbolic Constants

  • *Literal ConstantA literal constant is a value typed directly into your program wherever it is needed. For example:int myAge = 39;

    myAge is a variable of type int 39 is a literal constant.

  • *Symbolic ConstantsA symbolic constant is a constant that is represented by a name.after a constant is initialized, its value can't be changed. Two ways to declare a symbolic constant:With #define directive:#define STUDENT_PER_CLASS 15 #define TAX_RATE 0.1

    With const keywordconst int STUDENT_PER_CLASS = 15;

  • *Operators & ExpressionAn operator is a symbol that causes the compiler to take an actionOperators act on operands.Ex.Riel = dollar * rate;

    operator operandsExpression: combination of operator(s) and operands

  • *OperatorsOperator act on an operands

    Assignment: =Arithmetic: + - * / %Increment/decrement: ++ --Relational: > >= <

  • *AssignmentThe = symbol is called assignment operator

    assigns the value on the right to the variable on the left e.g.: rate=4050;

  • *Arithmetic OperatorsThere are five arithmetic operators:

    OperatorSymbolExampleAddition+Y = a + b;Subtraction-Y = a - b;Multiplication*Y = a * b;Division /Y = a / b;Modulus (get the reminder)%Y = 5%3; ==>y=2

  • *Arithmetic

    Arithmetic examples

    y = 5; // y is now 5x = y + 3; // x is now 8f = 2 * 4; // f is now 8.0g = f / 3.0; // g is now 2.667y = x / 3; // y is now 2z = x % 3; // z is now 2

  • *Increment and Decrement operators++x; x=x+1;--x; x=x-1;

    Note: ++x; prefix increment operator x++; postfix increment operator

    OperatorSymbolActionExamplesIncrement++Increments the operand by one++x, x++Decrement--Decrements the operand by one--x, x--

  • *Increment/Decrement operator

    Example:x = 5;f = 2.5;x++; // x is now