Help improve SovranCode?

Google Analytics can measure anonymous usage after you choose Allow. Essential account and progress features work either way.

SovranCode
C: Foundations for Systems Programming Variables, Types, and Operators
This device
Course contentsVariables, Types, and Operators · 15 titles

C foundations

What C Is and How C Programs RunYour First C ProgramVariables, Types, and OperatorsInput and Output with printf and scanfConditions and Loops

Program structure and data

Functions, Headers, and ScopeArrays and StringsPointers and Memory AddressesStructures, Enumerations, and UnionsFiles and Command-Line Arguments

Memory, tooling, and practice

Dynamic Memory AllocationPreprocessor Directives and Separate CompilationErrors, Debugging, and Undefined BehaviorBuild Tools and MakefilesProject: Command-Line Inventory Manager
C: Foundations for Systems Programming15 complete lessons

C foundations

What C Is and How C Programs RunYour First C ProgramVariables, Types, and OperatorsInput and Output with printf and scanfConditions and Loops

Program structure and data

Functions, Headers, and ScopeArrays and StringsPointers and Memory AddressesStructures, Enumerations, and UnionsFiles and Command-Line Arguments

Memory, tooling, and practice

Dynamic Memory AllocationPreprocessor Directives and Separate CompilationErrors, Debugging, and Undefined BehaviorBuild Tools and MakefilesProject: Command-Line Inventory Manager
PREVIOUS LESSONYour First C Program
NEXT LESSONInput and Output with printf and scanf
C fundamentals 65 min

Variables, Types, and Operators

A program becomes useful when names stand for changing information. Learn the small, reliable path from a typed declaration to a calculation, an updated value, and terminal output—without losing track of what each value means.

What you will leave with

You will be able to declare and initialize int, double, and const char * values; distinguish declaration from assignment; trace arithmetic one operator at a time; explain integer division and remainder; choose matching printf placeholders; protect a fixed value with const; and build a readable summary from several values.

Make every value carry a clear promise

DeclarationsRead a type, a name, and an initial value as one deliberate contract.
Value flowTrace a value from input data through a calculation, storage, and observable output.
Format pairsMatch an int, double, or text value with the correct printf placeholder.
Small repairsUse a compiler or runner message to correct a broken type-related promise precisely.

A variable is a named place for a typed value

Read a declaration from left to right: the type says what kind of value the name may hold, the name gives that value a useful role, and the expression after = supplies the first value. In int remaining = capacity - enrolled;, the program evaluates the right side first, then stores the result in a new whole-number variable named remaining.

Keep three actions separate in your mental model. A declaration introduces a name and type. Initialization gives that newly declared name its first value. An assignment later replaces the value held by an already declared, mutable name. The equal sign is not a math claim; it means “compute the right side, then store it in the left-side variable.”

C FUNDAMENTALS RUNNER

Store a whole-number calculation

Change capacity or enrolled, predict the remaining-seat count, then run the source. Keep each value's meaning visible in its name.

#include <stdio.h>

