Lesson 01beginnerFoundation

Introduction to C

Transition from C++ to C. Covers scanf/printf, string handling with fgets, file I/O using fopen/fclose, structs, complex format specifiers, functions with pointer parameters, and dynamic 2D allocation.

scanfprintffopenstructspointers
1

Hello, printf

The first C program: #include <stdio.h>, int main(void), and printf with \n instead of cout and endl — plus the escape sequences \t, \" and \\.

00a-hello-printf.c
/*
 * 00a-hello-printf.c — Your first C program: printf instead of cout
 *
 * Key concepts: #include <stdio.h>, int main(void), printf, \n and other escape sequences
 * Compile: gcc -o hello 00a-hello-printf.c
 * Run:     ./hello
 *
 * C++:  std::cout << "Hello" << std::endl;
 * C:    printf("Hello\n");
 */

#include <stdio.h>   // printf and scanf live here (C++ used <iostream>)

int main(void)       // (void) = "takes no arguments" — in C, () means "unspecified"
{
    printf("Hello from C!\n");           // \n ends the line — there is no endl
    printf("No newline here... ");
    printf("so this continues the same line.\n");

    printf("Escape sequences:\n");
    printf("  \\n  new line\n");
    printf("  \\t  tab:\t[after a tab]\n");
    printf("  \\\"  a quote: \"quoted\"\n");
    printf("  \\\\  a backslash: \\\n");

    return 0;        // 0 = success; the shell sees it as the exit status ($?)
}
$ gcc -o hello 00a-hello-printf.c
$ ./hello
Expected Outputclick Run to execute live
Hello from C!
No newline here... so this continues the same line.
Escape sequences:
  \n  new line
  \t  tab:	[after a tab]
  \"  a quote: "quoted"
  \\  a backslash: \
2

printf Format Specifiers

One specifier per type — %d, %f, %.2f, %e, %c, %s, %x and %% — and how several arguments are matched to the format left to right.

00b-printf-specifiers.c
/*
 * 00b-printf-specifiers.c — printf format specifiers: one per type
 *
 * Key concepts: %d %f %c %s %x %e %%, matching each specifier to an argument
 * Compile: gcc -o specifiers 00b-printf-specifiers.c
 * Run:     ./specifiers
 *
 * printf("format", arg1, arg2, ...): every % in the format consumes the next argument,
 * in order. The specifier MUST match the argument's type — the compiler only warns.
 */

#include <stdio.h>

int main(void)
{
    int age = 21;
    double pi = 3.14159265;
    char grade = 'A';
    char name[] = "Dana";        // a string is an array of chars ending with '\0'

    printf("%%d  int:        %d\n", age);
    printf("%%f  double:     %f\n", pi);          // 6 digits after the point by default
    printf("%%.2f 2 digits:  %.2f\n", pi);
    printf("%%e  scientific: %e\n", pi);
    printf("%%c  char:       %c\n", grade);
    printf("%%s  string:     %s\n", name);
    printf("%%x  hex:        %x\n", 255);
    printf("%%%%  a percent sign: 100%%\n");

    // Several values in one call — matched left to right
    printf("%s is %d years old and got %c (pi = %.3f)\n", name, age, grade, pi);

    return 0;
}
$ gcc -o specifiers 00b-printf-specifiers.c
$ ./specifiers
Expected Outputclick Run to execute live
%d  int:        21
%f  double:     3.141593
%.2f 2 digits:  3.14
%e  scientific: 3.141593e+00
%c  char:       A
%s  string:     Dana
%x  hex:        ff
%%  a percent sign: 100%
Dana is 21 years old and got A (pi = 3.142)
3

Width, Alignment and Padding

Field widths in printf: %5d, %-5d, %05d and %8.2f, used to print a neatly aligned table.

00c-printf-width.c
/*
 * 00c-printf-width.c — Width, alignment and padding: printing tables
 *
 * Key concepts: %5d (right-aligned), %-10s (left-aligned), %05d (zero padding), %8.2f
 * Compile: gcc -o width 00c-printf-width.c
 * Run:     ./width
 *
 * The number between % and the letter is the MINIMUM width of the field.
 */

#include <stdio.h>

