Comprehensive Study Guide: Introduction to Algorithms, C Programming, and Formatted Input/Output

Algorithms Theory, Design, and Development Lifecycle

  • Definition of Algorithm

    • An algorithm is a step-by-step procedure for solving a problem, clearly defining the actions to be performed and the exact order in which they should be executed.

    • In computer programming, an algorithm is a structured method used to solve a problem using a computer, expressed as a logical sequence of instructions.

    • Example: Algorithm to Add Two Numbers:

    • Step 1: Input the first number →A\rightarrow A

    • Step 2: Input the second number →B\rightarrow B

    • Step 3: Add AA and BB, store the result in SUMSUM

    • Step 4: Display SUMSUM

  • Multiple Approaches to Algorithm Design

    • Different sequence of steps can be used to solve the exact same problem; as long as the result produced is correct, each algorithm is valid.

    • Comparison Example (Calculating the average of 3 numbers):

    • Algorithm 1:

      • Step 1: Read number AA

      • Step 2: Read number BB

      • Step 3: Read number CC

      • Step 4: Compute average=A+B+C3\text{average} = \frac{A + B + C}{3}

      • Step 5: Display average

    • Algorithm 2:

      • Step 1: Read all three numbers together

      • Step 2: Store them as AA, BB, and CC

      • Step 3: Compute sum=A+B+C\text{sum} = A + B + C

      • Step 4: Compute average=sum3\text{average} = \frac{\text{sum}}{3}

      • Step 5: Display average

  • Good Algorithm Criteria

    • Possesses the correct logical flow to solve the targeted problem.

    • Produces correct output in a time-efficient manner.

    • Written using unambiguous, structured language.

    • Allows easy implementation into real programming languages.

    • Ensures all steps and operations are unambiguously defined and explicitly terminated.

  • Algorithm Development Steps (7-Step Lifecycle Pipeline)

    • 1. Problem Definition: Clearly define the problem, required inputs, and target outputs.

    • Example (Quadratic Equation Problem): Finding the solution or real/imaginary roots of a quadratic equation defined as ax2+bx+c=0a x^2 + b x + c = 0. Data needed: Coefficients aa, bb, and cc of real type.

    • 2. Model Development: Formulate mathematical models and equations needed for calculation.

    • Example Mathematical Model: Quadratic formula Discriminant d=b2−4ac\text{Discriminant } d = b^2 - 4 a c, x1=−b+b2−4ac2ax_1 = \frac{-b + \sqrt{b^2 - 4ac}}{2a}, and x2=−b−b2−4ac2ax_2 = \frac{-b - \sqrt{b^2 - 4ac}}{2a}.

    • 3. Algorithm Design: Construct flowcharts or pseudocode capturing control flow.

    • 4. Writing Code: Implement the algorithm into source code using a chosen programming language (such as C).

    • 5. Compilation: Translate source code into executable binary code using a compiler.

    • 6. Execution and Debugging: Execute program to check for syntax errors or logical/output errors.

    • Syntax Errors: Errors occurring when program code violates language syntax rules during compilation.

    • Output/Logic Errors: Errors where code compiles and runs successfully but produces incorrect logical results.

    • 7. Documentation: Compile comprehensive technical documentation including Problem Definition, Calculation Model/Mathematics, Flowchart/Algorithm Design, and Source Code.

