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
Step 2: Input the second number
Step 3: Add and , store the result in
Step 4: Display
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
Step 2: Read number
Step 3: Read number
Step 4: Compute
Step 5: Display average
Algorithm 2:
Step 1: Read all three numbers together
Step 2: Store them as , , and
Step 3: Compute
Step 4: Compute
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 . Data needed: Coefficients , , and of real type.
2. Model Development: Formulate mathematical models and equations needed for calculation.
Example Mathematical Model: Quadratic formula , , and .
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.

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-inOutput:
print,write,put,output,displayStoring Value:
set,store,save,initializeDecision (Selection):
if ... then ... else ... endifRepetition (Loop):
dowhile ... enddo,while ... endwhile,forCompute:
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
StartSet the calculator ONEmpty any valuesDoInput pricePush plus button (+)
While all prices have not been inputPrint total priceSet the calculator OFFEndExample 2: Class Average Score Calculation
StartSet total = 0Set grade counter = 1While grade counter is less than or equal to 10Input next scoreAdd score into totalAdd 1 to grade counter
Set class average = total / 10Print the class averageEnd
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.

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()FunctionEvery executable C program must contain exactly one
main()function, serving as execution start point.C is strictly case-sensitive (
mainis distinct fromMain,sumis distinct fromSum).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()andint main()compile cleanly; baremain()emits warnings.In Dev-C++ (Windows) and GCC (Linux):
int main()and baremain()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:

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:
chValue:
65(ASCII representation of character'A')Memory Address:
123456Value Range: to
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.voidusage: Indicates functions that return no value, or generic typeless pointers.