int main(void)
{
    printf("[%d]    no width\n", 42);
    printf("[%5d] width 5, right-aligned\n", 42);
    printf("[%-5d] width 5, left-aligned\n", 42);
    printf("[%05d] width 5, zero-padded\n", 42);
    printf("[%8.2f] width 8, 2 decimals\n", 3.14159);
    printf("[%-8s] string, left-aligned\n", "C");
    printf("[%8s] string, right-aligned\n", "C");

    // A small table: same widths on every row keep the columns straight
    printf("\n%-10s %6s %8s\n", "Name", "Grade", "Average");
    printf("%-10s %6d %8.1f\n", "Dana", 95, 91.25);
    printf("%-10s %6d %8.1f\n", "Avi", 78, 80.5);
    printf("%-10s %6d %8.1f\n", "Noa", 100, 97.75);

    return 0;
}
$ gcc -o width 00c-printf-width.c
$ ./width
Expected Outputclick Run to execute live
[42]    no width
[   42] width 5, right-aligned
[42   ] width 5, left-aligned
[00042] width 5, zero-padded
[    3.14] width 8, 2 decimals
[C       ] string, left-aligned
[       C] string, right-aligned

Name        Grade  Average
Dana           95     91.2
Avi            78     80.5
Noa           100     97.8
4

Reading a Number with scanf

scanf("%d", &n) instead of cin >> n: why the & is needed, and checking scanf's return value to catch input that is not a number.

00d-scanf-one-int.c
/*
 * 00d-scanf-one-int.c — Reading one number with scanf (instead of cin >>)
 *
 * Key concepts: scanf("%d", &n), why the & is needed, scanf's return value
 * Compile: gcc -o read_int 00d-scanf-one-int.c
 * Run:     ./read_int      (type a number and press Enter — then try typing "abc")
 *
 * C++:  std::cin >> n;
 * C:    scanf("%d", &n);   — scanf needs the ADDRESS of n (&n) so it can write into it.
 *       Forgetting the & is the classic first C bug: scanf writes to a random address.
 */

#include <stdio.h>

int main(void)
{
    int n = 0;

    printf("Enter a whole number: ");
    int matched = scanf("%d", &n);   // returns how many values it managed to read

    if (matched == 1)
        printf("You entered %d, twice that is %d\n", n, n * 2);
    else
        printf("That was not a number (scanf returned %d)\n", matched);

    return 0;
}
$ gcc -o read_int 00d-scanf-one-int.c
$ ./read_int
Expected Outputclick Run to execute live
42
Enter a whole number: You entered 42, twice that is 84
Asks for input — sample input is one click away
5

Several Values in One scanf

Reading an int and a double together with "%d %lf" (%lf for double), and a literal comma in the format with "%d,%d".

00e-scanf-many.c
/*
 * 00e-scanf-many.c — Reading several values, of different types, in one scanf
 *
 * Key concepts: %d %lf in one format, %lf for double (printf uses %f), literal characters in the format
 * Compile: gcc -o read_many 00e-scanf-many.c
 * Run:     ./read_many     (try: 7 2.5   then   3,4)
 *
 * Spaces and Enter between numbers are skipped automatically.
 * Any other character in the format (like the comma in "%d,%d") must appear in the input.
 */

#include <stdio.h>

int main(void)
{
    int count;
    double price;

    printf("How many items and the price of one (e.g. 7 2.5): ");
    if (scanf("%d %lf", &count, &price) != 2) {   // %lf reads a double; %f would read a float
        printf("Expected a whole number and a decimal number.\n");
        return 1;
    }
    printf("%d x %.2f = %.2f\n", count, price, count * price);

    int x, y;
    printf("A point as x,y (e.g. 3,4): ");
    if (scanf("%d,%d", &x, &y) == 2)              // the comma must be typed too
        printf("Point (%d, %d)\n", x, y);
    else
        printf("Could not read x,y — did you type the comma?\n");

    return 0;
}
$ gcc -o read_many 00e-scanf-many.c
$ ./read_many
Expected Outputclick Run to execute live
7 2.5
3,4
How many items and the price of one (e.g. 7 2.5): 7 x 2.50 = 17.50
A point as x,y (e.g. 3,4): Point (3, 4)
Asks for input — sample input is one click away
6

Strings, Characters and the Leftover Newline