Flowchart for Quadratic Equation Root Solver
  • Methods of Representing Algorithms

    • Written Representations:

    • Structured English: Natural language with rigid structural rules.

    • Pseudocode: An artificial, informal language used to develop algorithms without strict syntactical constraints. Focuses entirely on logic.

    • Common Pseudocode Keywords:

      • Input: read, get, input, key-in

      • Output: print, write, put, output, display

      • Storing Value: set, store, save, initialize

      • Decision (Selection): if ... then ... else ... endif

      • Repetition (Loop): dowhile ... enddo, while ... endwhile, for

      • Compute: calculate, compute, add, subtract, multiply, divide

    • Graphical Representations:

    • Flowchart: Diagrammatic representation using standard geometric shapes connected by arrows indicating control flow.

  • Pseudocode Examples

    • Example 1: Calculator Summation Loop

    • Start

    • Set the calculator ON

    • Empty any values

    • Do

      • Input price

      • Push plus button (+)

    • While all prices have not been input

    • Print total price

    • Set the calculator OFF

    • End

    • Example 2: Class Average Score Calculation

    • Start

    • Set total = 0

    • Set grade counter = 1

    • While grade counter is less than or equal to 10

      • Input next score

      • Add score into total

      • Add 1 to grade counter

    • Set class average = total / 10

    • Print the class average

    • End

  • Structure Theorem

    • Any computer program can be constructed using only three basic control structures:

    • 1. Sequence: A series of consecutive commands executed strictly in order from top to bottom.

    • 2. Selection: A structure allowing choice between execution pathways based on conditional evaluation (IF-THEN-ELSE).

    • 3. Repetition (Iteration): Enables a block of statements to execute repeatedly while a specified condition remains true.

Sequence, Selection, and Iteration Control Structures Diagram

Introduction to C Language and Fundamental Program Structure

  • History and Evolution of C

    • 1967: BCPL (Basic Combined Programming Language) designed by Martin Richards for operating systems and compiler development.

    • 1970: B language created by Ken Thompson at Bell Labs for early UNIX development.

    • 1972: C language developed by Dennis Ritchie at Bell Labs, based directly on B.

    • 1989: ANSI standardized C (ANSI C / C89), later adopted by ISO.

    • 2011 & 2018: Standards C11 and C18 introduced modern language enhancements.

    • Key Advantages of C: High performance for speed-critical systems, cross-hardware portability, low-level direct memory manipulation, and time/space execution efficiency.

  • C Standard Library and Header Files

    • Programs are stored in source files ending in .c (or .cpp).

    • Standard library functions are categorized across specialized header files:

    • <stdio.h>: Standard Input/Output functions (printf, scanf, getchar, puts, putchar, gets).

    • <math.h>: Mathematical computations (pow, sqrt, trigonometric functions).

    • <stdlib.h>: Utility, dynamic memory allocation (malloc, free), process control (exit, system), random numbers (rand, srand), conversions (atoi).

    • <string.h>: String manipulation (strcpy, strlen, strcat, strcmp).

    • <time.h>: Date and time functions (time_t, struct tm, difftime, time, mktime).

  • Structure of main() Function

    • Every executable C program must contain exactly one main() function, serving as execution start point.

    • C is strictly case-sensitive (main is distinct from Main, sum is distinct from Sum).

    • Every statement in C must end with a semicolon ;.

    • return(0); indicates normal, error-free program execution termination.

    • Compiler Behavior Variations Across Main Signatures:

    • In Turbo C 2.0 (DOS) and Microsoft Visual C++ (Windows): void main() and int main() compile cleanly; bare main() emits warnings.

    • In Dev-C++ (Windows) and GCC (Linux): int main() and bare main() compile cleanly; void main() emits warnings.

  • Preprocessor Directives and Comments

    • #include <stdio.h>: Preprocessor directive instructing compiler to incorporate function prototypes from standard headers prior to compilation.

    • Comments:

    • Used to improve code readability; completely ignored by compiler during code generation.

    • Multi-line block comments: /* ... */

    • Single-line comments: // ...

  • C Character Set and Escape Sequences

    • C programs are constructed using standard ASCII character subsets (Uppercase A–Z, Lowercase a–z, Digits 0–9, and Symbols).

    • Escape Characters Reference Table:

    • \a: Bell / alert / system beep

    • \b: Backspace

    • \t: Horizontal tab

    • : New line / line feed

    • \v: Vertical tab

    • \r: Carriage return

    • \': Single quote

    • \": Double quote

    • \\: Backslash

    • \xdd: Hexadecimal notation

    • \ddd: Octal notation

  • Identifiers and Keywords

    • Identifier Rules:

    • Must start with an alphabetic letter (A–Z, a–z) or an underscore _.

    • Can contain letters, digits (0–9), and underscores.

    • Strictly case-sensitive.

    • Maximum valid identifier length depends on specific compiler.

    • Cannot match reserved keywords.

    • Complete Table of 32 Standard C Keywords:

C Reserved Keywords List Table
  • Standard keywords list: auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while.

Variables, Data Types, Memory, and Storage

  • Variable Fundamentals

    • A variable is a named memory location used for storing data.

    • Variable Properties:

    • Name (Identifier)

    • Address (L-value, location in physical memory)

    • Data Type (Determines size and interpretation)

    • Memory Size (Number of allocated bytes)

    • Data Value (R-value, content stored in address)

    • Variable content can be modified at runtime.

    • Declaration Format:

    • <data type> <variable name>;

    • <data type> <variable name> = <initial value>;

    • Variables can be declared within any compound statement block enclosed by { and }.

    • Memory Structure Example: For char ch = 65;

    • Variable Name: ch

    • Value: 65 (ASCII representation of character 'A')

    • Memory Address: 123456

    • Value Range: −128-128 to 127127

  • Data Types and Modifiers

    • Basic C Data Types: char (character), int (integer), float (floating point), double (double-precision float), void (empty/valueless).

    • Modifiers: signed, unsigned, long, short.

    • void usage: Indicates functions that return no value, or generic typeless pointers.

C Data Types, Memory Allocation, Syntax, and Ranges Table
  • Comprehensive Data Type Specification Table:

    • char | Syntax: char | Memory: 1 byte | Range: −128-128 to 127127

    • unsigned char | Syntax: unsigned char | Memory: 1 byte | Range: 00 to 255255

    • integer | Syntax: int | Memory: 4 bytes | Range: −2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647

    • unsigned int | Syntax: unsigned int | Memory: 4 bytes | Range: 00 to 4,294,967,2954,294,967,295

    • short int | Syntax: short int | Memory: 2 bytes | Range: −32,768-32,768 to 32,76732,767

    • unsigned short int | Syntax: unsigned short int | Memory: 2 bytes | Range: 00 to 65,53565,535

    • long int | Syntax: long int | Memory: 4 bytes | Range: −2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647

    • unsigned long int | Syntax: unsigned long int | Memory: 4 bytes | Range: 00 to 4,294,967,2954,294,967,295

    • long long | Syntax: long long | Memory: 8 bytes | Range: −9,223,372,036,854,775,808-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8079,223,372,036,854,775,807

    • unsigned long long | Syntax: unsigned long long | Memory: 8 bytes | Range: 00 to 18,446,744,073,709,551,61518,446,744,073,709,551,615

    • float | Syntax: float | Memory: 4 bytes | Range: 3.4×10−383.4 \times 10^{-38} to 3.4×10+383.4 \times 10^{+38}

    • double | Syntax: double | Memory: 8 bytes | Range: 1.7×10−3081.7 \times 10^{-308} to 1.7×10+3081.7 \times 10^{+308}

    • long double | Syntax: long double | Memory: 8 bytes | Range: 1.7×10−3081.7 \times 10^{-308} to 1.7×10+3081.7 \times 10^{+308}

  • Type Casting

    • The explicit conversion of a variable from one data type to another.

    • Syntax: (data type) expression

    • Code Example: c} int x; float f = 3.134; x = (int) f; // Casting float to int; x becomes 3 &nbsp;&nbsp;&nbsp;&nbsp;

  • Constants and Symbolic Constants

    • Constants store fixed values that cannot be modified during program execution and do not possess accessible L-value addresses.

    • Types of Constants:

    • Integer Constant: -5, 1

    • Floating-point Constant: 3.14

    • Character Constant: 'c', '1', '$'

    • Escape Sequence: , \t, \"

    • String Constant: "BINUS", "B"

    • Symbolic Constant: Declared via #define PHI 3.14 or const float PHI = 3.14;

    • Symbolic constants declared via #define do not allocate variable memory spaces.

  • The sizeof Operator

    • Unary operator used to evaluate the memory footprint (in bytes) of data types or expressions.

    • Syntax: sizeof(expression) or sizeof(data_type)

    • Platform Variations: sizeof(int) evaluates to 4 bytes in Dev-C++ (Windows), but evaluates to 2 bytes in Turbo C ver 2.0 (DOS).

  • Literal Suffixes

    • Floating-point Suffixes:

    • F or f: float data type (e.g., 3.14f allocates 4 bytes)

    • Unsuffixed floating constant: Default double data type (e.g., 3.14 allocates 8 bytes)

    • L or l: long double data type (e.g., 3.14L allocates 16 bytes on supported compilers)

    • Integer Suffixes:

    • U or u: unsigned int (e.g., 174u)

    • L or l: long int (e.g., 174L)

    • UL, ul, LU, or lu: unsigned long int (e.g., 174ul)

    • Unsuffixed integer constant: Default int data type (e.g., 174)

    • Compiler Warnings regarding implicit truncation (e.g., Visual C++: warning: truncation from 'const double' to 'float' when assigning float x = 3.14;) are resolved using explicit suffixes (3.14f) or explicit casting ((float)3.14).