Comprehensive Data Type Specification Table:
char| Syntax:char| Memory: 1 byte | Range: tounsigned char| Syntax:unsigned char| Memory: 1 byte | Range: tointeger| Syntax:int| Memory: 4 bytes | Range: tounsigned int| Syntax:unsigned int| Memory: 4 bytes | Range: toshort int| Syntax:short int| Memory: 2 bytes | Range: tounsigned short int| Syntax:unsigned short int| Memory: 2 bytes | Range: tolong int| Syntax:long int| Memory: 4 bytes | Range: tounsigned long int| Syntax:unsigned long int| Memory: 4 bytes | Range: tolong long| Syntax:long long| Memory: 8 bytes | Range: tounsigned long long| Syntax:unsigned long long| Memory: 8 bytes | Range: tofloat| Syntax:float| Memory: 4 bytes | Range: todouble| Syntax:double| Memory: 8 bytes | Range: tolong double| Syntax:long double| Memory: 8 bytes | Range: to
Type Casting
The explicit conversion of a variable from one data type to another.
Syntax:
(data type) expressionCode Example:
c} int x; float f = 3.134; x = (int) f; // Casting float to int; x becomes 3
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,1Floating-point Constant:
3.14Character Constant:
'c','1','$'Escape Sequence: ,
\t,\"String Constant:
"BINUS","B"Symbolic Constant: Declared via
#define PHI 3.14orconst float PHI = 3.14;Symbolic constants declared via
#definedo not allocate variable memory spaces.
The
sizeofOperatorUnary operator used to evaluate the memory footprint (in bytes) of data types or expressions.
Syntax:
sizeof(expression)orsizeof(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:
Forf:floatdata type (e.g.,3.14fallocates 4 bytes)Unsuffixed floating constant: Default
doubledata type (e.g.,3.14allocates 8 bytes)Lorl:long doubledata type (e.g.,3.14Lallocates 16 bytes on supported compilers)Integer Suffixes:
Uoru:unsigned int(e.g.,174u)Lorl:long int(e.g.,174L)UL,ul,LU, orlu:unsigned long int(e.g.,174ul)Unsuffixed integer constant: Default
intdata type (e.g.,174)Compiler Warnings regarding implicit truncation (e.g., Visual C++:
warning: truncation from 'const double' to 'float'when assigningfloat 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()FunctionSyntax:
int printf(const char *format [, argument, ...]);Format Specification Template:
%[flags][width][.precision]typeFlags 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:
dori: Signed decimal integero: Unsigned octal integeru: Unsigned decimal integerx: Unsigned hexadecimal integerf: Floating-point numbere: Exponential scientific notation floating-pointc: Single characters: Character string%: Literal%characterp: Pointer addressLong Data Type Prefixes:
long double:%lfunsigned long int:%lulong int:%ld
Formatting Examples and Results:
printf("%6d", 34);34(Width 6, right-aligned)printf("%-6d", 34);34(Width 6, left-aligned)printf("%10s", "BINUS");BINUS(Width 10, right-aligned)printf("%-10s", "BINUS");BINUS(Width 10, left-aligned)printf("%8.2f", 3.14159);3.14(Width 8, 2 decimal places)printf("%-8.3f", 3.14159);3.141(Width 8, 3 decimal places, left-aligned)printf("%c ", 65);Aprintf("%x ", 'A');41(Hexadecimal value of ASCII 65)printf("%o ", 65);101(Octal value of ASCII 65)printf("%+d ", 34);+34printf("%+d ", -45);-45printf("%e ", 3.14);3.140000e+000
Advanced String Precision Formatting Example:
Given string array:
char ss[] = "Selamat Datang";printf("%.10s di Binus ", ss);Selamat Da di Binus(Truncates string to first 10 characters)printf("%10s di Binus ", ss);Selamat Datang di Binus(Width 10 exceeded; expands naturally)printf("%20.10s di Binus ", ss);Selamat Da di Binus(Width 20, right-aligned, truncated to 10 characters)printf("%-20.10s di Binus ", ss);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
cat cursor position and moves cursor to next position.Returns displayed character on success, or
EOFon 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
stron monitor and automatically appends a newline character ().Returns a non-negative integer on success, or
EOFon 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()FunctionHeader:
<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 input6 7 8assigns values tox, y, zand setsr = 3.

scanf()Format Specifiers Table:d: Signed integeru: Unsigned integerx: Hexadecimal integere,f,g: Floating-point numberc: Single characters: String terminated by whitespaceo: 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
Xallocated at memory address45678holding value234:Xevaluates to234(R-value content)&Xevaluates to45678(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);).%sspecifier stops reading upon encountering the first whitespace character (space, tab, newline).Reading Line with Spaces: Use scanset
scanf("%[^ ]", ss);to instructscanf()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 ishttp://binusmaya.binus.ac.id, processing terminates at:(nona–zcharacter), resulting insscontaining onlyhttp.Number Base Scanning: Scanning input
44with%ostores octal44(decimal value36); scanning with%xstores hexadecimal44(decimal value68).
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
ENTERbefore 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
ENTERkey.getche():Header:
<conio.h>| Syntax:int getche(void);Fetches next character immediately.
Echoes character to monitor screen.
Does not wait for
ENTERkey.
The
gets()FunctionHeader:
<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
bufferpointer on success, orNULLon 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);
}
```
- **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 toyandz, remains waiting for 3rd integer, or if terminated prematurely returnsx = 2.
Question: What is
xvalue if 3 character values are given as input?Answer:
x = 0, because characters fail to match%dinteger format conversion.
Exercise Q2:
Statement:
x = scanf("%s %s", ss1, ss2);Question: What are
ss1andss2if input is"Good morning everyone"?Answer:
ss1 = "Good",ss2 = "morning", and return valuex = 2("everyone"remains unread in buffer).
Question: What is
xif input is"Class 1PAT"?Answer:
ss1 = "Class",ss2 = "1PAT", andx = 2.
Exercise Q3:
Code:
char ss[40]; scanf("%4s", ss);with input"Good morning".Answer:
ss = "Good"(Width specifier4restricts 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: .
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; } ``` - **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 True/False Statements Verification:
Statement: "Every C program begins execution at main function." TRUE.
Statement: "Comments cause the computer to print text enclosed between
/*and*/on screen." FALSE (Comments are ignored entirely by compiler).Statement: "All variables must be defined before used." TRUE.
Statement: "All variables must be given a type when defined." TRUE.
Statement: "C considers
numberandNumberto be identical." FALSE (C is strictly case-sensitive).