%s stops at the first space and needs no &, %19s limits the length, and " %c" with a cleared input line avoids the classic leftover-newline bug.

00f-scanf-strings-chars.c
/*
 * 00f-scanf-strings-chars.c — Strings and single characters with scanf, and the leftover newline
 *
 * Key concepts: %s stops at whitespace, no & for arrays, %19s limits the length, " %c" skips the '\n'
 * Compile: gcc -o read_text 00f-scanf-strings-chars.c
 * Run:     ./read_text     (try typing two words: Yaniv Gabay)
 */

#include <stdio.h>

int main(void)
{
    char first[20];
    char initial;

    printf("Your full name: ");
    scanf("%19s", first);   // no &: the array name is already an address; 19 + '\0' = 20
    printf("%%s read only \"%s\" — it stops at the first space\n", first);

    // The rest of the line (" Gabay" + Enter) is still waiting in the input buffer:
    // the next scanf would read 'G' from it instead of waiting for you. Throw it away first.
    int c;
    while ((c = getchar()) != '\n' && c != EOF)
        ;

    printf("Your grade letter: ");
    scanf(" %c", &initial);   // the space before %c skips any spaces/Enter left over — a good habit
    printf("Grade '%c' — its ASCII code is %d\n", initial, initial);

    return 0;
}
$ gcc -o read_text 00f-scanf-strings-chars.c
$ ./read_text
Expected Outputclick Run to execute live
Yaniv Gabay
A
Your full name: %s read only "Yaniv" — it stops at the first space
Your grade letter: Grade 'A' — its ASCII code is 65
Asks for input — sample input is one click away
7

Basic Input & Output

Side-by-side comparison of C scanf/printf versus C++ cin/cout, showing equivalent I/O operations.

01-basic-input-output.c
$ gcc -o basic_io 01-basic-input-output.c
$ ./basic_io
Expected Outputclick Run to execute live
--- Section 1: Reading input with scanf ---

  Enter a number: 42
  You entered: 42

--- Section 2: Parsing strings with sscanf ---

  Format       | Input                | Result     | Notes
  ------------ | -------------------- | ---------- | -----
  %d           | 42                   | 42         | integer
  %f           | 3.14                 | 3.14       | float
  %2d          | 99                   | 99         | 2-digit only
  %f (sci)     | 1.23E4               | 12300      | scientific

--- Section 3: String parsing with %s (max 9 chars) ---

  Input: "       HelloWorld"   -> %9s -> "HelloWorl"
  Input: "Hello         World" -> %9s -> "Hello"  (stops at whitespace)
  Input: "   a b c d e..."     -> %9s -> "a"  (skips leading spaces)

--- Section 4: Parsing multiple fields at once ---

  Input:  "25 54.32E-1 Thompson 56789"
  Format: "%d%f%9s%2d%f%*d"

  Fields converted: 5
  %d   -> i    = 25
  %f   -> x    = 5.432
  %9s  -> str1 = "Thompson"
  %2d  -> j    = 56     (only first 2 digits of 56789)
  %f   -> y    = 789   (remaining digits)
  %*d  -> skipped       (the * means: read but discard)

--- Section 5: Scansets — character class matching ---

  %3[0-9]  : digits only, max 3
  Input:  "123456"
  Result: "123"  (first 3 digits)

  %3[0-9]  : stops at non-digit
  Input:  "12a3456"
  Result: "12"  (stopped at 'a')

  %9[^X]   : everything except 'X'
  Input:  "123456X789"
  Result: "123456"  (stopped at 'X')

  %[a-zA-Z]: alphabetic only
  Input:  "abcd4"
  Result: "abcd"  (stopped at '4')

  %[^\n]   : read until newline
  Input:  "Hello World
 abcde"
  Result: "Hello World"  (stopped at \n)
Asks for input — sample input is one click away
8

More Basic I/O

Extended I/O examples covering multiple data types and format specifiers.

02-more-basic-input-output.c
/*
 * 02-more-basic-input-output.c — More I/O — multiple data types and format specifiers
 *
 * Key concepts: scanf, printf, data types
 * Compile: gcc -o prog 02-more-basic-input-output.c
 * Run:     ./prog
 */


