🐛Intro to Computer Programming
Fundamental Programming Functions
Study smarter with Fiveable
Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.
Why This Matters
Every program you'll ever write—from a simple calculator to a complex web application—relies on the same core building blocks. When you're tested on programming fundamentals, you're not just being asked to recall syntax; you're being evaluated on whether you understand how data flows through a program, how decisions get made, and how repetition creates efficiency. These concepts form the foundation for everything from algorithm design to software architecture.
Think of these functions as your programming vocabulary. Variables store your data, control structures direct traffic, and functions package logic for reuse. Master the underlying principles—not just the code snippets—and you'll be able to apply them in any language or context. Don't just memorize what each function does; know why you'd choose one approach over another and when each tool is the right fit.
Data Storage and Types
Programs need somewhere to keep information while they work. The way you store data determines what operations you can perform on it and how efficiently your program runs.
Variables and Data Types
- Variables act as named containers—they hold values that can change during program execution, like
score = 0becomingscore = 100 - Data types define what kind of value a variable holds: integers (whole numbers), floats (decimals), strings (text), and booleans (true/false)
- Type mismatches cause errors—trying to add
"5"(string) +5(integer) fails in strongly-typed languages because the computer sees text and numbers differently
Arrays and Lists
- Arrays store multiple values under one name—access individual elements using an index, like
grades[0]for the first item - Arrays are fixed-size; lists are dynamic—arrays require you to declare size upfront, while lists grow and shrink as needed
- Zero-based indexing is standard in most languages—the first element is at position
0, not1, which is a common source of off-by-one errors
String Manipulation
- Strings are sequences of characters—you can slice them (
"hello"[0:2]returns"he"), concatenate them ("hello" + "world"), or search within them - Common string methods include
.length(),.toUpperCase(),.split(), and.replace()—these transform text without changing the original - Immutability matters—in many languages, strings can't be modified in place; operations create new strings, which affects memory usage
Compare: Arrays vs. Lists—both store collections, but arrays offer faster access with fixed memory allocation while lists provide flexibility at the cost of some performance. If an exam asks about choosing data structures, consider whether your data size is known upfront.
Input and Output Operations
Programs are useless if they can't communicate with users or other systems. I/O operations bridge the gap between your code and the outside world.
Input and Output Operations
- Input functions capture external data—
input()in Python orScannerin Java pause execution and wait for user response - Output functions display results—
print(),console.log(), orSystem.out.println()send data to the screen or console - Always validate input—users enter unexpected data; check that a number is actually a number before performing calculations
Basic File Handling
- Files enable data persistence—without files, all data disappears when the program ends; files let you save and retrieve information
- The open-read/write-close pattern is universal: open a file handle, perform operations, then close to free system resources
- File modes matter—
"r"for reading,"w"for writing (overwrites!),"a"for appending; using the wrong mode can destroy data
Compare: Console I/O vs. File I/O—both move data in and out of your program, but console operations are temporary and interactive while file operations persist data permanently. FRQs often ask you to modify programs to save results—know how to switch between them.
Control Flow and Decision Making
Programs need to make choices and respond to different conditions. Control structures determine which code runs and when, giving your programs intelligence.
Conditional Statements (if-else)
ifstatements create decision points—code inside the block only executes when the condition evaluates totrueelseandelse ifhandle alternatives—chain multiple conditions to cover all possible scenarios: if this, else if that, else default- Boolean expressions drive conditions—comparisons like
$$x > 5$$,$$y == 10$$, or$$z != 0$$return true or false to trigger branches
Loops (for, while)
forloops iterate a known number of times—use when you know exactly how many repetitions:for i in range(10)runs exactly 10 timeswhileloops continue until a condition fails—use when repetition depends on changing state: keep asking for input until it's valid- Infinite loops occur when exit conditions never trigger—forgetting to update the loop variable means
while(true)runs forever
Compare: for vs. while loops—both repeat code, but for loops excel when you know the iteration count upfront (traversing an array), while while loops handle uncertain conditions (waiting for valid input). Choosing the wrong loop type is a common exam trap.
Operations and Calculations
Computers excel at math and manipulation. Understanding operators and their rules ensures your calculations produce correct results.
Arithmetic Operations
- Basic operators include
+(addition),-(subtraction),*(multiplication),/(division), and%(modulus, which returns the remainder) - Operator precedence follows math rules—multiplication and division before addition and subtraction; use parentheses to override:
$$(2 + 3) * 4 = 20$$vs.$$2 + 3 * 4 = 14$$ - Integer vs. float division behaves differently—
$$7 / 2$$might return3(integer division) or3.5(float division) depending on language and data types
Compare: / vs. % operators—division gives you the quotient, modulus gives you the remainder. Modulus is essential for checking divisibility ($$n \% 2 == 0$$ means even), cycling through arrays, or extracting digits. Both appear frequently in algorithm questions.
Code Organization and Reusability
Good programmers avoid repeating themselves. Functions and methods package logic into reusable units, making code cleaner and easier to maintain.
Functions and Methods
- Functions are named, reusable code blocks—define once with
def functionName():or similar syntax, then call anywhere by name - Parameters pass data in; return values pass data out—
def add(a, b): return a + btakes two inputs and sends back their sum - Methods are functions attached to objects—
myString.upper()calls theuppermethod on that specific string instance, a key concept in object-oriented programming
Error Handling and Debugging
- Try-catch blocks anticipate failures—wrap risky code in
try, handle problems incatchorexceptwithout crashing the entire program - Common error types include syntax errors (code won't run), runtime errors (crashes during execution), and logic errors (wrong output, hardest to find)
- Debugging strategies include print statements to trace values, breakpoints to pause execution, and reading error messages carefully—the line number is your friend
Compare: Functions vs. Methods—both encapsulate reusable logic, but functions are standalone while methods belong to objects and can access that object's data. Understanding this distinction is crucial for object-oriented programming questions.
Quick Reference Table
| Concept | Best Examples |
|---|---|
| Data Storage | Variables, Arrays, Lists |
| Data Types | Integers, Floats, Strings, Booleans |
| User Interaction | Input operations, Output operations, Console I/O |
| Decision Making | if-else statements, Boolean expressions |
| Repetition | for loops, while loops |
| Calculations | Arithmetic operators, Operator precedence, Modulus |
| Code Reuse | Functions, Methods, Parameters/Return values |
| Data Persistence | File reading, File writing, Open/Close pattern |
| Error Management | Try-catch blocks, Debugging techniques |
Self-Check Questions
-
Which two concepts both store multiple values, and what's the key difference in how they handle size?
-
If you need to repeat code but don't know in advance how many times, which loop type should you use and why?
-
Compare and contrast functions and methods—when would you use each, and how do they relate to object-oriented programming?
-
A program crashes when a user enters "abc" instead of a number. Which two fundamental concepts would you combine to prevent this crash?
-
You're writing a program that needs to save high scores between gaming sessions. Which fundamental concept enables this, and what's the standard pattern for implementing it?