Formatted Output Operations

  • Standard Output Functions

    • C provides multiple functions in standard library header files for outputting data to screen:

    • printf(): Formatted screen output (stdio.h).

    • putchar(): Single character output (stdio.h).

    • putch(): Single ASCII character output without cursor progression (conio.h).

    • puts(): String output with automated trailing newline (stdio.h).

  • The printf() Function

    • Syntax: int printf(const char *format [, argument, ...]);

    • Format Specification Template: %[flags][width][.precision]type

    • Flags Specification:

    • Unspecified (none): Right-justified output.

    • - (minus): Left-justified output.

    • + (plus): Forces display of sign symbol (+ or -) for numeric values.

    • Width and Precision:

    • width: Minimum total column count reserved for output.

    • precision: Number of decimal places for floating points, or maximum character count for strings.

    • Type Specifiers Table:

    • d or i: Signed decimal integer

    • o: Unsigned octal integer

    • u: Unsigned decimal integer

    • x: Unsigned hexadecimal integer

    • f: Floating-point number

    • e: Exponential scientific notation floating-point

    • c: Single character

    • s: Character string

    • %: Literal % character

    • p: Pointer address

    • Long Data Type Prefixes:

    • long double: %lf

    • unsigned long int: %lu

    • long int: %ld

  • Formatting Examples and Results:

    • printf("%6d", 34); →\rightarrow 34 (Width 6, right-aligned)

    • printf("%-6d", 34); →\rightarrow 34 (Width 6, left-aligned)

    • printf("%10s", "BINUS"); →\rightarrow BINUS (Width 10, right-aligned)

    • printf("%-10s", "BINUS"); →\rightarrow BINUS (Width 10, left-aligned)

    • printf("%8.2f", 3.14159); →\rightarrow 3.14 (Width 8, 2 decimal places)

    • printf("%-8.3f", 3.14159); →\rightarrow 3.141 (Width 8, 3 decimal places, left-aligned)

    • printf("%c ", 65); →\rightarrow A

    • printf("%x ", 'A'); →\rightarrow 41 (Hexadecimal value of ASCII 65)

    • printf("%o ", 65); →\rightarrow 101 (Octal value of ASCII 65)

    • printf("%+d ", 34); →\rightarrow +34

    • printf("%+d ", -45); →\rightarrow -45

    • printf("%e ", 3.14); →\rightarrow 3.140000e+000

  • Advanced String Precision Formatting Example:

    • Given string array: char ss[] = "Selamat Datang";

    • printf("%.10s di Binus ", ss); →\rightarrow Selamat Da di Binus (Truncates string to first 10 characters)

    • printf("%10s di Binus ", ss); →\rightarrow Selamat Datang di Binus (Width 10 exceeded; expands naturally)

    • printf("%20.10s di Binus ", ss); →\rightarrow Selamat Da di Binus (Width 20, right-aligned, truncated to 10 characters)

    • printf("%-20.10s di Binus ", ss); →\rightarrow Selamat Da di Binus (Width 20, left-aligned, truncated to 10 characters)

  • Character and String Output Functions

    • putchar():

    • Header: <stdio.h> | Syntax: int putchar(int c);

    • Displays character c at cursor position and moves cursor to next position.

    • Returns displayed character on success, or EOF on error.

    • putch():

    • Header: <conio.h> | Syntax: int putch(int c);

    • Displays ASCII character without advancing cursor position.

    • puts():

    • Header: <stdio.h> | Syntax: int puts(const char *str);

    • Displays string str on monitor and automatically appends a newline character ().

    • Returns a non-negative integer on success, or EOF on error.