// to write the same program in c:
//https://en.cppreference.com/w/c/io //IMPORTANT
#include <stdio.h>
//https://en.cppreference.com/w/c/io/fscanf
int main()
{

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  More I/O\n");
    printf("══════════════════════════════════════\n\n");
    // there are MANY variant of scanf and printf
    // scanf() and printf() are the most basic ones
    //basic scanf:
    printf("\n");
    // --- Section 1: Basic scanf ---
    printf("--- Section 1: Basic scanf (reading from keyboard) ---\n\n");
    int number;
    printf("  Enter a number: ");
    fflush(stdout);
    scanf("%d", &number);
    printf("  You entered: %d\n\n", number);

    // --- Section 2: sscanf (parsing from a string) ---
    printf("--- Section 2: sscanf (reading from a string) ---\n\n");
    //its very helpful, when you have a string and you need to
    // extract some data from it
    char data[] = "123 456";
    int a, b;
    // (parameters: string, format, variables)
    sscanf(data, "%d %d", &a, &b);
    printf("  Input string: \"%s\"\n", data);
    printf("  sscanf(data, \"%%d %%d\", &a, &b)\n");
    printf("  Result: a = %d, b = %d\n\n", a, b);

    // --- Section 3: snprintf (safe formatted printing to a string) ---
    printf("--- Section 3: snprintf (print to string, not screen) ---\n\n");
    // another usefull in my opinion is snprintf
    // which instead of printing to std output, it prints to a string
    // which buffer overflow protection

    char buffer[10]; // Small buffer to demonstrate overflow protection
    int length = snprintf(buffer, sizeof(buffer), "Hello, %s!", "World");
    printf("  Buffer size: %zu bytes\n", sizeof(buffer));
    printf("  snprintf(buffer, %zu, \"Hello, %%s!\", \"World\")\n", sizeof(buffer));
    printf("  Result:  \"%s\"\n", buffer);
    printf("  Wanted length: %d  (truncated because buffer is only %zu bytes)\n\n", length, sizeof(buffer));

    return 0;
}
$ gcc -o more_io 02-more-basic-input-output.c
$ ./more_io
Expected Outputclick Run to execute live
══════════════════════════════════════
  More I/O
══════════════════════════════════════


--- Section 1: Basic scanf (reading from keyboard) ---

  Enter a number: 7
  You entered: 7

--- Section 2: sscanf (reading from a string) ---

  Input string: "123 456"
  sscanf(data, "%d %d", &a, &b)
  Result: a = 123, b = 456

--- Section 3: snprintf (print to string, not screen) ---

  Buffer size: 10 bytes
  snprintf(buffer, 10, "Hello, %s!", "World")
  Result:  "Hello, Wo"
  Wanted length: 13  (truncated because buffer is only 10 bytes)
Asks for input — sample input is one click away
9

String Reading with fgets

Safe string input using fgets instead of the dangerous gets function, with buffer size handling.

03-more-basic-input-output.c
/*
 * 03-more-basic-input-output.c — Safe string input with fgets instead of gets
 *
 * Key concepts: fgets, buffer overflow protection, gets vs fgets
 * Compile: gcc -o prog 03-more-basic-input-output.c
 * Run:     ./prog
 */


// to write the same program in c:
//https://en.cppreference.com/w/c/io //IMPORTANT
#include <stdio.h>

