Reviewer LECTURE 4-7 COMPROG.pdf

Full Transcript

Lecture 4 - Components of a C Program (P1) Introduction Algorithms to Programs ○ Instructions on how to do a task ○ Algorithm: Talking to humans, easy to understand Plain English, pseudocode, flowchart ○ Program:...

Lecture 4 - Components of a C Program (P1) Introduction Algorithms to Programs ○ Instructions on how to do a task ○ Algorithm: Talking to humans, easy to understand Plain English, pseudocode, flowchart ○ Program: Talking to computer (compiler) “Formal expression” of algorithm Writing, Editing, Compiling and Linking Programs in C ○ Writing and editing Text editor, source files ○ Compiler Source code -> Machine language Two parts: Preprocessor ○ Preprocessor directives ○ Result is called translation unit Translators ○ Reads translation unit and writes resulting object module ○ Linking Programs Linker assembles all functions to final exe. 1. Structure of a C Program Basic Structure Example: C #include int main() { printf("Hello World!"); return 0; } Key Parts of a C Program: ○ Preprocessor Directives: #include includes standard input/output functions. “HASH-INCLUDE” ○ Main Function: Entry point of every C program (int main()). ○ Statements: Instructions inside the function (e.g., printf("Hello World!")). ○ Return Statement: Ends the program (return 0;). 2. Values and Variables Basic Types: ○ Integers (int): Whole numbers (e.g., 0, 1, -1). ○ Floating-Point Numbers (float): Numbers with fractions (e.g., 1.0, 0.5). ○ Characters (char): Single characters (e.g., 'A', 'z'). ○ Character Strings (char-s): Sequence of characters (e.g., "Hello World"). Variable Declaration Example: C int count; float result; char letter; 3. Expressions Expression: A combination of values, variables, and operators that produces a result. Arithmetic Operators: ○ + (Addition), - (Subtraction) ○ * (Multiplication), / (Division)z ○ % (Modulus - remainder of division) Operator Precedence (PODMAS): ○ Parentheses → Order of exponents → Division/Multiplication → Addition/Subtraction. Example of Expression Evaluation: C int result = 1 + 2 * 3 - 4 / 5; // Result: 7 as ⅘ = 0 because ⅘ is not int float result = (1 + 2.0) * (3 - 4) / 5 = (3.0) * (-1) / 5 = -3.0 / 5 = -0.6 // float is communicable as declared in 2.0, therefore the result is a floating point value 4. Function Calls Function Call: Invoking a set of instructions by name. Example: Quadratic Equation Solver C x1 = SolveQuadratic1(A, B, C); x2 = SolveQuadratic2(A, B, C); ○ SolveQuadratic1 and SolveQuadratic2 are assumed to be functions that solve the quadratic equation. 5. Comments Purpose: To document the code for clarity. Comments are ignored during execution. Types of Comments: ○ Single-line comments: // This is a comment ○ Multi-line comments: Summary Structure of a C Program: Preprocessor directives, main function, statements, and return statement. Values and Variables: Different data types (int, float, char) Expressions: PODMAS Function Calls: Calling and using functions in C Comments: Comments are for explaining codes to viewers. Lecture 5 - Components of a C Program (Part 2) 1. Types and Variables Types: A type defines the kind of data a value holds. ○ Built-in Types: char, int, float ○ Type Modifiers: long, short, const ○ User-defined Types: Arrays and structures ○ Strings: Arrays of char Variable Declaration Example: C int age; float salary = 5000.50; char initial = 'A'; 2. Character Representation ASCII (American Standard Code for Information Interchange): ○ Characters are stored as integers. ○ ASCII values range from 0 (NUL) to 127 (DEL). ○ Example: 'A' has ASCII value 65. ○ 128 to 255 are “extended” sets Floating Point ○ A fractional number, like 789.34 ○ C supports three (3) different sizes of floating-point data: Float - 4 bytes Double - 8 bytes Long double - 10 bytes ○ Floating point size is machine-dependent ○ Sizeof tells exact size in bytes ○ Always signed Variable ○ Logical name for a container ○ Have an associated type ○ Must be declared before use: [modifiers] ; [modifiers] = ; 3. Keywords and Identifiers Keywords: Reserved words in C that have special meanings (e.g., int, float, if, else). Cannot be used as variable names. Identifiers: Names for variables, functions, etc. They must begin with a letter or underscore and are case-sensitive. Example of Valid Identifiers: C int score; float height_1; 4. Assignments Assignment Operator: = is used to assign a value to a variable. Example: C int x = 5; x = x + 1; // x is now 6 5. Constant Variables Constants: Variables whose values cannot change once assigned. Declared using the const keyword. Also known as “Global” variables. Example: C const int MAX = 100; const float PI = 3.1416; 6. Booleans Booleans in C: There is no built-in Boolean type, but integers are used as Booleans. ○ 0 is false, and any non-zero value is true. ○ Only two values: true/false ○ Used for conditions (selecting and looping) Example: C int isTrue = 1; if (isTrue) { printf("This is true!"); } 7. Boolean Expressions and Operators Boolean Operators: ○ AND: && (True if both conditions are true) ○ OR: || (True if at least one condition is true) ○ NOT: ! (True if the condition is false) ○ Equality: == ○ Inequality: != ○ Comparison Operators: , = Example of Boolean Expression: C int age = 20; if (age >= 18 && age 1 42 = 18 6. Explanation: ○ 1 < 2: This is true because 1 is less than 2. ○ 0 > 1: This is false because 0 is not greater than 1. ○ 42 = 18: This checks if age is greater than or equal to 18. Lecture 6: Formatted Input/Output (CS102) 1. Overview of Formatted Input/Output Formatted Input/Output (I/O) refers to how data is read from and written to input/output streams in a specific format using functions like scanf() and printf(). 2. Streams Streams are sequences of characters organized into lines, serves as a channel to convey chars between I/O and programs. ○ 0 or more chars ○ Ends with “\n” ○ Text Input/Output: Dealt with as a sequence of characters. ○ Examples: Input: scanf(“%d %f”, &item, &cost); Output: printf(“The value of x is %d\n”, x); 3. Standard Streams stdin: Standard input, usually from the keyboard. stdout: Standard output, usually to the screen. stderr: Standard error, usually to the screen.. Include at the top of your program for I/O operations. Can be redirected 4. Formatted Input: scanf() Used to read data from the standard input stream. Syntax: scanf(format-control-string, &variable1, &variable2, …); Example: scanf("%s %f %c %d", name, &age, &gender, &idNumber); Important: Use & for non-string variables (e.g., integers, floats). Do not use & for strings. 5. Formatted Output: printf() Used to write formatted data to the standard output stream. Syntax: printf(format-control-string, variable1, variable2, …); Example: printf("%s is %.1f years old, gender %c, ID: %d\n", name, age, gender, idNumber); 6. Conversion Specifiers For printf() and scanf(): ○ %d: Decimal integer. ○ %f: Float. ○ %c: Character. ○ %s: String. Example: printf("%d %f %c %s", integer, floatVar, charVar, stringVar); Precision Modifiers: For floating-point numbers: %.2f limits to 2 decimal places. Width Modifiers: Control the minimum number of positions for output. 7. Common Conversion Specifiers Numeric: ○ %d: Decimal integer. ○ %f: Floating-point number. Alphanumeric: ○ %c: Character. ○ %s: String. Modifiers for printf() and scanf() 1. Conversion Specifiers for Numerical Information: %d: Decimal integer. %f: Float. %lf: Double. 2. Conversion Specifiers for Alphanumeric Information: %c: Single character. %s: String. 3. Numeric Display Modifiers: %i or %d: Display a signed decimal integer. %f: Display a floating-point value. %e or %E: Display a floating-point value in exponential notation. %g or %G: Display a floating-point value in either %f or %e form. L: Modifier for long double (used before a float conversion specifier). 4. Width Modifier: Specifies the minimum number of characters to be used for output. If the data is too large, the width will be overridden. 5. Precision Modifier: For floating-point numbers, it specifies the number of decimal places to print. Format:.p where p is the number of decimal places. Example: %.2f prints 2 decimal places. 6. Flag Modifier: 0: Adds leading zeros if there is a width specification. -: Left-justifies the data. Without a flag, data is right-justified by default. 7. Length Modifiers for scanf(): h or l: Used for short or long integers in scanf(). l or L: Used for double or long double in scanf(). Lecture 7: Data File I/O (CS102) 1. Data File I/O File Input/Output (I/O) allows programs to interact with files for reading and writing data. 2. Types of Files in C 1. Text Files: ○ Contain data in ASCII character format. ○ Each line ends with a newline character (\n). ○ Can be read or edited by any text editor. ○ Typically use the.txt file extension. 2. Binary Files: ○ Store data in binary form (0’s and 1’s). ○ Created and read only through programs. ○ Not human-readable and typically use the.bin file extension. 3. Three Steps for Accessing Data Files 1. Opening the File: Using the fopen() function. 2. Reading/Writing Data: Using fscanf() for reading or fprintf() for writing. 3. Closing the File: Using the fclose() function. 4. Opening a Data File: fopen() Declare a File Stream Pointer: FILE *fptr; Use fopen() to Open the File: fptr = fopen("data.txt", "wt"); ○ The first argument is the filename (e.g., "data.txt"). ○ The second argument is the mode: "w" or "wt": Open an ASCII file for writing. "r" or "rt": Open an ASCII file for reading. "a" or "at": Open an ASCII file for appending. "wb": Open a binary file for writing. "rb": Open a binary file for reading. "ab": Open a binary file for appending. 5. Closing a Data File: fclose() Once finished with file operations, close the file using fclose(): fclose(fptr); 6. Writing to an ASCII Data File: fprintf() Syntax: fprintf(file_pointer, format_specifiers, data); Example: fprintf(fptr, "%d\n", x); arg1: The file stream pointer (e.g., fptr). arg2: Same as printf(), including format specifiers (e.g., %d for an integer). 7. Reading from an ASCII Data File: fscanf() Syntax: c Copy code fscanf(file_pointer, format_specifiers, &variable); Example: fscanf(fptr, "%d", &x);

Use Quizgecko on...
Browser
Browser