Formatted Input Operations

  • Input Operations Overview

    • Input operation is the process of reading data from standard input devices (keyboard/disk) into memory.

    • Standard Functions: scanf(), getchar(), getch(), getche(), gets().

  • The scanf() Function

    • Header: <stdio.h> | Syntax: int scanf(const char *format [, argument]...);

    • Arguments passed to scanf() must be pointers (memory addresses). The address-of operator & precedes scalar variable names.

    • Return Value: Integer representing the number of input fields successfully matched, converted, and assigned.

    • Example: r = scanf("%d %d %d", &x, &y, &z); with input 6 7 8 assigns values to x, y, z and sets r = 3.

scanf Format Specifiers and Descriptions
  • scanf() Format Specifiers Table:

    • d: Signed integer

    • u: Unsigned integer

    • x: Hexadecimal integer

    • e, f, g: Floating-point number

    • c: Single character

    • s: String terminated by whitespace

    • o: Unsigned octal integer

    • [...]: Scanset; reads string containing only characters enclosed within brackets

    • [^...]: Scanset; reads string until any character enclosed inside brackets is encountered

  • Distinction Between Variable Value and Address

    • For integer variable X allocated at memory address 45678 holding value 234:

    • X evaluates to 234 (R-value content)

    • &X evaluates to 45678 (L-value memory address)

  • String Input Handling via scanf()

    • Strings (character arrays) are implicitly memory pointers, so no address operator & is used in argument list (e.g., scanf("%s", ss);).

    • %s specifier stops reading upon encountering the first whitespace character (space, tab, newline).

    • Reading Line with Spaces: Use scanset scanf("%[^ ]", ss); to instruct scanf() to read all characters until a newline () key is pressed.

    • Scanset Range Rules: scanf("%[a-z]", ss); reads exclusively lower-case alphabetic characters. If input is http://binusmaya.binus.ac.id, processing terminates at : (non a–z character), resulting in ss containing only http.

    • Number Base Scanning: Scanning input 44 with %o stores octal 44 (decimal value 36); scanning with %x stores hexadecimal 44 (decimal value 68).

  • Single Character Input Functions Comparison

    • getchar():

    • Header: <stdio.h> | Syntax: int getchar(void);

    • Fetches next character from keyboard buffer.

    • Echoes character to monitor screen.

    • Requires user to press ENTER before returning control.

    • getch():

    • Header: <conio.h> | Syntax: int getch(void);

    • Fetches next character immediately from keyboard buffer.

    • Does not echo character to screen.

    • Does not wait for ENTER key.

    • getche():

    • Header: <conio.h> | Syntax: int getche(void);

    • Fetches next character immediately.

    • Echoes character to monitor screen.

    • Does not wait for ENTER key.

  • The gets() Function

    • Header: <stdio.h> | Syntax: char *gets(char *buffer);

    • Reads complete string line from keyboard buffer into memory until newline character () is encountered.

    • Automatically replaces trailing newline with a null terminator \0.

    • Returns buffer pointer on success, or NULL on error.

Code Implementations, Exercises, and Solutions

  • Complete Program 1: Circle Area Calculation

  /* Program circle area */
  #include <stdio.h>

  const float Pi = 3.14;

  int main(){
      float r;
      float area;
      scanf("%f", &r);
      area = Pi * r * r;
      printf("Circle area = %5.2f", area);
      return (0);
  }