int main()
{

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Safe string input with fgets instead of gets\n");
    printf("══════════════════════════════════════\n\n");

    printf("\n");
    // --- Section 1: gets vs fgets ---
    printf("--- Section 1: gets() vs fgets() ---\n\n");

    // 1. gets = not recommended, not safe
    // it keeps reading chars regardless of buffer size until \n or \0
    char buffer[100];
    printf("  [gets] Enter a string (WARNING: gets has no size limit!): ");
    fflush(stdout);
    gets(buffer);  // Unsafe usage
    printf("  [gets] You entered: \"%s\"\n", buffer);
    printf("  NOTE: gets() can overflow the buffer — NEVER use in real code!\n\n");

    // fgets is the safe alternative
    char buffer_2[100];
    printf("  [fgets] Enter a string (safe — limited to buffer size): ");
    fflush(stdout);
    fgets(buffer_2, sizeof(buffer_2), stdin);  // Safe usage
    printf("  [fgets] You entered: \"%s\"", buffer_2);
    printf("  NOTE: fgets() includes the \\n in the result\n\n");

    // --- Section 2: Reading single characters ---
    printf("--- Section 2: Reading single characters ---\n\n");

    char ch;
    printf("  Enter a single character: ");
    fflush(stdout);
    scanf("%c", &ch);
    printf("  scanf(\"%%c\") read: '%c' (ASCII %d)\n", ch, ch);
    // Swallow the leftover newline from pressing Enter
    scanf("%c", &ch);

    char ch_2;
    printf("  Enter another character (using getchar): ");
    fflush(stdout);
    ch_2 = getchar();
    printf("  getchar() read: '%c' (ASCII %d)\n\n", ch_2, ch_2);

    // --- Section 3: printf string formatting ---
    printf("--- Section 3: printf string formatting ---\n\n");

    const char* s = "Hello";

    printf("  String: \"%s\"\n\n", s);
    printf("  %-15s | %s\n", "Format", "Output");
    printf("  --------------- | ------\n");
    printf("  %%s              | [%s]\n", s);
    printf("  %%10s  (right)   | [%10s]\n", s);
    printf("  %%-10s (left)    | [%-10s]\n", s);
    printf("  %%.3s  (3 chars) | [%.3s]\n", s);
    printf("  %%10.3s          | [%10.3s]\n", s);
    printf("  %%*s  (* = 10)   | [%*s]\n\n", 10, s);


}
$ gcc -std=gnu99 -o string_io 03-more-basic-input-output.c
$ ./string_io
Expected Outputclick Run to execute live
══════════════════════════════════════
  Safe string input with fgets instead of gets
══════════════════════════════════════


--- Section 1: gets() vs fgets() ---

  [gets] Enter a string (WARNING: gets has no size limit!): hello gets
hello fgets
A
B
  [gets] You entered: "hello gets"
  NOTE: gets() can overflow the buffer — NEVER use in real code!

  [fgets] Enter a string (safe — limited to buffer size):   [fgets] You entered: "hello fgets
"  NOTE: fgets() includes the \n in the result

--- Section 2: Reading single characters ---

  Enter a single character:   scanf("%c") read: 'A' (ASCII 65)
  Enter another character (using getchar):   getchar() read: 'B' (ASCII 66)

--- Section 3: printf string formatting ---

  String: "Hello"

  Format          | Output
  --------------- | ------
  %s              | [Hello]
  %10s  (right)   | [     Hello]
  %-10s (left)    | [Hello     ]
  %.3s  (3 chars) | [Hel]
  %10.3s          | [       Hel]
  %*s  (* = 10)   | [     Hello]
Asks for input — sample input is one click awaygets() was removed in C11 — compiled with -std=gnu99 so the unsafe version still builds (expect a warning)
10

File I/O Basics

File operations with fopen, fclose, fprintf, and fscanf — the C equivalent of C++ fstream.

04-basic-files-ptrs.c
$ gcc -o file_io 04-basic-files-ptrs.c
$ ./file_io
Expected Outputclick Run to execute live
--- Section 1: Writing to a file (mode "w") ---

  Wrote 2 lines to example.txt

--- Section 2: Reading from a file (mode "r") ---

  Contents of example.txt:
    > Hello, this is a test file.
    > Writing another line.

--- Section 3: Read+Write mode ("r+") with fseek ---

  Appended a line using fseek(SEEK_END)

  Reading WITHOUT seeking back to start:
    (nothing — file pointer is at the end!)

  Reading AFTER fseek(SEEK_SET) — back to start:
    > Hello, this is a test file.
    > Writing another line.
    > Appending a new line.
Asks for input
11

Structs with File I/O

Reading and writing struct data to files, combining struct definitions with file operations.

05-more-files-struct.c
$ gcc -o files_struct 05-more-files-struct.c
$ ./files_struct
Expected Outputclick Run to execute live
══════════════════════════════════════
  Reading/writing structs to files
══════════════════════════════════════


--- Wrote 3 employees to employees.txt ---

--- Read them back: ---

  ID   | Name       | Salary
  ---- | ---------- | ----------
  1    | Alice      | $55000.00
  2    | Bob        | $60000.00
  3    | Charlie    | $50000.00
Asks for input
12

Complex Format Specifiers

