upgrade
upgrade

🐛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.

Get Started

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 = 0 becoming score = 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, not 1, 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 datainput() in Python or Scanner in Java pause execution and wait for user response
  • Output functions display resultsprint(), console.log(), or System.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)

  • if statements create decision points—code inside the block only executes when the condition evaluates to true
  • else and else if handle 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)

  • for loops iterate a known number of times—use when you know exactly how many repetitions: for i in range(10) runs exactly 10 times
  • while loops 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 return 3 (integer division) or 3.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 outdef add(a, b): return a + b takes two inputs and sends back their sum
  • Methods are functions attached to objectsmyString.upper() calls the upper method 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 in catch or except without 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

ConceptBest Examples
Data StorageVariables, Arrays, Lists
Data TypesIntegers, Floats, Strings, Booleans
User InteractionInput operations, Output operations, Console I/O
Decision Makingif-else statements, Boolean expressions
Repetitionfor loops, while loops
CalculationsArithmetic operators, Operator precedence, Modulus
Code ReuseFunctions, Methods, Parameters/Return values
Data PersistenceFile reading, File writing, Open/Close pattern
Error ManagementTry-catch blocks, Debugging techniques

Self-Check Questions

  1. Which two concepts both store multiple values, and what's the key difference in how they handle size?

  2. If you need to repeat code but don't know in advance how many times, which loop type should you use and why?

  3. Compare and contrast functions and methods—when would you use each, and how do they relate to object-oriented programming?

  4. A program crashes when a user enters "abc" instead of a number. Which two fundamental concepts would you combine to prevent this crash?

  5. 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?