&nbsp;&nbsp;```

- **Complete Program 2: Quadratic Equation Root Solver**

c #include #include

int main(){ double a, b, c, d, x1, x2; printf("Input coefficient of a: "); scanf("%lf", &a); printf("Input coefficient of b: "); scanf("%lf", &b); printf("Input coefficient of c: "); scanf("%lf", &c);

  d = b * b - 4 * a * c;

  if(d < 0) printf("Imaginary");
  else{
      x1 = (-b + sqrt(d)) / (2 * a);
      x2 = (-b - sqrt(d)) / (2 * a);
      printf("x1 = %lf x2 = %lf", x1, x2);
  }
  return 0;

}   ```

  • Detailed Solutions to Practice Exercises

    • Exercise Q1:

    • Statement: x = scanf("%d %d %d", &y, &z, &w);

    • Question: What happens if input was 2 integer values?

      • Answer: scanf() successfully assigns the 2 integers to y and z, remains waiting for 3rd integer, or if terminated prematurely returns x = 2.

    • Question: What is x value if 3 character values are given as input?

      • Answer: x = 0, because characters fail to match %d integer format conversion.

    • Exercise Q2:

    • Statement: x = scanf("%s %s", ss1, ss2);

    • Question: What are ss1 and ss2 if input is "Good morning everyone"?

      • Answer: ss1 = "Good", ss2 = "morning", and return value x = 2 ("everyone" remains unread in buffer).

    • Question: What is x if input is "Class 1PAT"?

      • Answer: ss1 = "Class", ss2 = "1PAT", and x = 2.

    • Exercise Q3:

    • Code: char ss[40]; scanf("%4s", ss); with input "Good morning".

      • Answer: ss = "Good" (Width specifier 4 restricts input to 4 characters).

    • Exercise Q4:

    • Code: char ch; ch = getchar(); with input "Binus".

      • Answer: ch = 'B' (Reads first character of string buffer).

    • Exercise Q5:

    • Code: char ch1, ch2; ch1 = getchar(); ch2 = getchar(); with input "Binus".

      • Answer: ch1 = 'B', ch2 = 'i'.

    • Exercise Q6:

    • Assignment: Create program calculating final grade: Final Score=0.20×Assignment+0.30×Mid+0.50×Final\text{Final Score} = 0.20 \times \text{Assignment} + 0.30 \times \text{Mid} + 0.50 \times \text{Final}.

    • Solution Code:

      #include <stdio.h>
    
      int main() {
          float assignment, mid, final_exam, final_score;
          printf("Input Assignment Score: "); scanf("%f", &assignment);
          printf("Input Mid Exam Score: "); scanf("%f", &mid);
          printf("Input Final Exam Score: "); scanf("%f", &final_exam);
          final_score = (0.20 * assignment) + (0.30 * mid) + (0.50 * final_exam);
          printf("Final Score = %.2f
    ", final_score);
          return 0;
      }
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;```
    - **Exercise Q7**:
    - Explanation of `gender = getchar()` execution skip issue:
      - When student number is entered via `scanf("%d", &nim);` and user presses `ENTER`, integer value is consumed but newline character `
    ` remains lingering in standard keyboard buffer. Subsequent `gender = getchar();` immediately consumes lingering `
    ` character without pausing for user input.
    - **Exercise Q8**:
    - Code Output evaluation:
    

    c #include int main(){ char ss[] = "10 % 3 = 1 "; char str[] = "Welcome to Binus everyone "; printf(ss); printf("%s", ss); printf(str); printf("%s", str); return 0; }       ```

    • Output Generated: text 10 % 3 = 1 10 % 3 = 1 Welcome to Binus everyone Welcome to Binus everyone &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

      • True/False Statements Verification:

      • Statement: "Every C program begins execution at main function." →\rightarrow TRUE.

      • Statement: "Comments cause the computer to print text enclosed between /* and */ on screen." →\rightarrow FALSE (Comments are ignored entirely by compiler).

      • Statement: "All variables must be defined before used." →\rightarrow TRUE.

      • Statement: "All variables must be given a type when defined." →\rightarrow TRUE.

      • Statement: "C considers number and Number to be identical." →\rightarrow FALSE (C is strictly case-sensitive).