Advanced printf/scanf formatting: width, precision, padding, and field alignment.

06-complex-usage-scanf-printf.c
/*
 * 06-complex-usage-scanf-printf.c — Advanced scanf/printf formatting — width, precision, flags
 *
 * Key concepts: format specifiers, width modifiers, precision
 * Compile: gcc -o prog 06-complex-usage-scanf-printf.c
 * Run:     ./prog
 */


// to write the same program in c:
// https://en.cppreference.com/w/c/io //IMPORTANT
#include <stdio.h>

int main()
{

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Advanced scanf/printf formatting\n");
    printf("══════════════════════════════════════\n\n");

    printf("\n");
    // --- Section 1: Multi-type scanf ---
    printf("--- Section 1: Reading multiple types at once ---\n\n");
    int integer;
    float realNumber;
    char character;
    char string[100];

    printf("  Enter: integer float char string (e.g., 42 3.14 A hello): ");
    fflush(stdout);
    scanf("%d %f %c %s", &integer, &realNumber, &character, string);

    printf("\n  %-12s | %s\n", "Type", "Value");
    printf("  ------------ | -----\n");
    printf("  %%d (int)     | %d\n", integer);
    printf("  %%f (float)   | %.2f\n", realNumber);
    printf("  %%c (char)    | '%c'\n", character);
    printf("  %%s (string)  | \"%s\"\n\n", string);

    // --- Section 2: Precision and width ---
    printf("--- Section 2: Precision and width formatting ---\n\n");
    double pi = 3.141592653589793;
    int number = 50;

    printf("  Pi with different precision:\n");
    printf("    %%.2f  -> %.2f\n", pi);
    printf("    %%.5f  -> %.5f\n", pi);
    printf("    %%.10f -> %.10f\n\n", pi);

    printf("  Width formatting (| shows boundaries):\n");
    printf("    %%10d  (right-aligned) -> |%10d|\n", number);
    printf("    %%-10d (left-aligned)  -> |%-10d|\n\n", number);

    // --- Section 3: Parsing a date string ---
    printf("--- Section 3: Parsing a formatted string ---\n\n");
    char line[256];
    int day, year;
    char month[20];
    fgetc(stdin); // Consume leftover newline from previous scanf

    printf("  Enter a date (e.g., January 1, 2020): ");
    fflush(stdout);
    fgets(line, sizeof(line), stdin);
    sscanf(line, "%s %d, %d", month, &day, &year);

    printf("\n  Parsed result:\n");
    printf("    Month: %s\n", month);
    printf("    Day:   %d\n", day);
    printf("    Year:  %d\n", year);
    if (year == 0) printf("    NOTE: Year is 0 — did you forget the comma?\n");

    printf("\n========================================\n");
    printf("  End of demo\n");
}
$ gcc -o complex_fmt 06-complex-usage-scanf-printf.c
$ ./complex_fmt
Expected Outputclick Run to execute live
══════════════════════════════════════
  Advanced scanf/printf formatting
══════════════════════════════════════


--- Section 1: Reading multiple types at once ---

  Enter: integer float char string (e.g., 42 3.14 A hello): 42 3.14 A hello
March 5, 2024

  Type         | Value
  ------------ | -----
  %d (int)     | 42
  %f (float)   | 3.14
  %c (char)    | 'A'
  %s (string)  | "hello"

--- Section 2: Precision and width formatting ---

  Pi with different precision:
    %.2f  -> 3.14
    %.5f  -> 3.14159
    %.10f -> 3.1415926536

  Width formatting (| shows boundaries):
    %10d  (right-aligned) -> |        50|
    %-10d (left-aligned)  -> |50        |

--- Section 3: Parsing a formatted string ---

  Enter a date (e.g., January 1, 2020): 
  Parsed result:
    Month: March
    Day:   5
    Year:  2024

========================================
  End of demo
Asks for input — sample input is one click away
13

More Complex Formatting

Parsing mixed-type input with sscanf, handling whitespace in format strings, and using scansets to extract substrings.