int main(void) {
  int capacity = 24;
  int enrolled = 18;
  int remaining = capacity - enrolled;

  printf("%d seats remain.\n", remaining);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Add an int named waitlist, subtract it from remaining, and print the updated result with %d.

01Declare

Choose the type and give the value a meaningful name.

02Initialize

Compute or provide the first value after the declaration's =.

03Transform

Use an operator to calculate a new value from known values.

04Observe

Print the result with a placeholder that matches its type.

Use a type as a useful boundary

C has more types than a first lesson needs. Start with the ones that make everyday data intentions clear. A type does not merely label a value for the compiler: it determines the operations and representation rules that apply to it. Use the smallest type concept that accurately describes the problem, then let later lessons add detail about sizes, arrays, pointers, and conversion rules.

int

Whole-number quantities

Use int for counts, positions, completed tasks, and other values that should not include a fractional part. Its exact range is implementation-dependent, so do not assume it can store every possible real-world count without checking the requirements.

double

Fractional numeric values

Use double for quantities such as hours, measurements, and rates when a fraction matters. Binary floating-point values are approximations, so later you will learn why money and exact decimal rules require deliberate design.

const char *

Read-only text reference

This beginner form lets a name refer to a text string such as "C study lab". The pointer and string rules deserve their own lesson; for now, use it to give a label to output without trying to edit the string itself.

const

A value you do not plan to replace

Put const before a declaration when the name should not be assigned a new value through that variable. It documents an invariant and gives the compiler a chance to catch accidental reassignment.

Name the unit, not only the thing

session_hours, open_seats, and pages_per_chapter make the expected unit visible. Names such as x, value, or data force readers to reconstruct the meaning every time they trace a calculation.

Update a variable by reading, calculating, then storing

An assignment can reuse the current value of the same variable. C evaluates the expression on the right before it changes the left. In checked_in = checked_in + 1;, the old count is read, one is added, and the new count replaces the old value. Nothing “changes itself”; each step has a clear order.

C FUNDAMENTALS RUNNER

Trace a reassignment

Run the starter once. Then change the amount added to checked_in and explain the old value, the calculation, and the stored result.

#include <stdio.h>

int main(void) {
  int checked_in = 12;

  checked_in = checked_in + 1;
  printf("%d learners have checked in.\n", checked_in);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Add a second assignment that subtracts one cancellation, then print the final count only once.

Do not use an uninitialized value

A local variable must receive a meaningful value before you read it. Compilers often warn when they can prove that a path uses an uninitialized variable. Treat that warning as a real missing decision, not as cosmetic noise.

Calculate with operators—and read their order

Arithmetic operators transform numeric values. Multiplication, division, and remainder happen before addition and subtraction. Parentheses make a grouping explicit when the calculation matters to a human reader. Rather than memorizing a long precedence table, write a small named intermediate value or use parentheses whenever a reader could reasonably misread your intent.

+   -

Add and subtract

Combine quantities or calculate a difference: open_seats = seats - booked.

*   /

Multiply and divide

Scale a quantity or split it into groups. The types of both operands affect division.

%

Find an integer remainder

For integers, 17 % 5 is 2: five fits three times with two left over.

C FUNDAMENTALS RUNNER

Calculate groups and a remainder

Change the chapter count or group size. Before running it, predict total_pages, whole_groups, and spare_pages independently.

#include <stdio.h>

int main(void) {
  int pages_per_chapter = 8;
  int chapters = 3;
  int total_pages = pages_per_chapter * chapters;
  int whole_groups = total_pages / 5;
  int spare_pages = total_pages % 5;

  printf("Total pages: %d\n", total_pages);
  printf("Groups of five: %d, spare: %d\n", whole_groups, spare_pages);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Add parentheses to one expression, then change the group size from 5 to 6 and explain the new quotient and remainder.

Integer division discards the fractional part

When both operands are int, 7 / 2 produces 3, not 3.5. If the fraction matters, use floating-point operands deliberately—for example 7.0 / 2.0—and keep the result in a floating-point type. The browser runner demonstrates the lesson subset; use a local compiler as the authority for full conversion rules.

Match a value's type to its output format

printf needs a format string and values that match it. In this lesson, pair %d with an int, %f with a double, and %s with a text reference such as const char *. A mismatched format can make a real C program behave unpredictably, so treat each placeholder as part of the value's contract.

C FUNDAMENTALS RUNNER

Calculate and format a double

This program uses decimal operands, so the division and multiplication remain fractional when needed. The lesson runner displays %f with six digits after the decimal point, as printf does by default.

#include <stdio.h>

int main(void) {
  double session_hours = 1.5;
  double weekly_hours = session_hours * 3.0;

  printf("Weekly study time: %f hours\n", weekly_hours);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change session_hours to 1.25 and weekly_hours to session_hours * 4.0. Predict the exact six-decimal output before running it.

printf("%d", count)

Print an int

%d asks printf to interpret the corresponding value as an integer. Use it for whole-number counts and calculation results.

printf("%f", hours)

Print a double

%f displays a floating-point value. In this beginner form, standard printf displays six decimal places unless you later specify a precision.

printf("%s", name)

Print text

%s expects a pointer to a null-terminated character sequence. You will study that representation carefully in the arrays-and-strings unit.

printf("%%")

Print a percent sign

Two percent characters in the format string request one literal percent sign. This keeps output formatting separate from the value expressions that follow the string.

Protect a fixed rule with const

Use const when a name represents a rule or fixed configuration that this function must not overwrite. The broken source below tries to change max_attempts after promising it is constant. Read the runner message, then make one intentional repair: either preserve the fixed rule by removing the assignment, or make the value truly mutable by changing only const int to int.

C FUNDAMENTALS RUNNER

Repair a const contract

Do not guess at multiple changes. Decide whether max_attempts is a fixed rule or a changing counter, then make the source match that decision.

#include <stdio.h>

int main(void) {
  const int max_attempts = 3;

  max_attempts = max_attempts + 1;
  printf("Maximum attempts: %d\n", max_attempts);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Choose one repair, run it, and explain why that version has a clearer contract.

Compile with conversion warnings visible

Save a version of these examples as values.c. A local compiler understands the full C language and your system's implementation choices. Use warning flags while you experiment so a suspicious conversion or formatting mismatch is visible before it becomes a hard-to-find output bug.

macOSCompile with Clang and ask for useful conversion evidence.clang -Wall -Wextra -Wpedantic -Wconversion values.c -o values./values
LinuxCompile with GCC or Clang from your build-tools package.gcc -Wall -Wextra -Wpedantic -Wconversion values.c -o values./valuesUse the diagnostic line and its nearby source, then make the smallest correction that restores the intended type relationship.
WindowsCompile from a configured Developer Command Prompt.cl /W4 values.cvalues.exeToolchains use different flag names, but the habit stays the same: read warnings before trusting an apparently successful build.

Independent lab: report a study session

Use the starter to produce a short, readable terminal report. Change the session name, seats, booked count, and duration. Then add a new int calculation that has a clear unit—perhaps reserved_seats or remaining_after_waitlist—and print it using the correct placeholder. Your program should have a label, a whole-number calculation, a fractional value, and a visible success status.

C FUNDAMENTALS RUNNER

Build a typed study-session report

Use the starter's structure, but make all values describe a real session you could explain to another person. Predict the output before running it.

#include <stdio.h>

int main(void) {
  const char *session_name = "C study lab";
  int seats = 32;
  int booked = 19;
  int open_seats = seats - booked;
  double session_hours = 1.5;

  printf("%s\n", session_name);
  printf("%d seats are open.\n", open_seats);
  printf("Length: %f hours\n", session_hours);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Add one named integer calculation and one matching %d output line. Then decide whether session_hours should remain a double and explain why.

Lesson review

You now have the core data flow that every later C program will use: choose a type, give the value a meaningful name, initialize it, calculate with the correct operators, update it only when the program's rules permit it, and format the output according to the value's type. The next lesson will add input, which means users will start supplying some of those values themselves.

  • I can distinguish a declaration, initialization, and later assignment in a C source file.
  • I can choose int for a whole-number count, double for a fractional quantity, and const char * for a beginner text label.
  • I can trace + - * / %, state the difference between integer division and remainder, and add parentheses or a named intermediate value when clarity needs it.
  • I can match %d, %f, and %s to the values passed to printf, and use const to protect a fixed rule.
KNOWLEDGE CHECK

Name the value, type, and operation

Answer from the source model rather than memorizing punctuation. Then use each explanation to connect a declaration, assignment, operator, and output placeholder.

01Which declaration is the clearest choice for a whole-number count of available seats?
02After this code runs, what value does checked_in hold? int checked_in = 8; checked_in = checked_in + 2;
03What is the value of 17 % 5 when both operands are int values?
04Why is const int max_attempts = 3; useful?
05Which printf placeholder matches a double value such as double hours = 1.5; in this lesson?
PREVIOUS LESSONYour First C Program
NEXT LESSONInput and Output with printf and scanf
ON THIS PAGEVariables, Types, and OperatorsLesson mapVariablesTypesAssignmentOperatorsDouble and printfConstantsCompile locallyIndependent labLesson reviewKnowledge check
Course contents