07-another-complex.c
/*
 * 07-another-complex.c — More complex scanf/printf patterns
 *
 * Key concepts: format strings, type modifiers
 * Compile: gcc -o prog 07-another-complex.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  More complex scanf/printf patterns\n");
    printf("══════════════════════════════════════\n\n");
    char *line = NULL;   // Pointer to the buffer allocated by getline
    size_t len = 0;      // Size of the allocated buffer
    size_t read;        // Number of characters read by getline
    int *grades = NULL;  // Array to store grades
    int numGrades = 0;   // Number of grades read
    char name[100];      // String to store the name

    printf("\n");
    printf("  Example: 90 85 72 John Smith\n\n");
    printf("  > ");
    fflush(stdout);
    read = getline(&line, &len, stdin); // Read the line
    if (read == -1) {
        printf("Failed to read input\n");
        return 1; // Exit if input reading fails
    }

    // Tokenize the input to separate grades from the name
    char *token = strtok(line, " \n");
    while (token != NULL) {
        int grade;
        if (sscanf(token, "%d", &grade) == 1) {
            // Reallocate grades array to hold new grade
            int *newGrades = realloc(grades, (numGrades + 1) * sizeof(int));
            if (newGrades == NULL) {
                printf("Failed to allocate memory for grades\n");
                free(grades);
                free(line);
                return 1;
            }
            grades = newGrades;
            grades[numGrades++] = grade;
        } else {
            // Assume the token is part of the name
            strcpy(name, token);
            // Collect the remaining part of the name
            while ((token = strtok(NULL, "\n")) != NULL) {
                strcat(name, " ");
                strcat(name, token);
            }
            break;
        }
        token = strtok(NULL, " \n");
    }

    // Output the results
    printf("\n  --- Parsed Result ---\n\n");
    printf("  Name:   %s\n", name);
    printf("  Grades: ");
    for (int i = 0; i < numGrades; i++) {
        printf("%d%s", grades[i], (i < numGrades - 1) ? ", " : "");
    }
    printf("  (%d total)\n\n", numGrades);
    // Clean up
    free(grades);
    free(line);

    return 0;

}
$ gcc -o another_complex 07-another-complex.c
$ ./another_complex
Expected Outputclick Run to execute live
══════════════════════════════════════
  More complex scanf/printf patterns
══════════════════════════════════════


  Example: 90 85 72 John Smith

  > 90 85 72 John Smith

  --- Parsed Result ---

  Name:   John Smith
  Grades: 90, 85, 72  (3 total)
Asks for input — sample input is one click away
14

Functions with Pointers

Passing pointers to functions for output parameters — the C pattern for returning multiple values.

08-dont-forget-functions.c
$ gcc -o functions 08-dont-forget-functions.c
$ ./functions
Expected Outputclick Run to execute live
══════════════════════════════════════
  Functions with pointer parameters in C
══════════════════════════════════════


  separate functions using pointer params.

  Enter grades followed by a name
  Example: 90 85 72 John Smith

  > 90 85 72 John Smith

  --- Parsed Result ---

  Name:   John Smith
  Grades: 90, 85, 72  (3 total)
Asks for input — sample input is one click away
15

Advanced Patterns

A multi-struct program that reads structured records from files using fopen/fscanf and processes them with pointer-based functions.

09-last-example.c
/*
 * 09-last-example.c — Advanced pointer patterns and string manipulation
 *
 * Key concepts: pointers, strings, arrays
 * Compile: gcc -o prog 09-last-example.c
 * Run:     ./prog
 */

#include <stdio.h>
#include <stdlib.h>

void initializeData(int **data, int rows, int cols);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Advanced pointer patterns and string manipulation\n");
    printf("══════════════════════════════════════\n\n");
    
    printf("\n");
    int rows = 3, cols = 4;
    printf("  Allocating %dx%d matrix with malloc...\n\n", rows, cols);
    int **data = malloc(rows * sizeof(int*));
    initializeData(data, rows, cols);

    printf("  Values (data[i][j] = i * %d + j):\n\n", cols);
    printf("       ");
    for (int j = 0; j < cols; j++) printf("col%-2d ", j);
    printf("\n       ");
    for (int j = 0; j < cols; j++) printf("----- ");
    printf("\n");
    for (int i = 0; i < rows; i++) {
        printf("  row%d |", i);
        for (int j = 0; j < cols; j++) {
            printf(" %3d  ", data[i][j]);
        }
        printf("\n");
    }
    printf("\n========================================\n");

    // Free the allocated memory
    for (int i = 0; i < rows; i++) {
        free(data[i]);
    }
    free(data);

    return 0;
}


void initializeData(int **data, int rows, int cols) {
    // Allocate memory for the array of row pointers
    
    if (data == NULL) {
        perror("Failed to allocate memory for row pointers");
        exit(EXIT_FAILURE);
    }

    // Allocate memory for each row and initialize values
    for (int i = 0; i < rows; i++) {
        (data)[i] = malloc(cols * sizeof(int));
        if ((data)[i] == NULL) {
            perror("Failed to allocate memory for rows");
            exit(EXIT_FAILURE);
        }
        for (int j = 0; j < cols; j++) {
            (data)[i][j] = i * cols + j;  // Example data
        }
    }
}
$ gcc -o last_example 09-last-example.c
$ ./last_example
Expected Outputclick Run to execute live
══════════════════════════════════════
  Advanced pointer patterns and string manipulation
══════════════════════════════════════


  Allocating 3x4 matrix with malloc...

  Values (data[i][j] = i * 4 + j):

       col0  col1  col2  col3  
       ----- ----- ----- ----- 
  row0 |   0     1     2     3  
  row1 |   4     5     6     7  
  row2 |   8     9    10    11  

========================================
16

2D Dynamic Allocation

Dynamically allocating a 2D array using pointer-to-pointer, with proper malloc/free patterns.

10-last-last-example.c
/*
 * 10-last-last-example.c — 2D dynamic allocation in C (malloc/free)
 *
 * Key concepts: malloc, free, 2D arrays, pointer-to-pointer
 * Compile: gcc -o prog 10-last-last-example.c
 * Run:     ./prog
 */

#include <stdio.h>
#include <stdlib.h>

void initializeData(int ***data, int rows, int cols);

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  2D dynamic allocation in C (malloc/free)\n");
    printf("══════════════════════════════════════\n\n");
    
    printf("\n");
    printf("  receives int*** so it can allocate\n");
    printf("  the array itself (modify caller's pointer).\n\n");

    int rows = 3, cols = 4;
    int ** data;
    printf("  Calling initializeData(&data, %d, %d)...\n\n", rows, cols);
    initializeData(&data, rows, cols);

    printf("  Values (data[i][j] = i * %d + j):\n\n", cols);
    printf("       ");
    for (int j = 0; j < cols; j++) printf("col%-2d ", j);
    printf("\n       ");
    for (int j = 0; j < cols; j++) printf("----- ");
    printf("\n");
    for (int i = 0; i < rows; i++) {
        printf("  row%d |", i);
        for (int j = 0; j < cols; j++) {
            printf(" %3d  ", data[i][j]);
        }
        printf("\n");
    }
    printf("\n========================================\n");

    // Free the allocated memory
    for (int i = 0; i < rows; i++) {
        free(data[i]);
    }
    free(data);

    return 0;
}


void initializeData(int ***data, int rows, int cols) {
    // Allocate memory for the array of row pointers
    
    *data = malloc(rows*sizeof(int*));

    if (data == NULL) {
        perror("Failed to allocate memory for row pointers");
        exit(EXIT_FAILURE);
    }

    // Allocate memory for each row and initialize values
    for (int i = 0; i < rows; i++) {
        (*data)[i] = malloc(cols * sizeof(int));
        if ((*data)[i] == NULL) {
            perror("Failed to allocate memory for rows");
            exit(EXIT_FAILURE);
        }
        for (int j = 0; j < cols; j++) {
            (*data)[i][j] = i * cols + j;  // Example data
        }
    }
}
$ gcc -o last_last 10-last-last-example.c
$ ./last_last
Expected Outputclick Run to execute live
══════════════════════════════════════
  2D dynamic allocation in C (malloc/free)
══════════════════════════════════════


  receives int*** so it can allocate
  the array itself (modify caller's pointer).

  Calling initializeData(&data, 3, 4)...

  Values (data[i][j] = i * 4 + j):

       col0  col1  col2  col3  
       ----- ----- ----- ----- 
  row0 |   0     1     2     3  
  row1 |   4     5     6     7  
  row2 |   8     9    10    11  

========================================

Open Full Terminal

Get a Linux terminal with all 16 files from this lesson pre-loaded. Compile, run, and experiment freely.