C Program to find Binomial Coefficients

C Program to find Binomial Integers without using recursion.

Binomial coefficients are positive integers that are coefficient of any term in the expansion of (x + a) the number of combination’s of a specified size that can be drawn from a given set.

There are many ways to compute the Binomial coefficients. Like,

In this post we will be using a non-recursive, multiplicative formula.

The program is given below:

// C program to find the Binomial coefficient. Downloaded from www.c-program-example.com 
#include<stdio.h> 
void main() {
    int i, j, n, k, min, c[20][20]={0};
    printf("This program is brought to you by www.c-program-example.com\n" );     
    printf("\n Enter the value of n: ");     
    scanf("%d", &n);     
    printf("\n Enter the value of k: ");     
    scanf("%d", &k);
    if(n >= k) {         
        for(i=0; i<=n; i++) {             
            min = i<k? i:k;
            for(j = 0; j <= min; j++) {
                 if(j==0 || j == i) {
                     c[i][j] = 1;
                 } else {
                     c[i][j] = c[i-1][j-1] + c[i-1][j];
                 }
             }
         }
         printf("%d\t",c[n][k]);
         printf("\n");
     } else {
         printf("\n Invalid input \n Enter value n>=k \n");
     }
}

Sample output

Links

Code::Blocks IDE — Install and Write Your First C Program (2026)

Code::Blocks is a free, standalone C and C++ IDE that is perfect for beginners — because the recommended installer comes with a compiler built in. Unlike VS Code, you do not need to install GCC separately or configure anything: download one file, install it, and you are writing and running C programs in minutes.

This guide covers downloading, installing, and writing your first C program in Code::Blocks on Windows.

Why Choose Code::Blocks?

Code::Blocks is the easiest way to start C programming on Windows because the mingw-setup version bundles MinGW (the GCC compiler) with the editor. Everything works out of the box:

  • No separate compiler setup — GCC is included and pre-configured
  • One-click build and run — compile and execute with a single button
  • Lightweight — runs well even on older or low-spec machines
  • Free and open source — no accounts, no cost

If you would rather use a more modern, extensible editor (and do not mind installing the compiler yourself), see our VS Code for C programming guide instead. And if you just want to test a quick program with nothing to install, try an online C compiler.

Step 1 — Download Code::Blocks (with the Compiler)

Go to the official site codeblocks.org/downloads/binaries. Under the Windows section, download the file whose name ends in mingw-setup — currently:

codeblocks-25.03mingw-setup.exe

This is the important step. There are two installers — one with mingw in the name and one without. The mingw-setup version includes the GCC compiler. If you download the plain version by mistake, Code::Blocks will install but have no compiler, and you will not be able to build programs.

Step 2 — Install Code::Blocks

  1. Run the downloaded .exe
  2. Click through Next and accept the licence
  3. Leave the default components selected (this includes the MinGW compiler) and finish the install
  4. Launch Code::Blocks

On first launch, Code::Blocks detects the bundled GNU GCC compiler and selects it automatically. If it asks, choose GNU GCC Compiler and set it as default.

Step 3 — Create Your First Project

You can compile a single file, but the cleanest way to work is with a project:

  1. Go to File → New → Project…
  2. Select Console application and click Go
  3. Choose C (not C++) and click Next
  4. Give the project a title and choose a folder to save it in
  5. Leave the compiler as GNU GCC Compiler and click Finish

Code::Blocks creates a project with a ready-made main.c containing a Hello World program.

Step 4 — Write Your Program

Open main.c from the left-hand project panel and replace its contents with:

#include <stdio.h>

int main(void) {
    printf("Hello from Code::Blocks!\n");
    return 0;
}

Step 5 — Build and Run

Press F9 (Build and Run), or click the Build and Run button (the gear-and-play icon) in the toolbar. Code::Blocks compiles your program and opens a console window showing:

Hello from Code::Blocks!

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.

The “Press any key to continue” line is Code::Blocks keeping the console open so you can read the output — a small but helpful touch for beginners.

Useful Code::Blocks Shortcuts

Key Action
F9 Build and run
Ctrl+F9 Build only (compile without running)
Ctrl+F10 Run the last built program
F8 Start the debugger
F7 Compile the current file

Using the Debugger

Code::Blocks includes the GDB debugger. Click in the margin to the left of a line number to set a breakpoint (a red dot), then press F8. Execution pauses at the breakpoint, and you can open Debug → Debugging windows → Watches to inspect variable values as you step through with F7. This is one of the best ways to understand how loops, arrays, and pointers actually behave.

Common Issues

Problem Fix
“No compiler found” or cannot build You installed the version without MinGW — reinstall using the mingw-setup installer
Compiler not auto-detected Go to Settings → Compiler → Toolchain executables and confirm the path points to the bundled MinGW folder
Console window flashes and closes instantly Run with F9 (Build and Run) — Code::Blocks adds the “Press any key” pause automatically
Want to compile just one file without a project Open the .c file and press F9; choose to build it directly when prompted

Code::Blocks vs VS Code — Which Should You Use?

Code::Blocks VS Code
Compiler included Yes (mingw-setup) No — install GCC separately
Setup effort Minimal — works out of the box Moderate — extension + config
Best for Beginners, quick start, low-spec PCs Modern features, extensions, long-term use
Languages C / C++ focused Everything (with extensions)

Start with Code::Blocks if you want to begin coding immediately with zero configuration. Move to VS Code later if you want a more modern, extensible setup. For a full comparison of every option, see Best Free C IDEs for Beginners.

What’s Next

Your IDE is ready. Time to write real programs — browse our full list of C programs with examples, and try setting a breakpoint inside a sorting program to watch the array change step by step.


As an Amazon Associate we earn from qualifying purchases.

Recommended Book

With your IDE set up, the best book to learn C properly is The C Programming Language by Kernighan and Ritchie (K&R). For more options across every level, see our guide to the best C programming books.

Best Online C Compilers in 2026 (No Installation Needed)

Sometimes you just need to run a C program without installing anything — maybe you are on a school computer, a Chromebook, a borrowed laptop, or you only have one or two programs to test. Online C compilers let you write, compile, and run C code right in your browser, with nothing to download.

This guide covers the best online C compilers in 2026, what each is good at, and which to choose for your situation. All of them are free.

Quick Pick

If you want… Use
A debugger (breakpoints, step through code) OnlineGDB
The simplest beginner-friendly interface Programiz
Saved projects and collaboration Replit
Many languages and code sharing JDoodle
To see the assembly your code compiles to Compiler Explorer

1. OnlineGDB — Best for Debugging

OnlineGDB is the most capable free online C environment. It uses real gcc to compile and gdb to debug — so unlike most browser compilers, you can set breakpoints, step through your code line by line, and inspect variable values as the program runs. For learning how pointers and loops actually behave, this is invaluable.

  • Pros: full debugger, supports standard input, saves code with an account
  • Cons: interface is a little busy for first-timers
  • Best for: debugging and understanding how your code executes

2. Programiz — Best for Beginners

The Programiz Online C Compiler has the cleanest, simplest interface of the lot. There is nothing to configure — type your code, click Run, see the output. Programiz also publishes excellent beginner C tutorials, so you can read and practise in the same place.

  • Pros: dead simple, fast, great for quick tests
  • Cons: no debugger
  • Best for: absolute beginners testing small programs

3. Replit — Best for Projects and Collaboration

Replit is a full online IDE that supports C and 50+ other languages. You can save projects, work across multiple files, share a live link, and even collaborate in real time like a Google Doc for code. It is more than a quick compiler — it is a place to build and keep your work.

  • Pros: multi-file projects, saved work, real-time collaboration
  • Cons: heavier than a simple compiler; free tier has limits
  • Best for: larger programs, group work, keeping a portfolio

4. JDoodle — Best for Sharing and Many Languages

JDoodle supports over 70 languages and makes it easy to share a snippet via a link. It has syntax highlighting, code completion, and accepts standard input. A solid all-rounder when you bounce between languages.

  • Pros: many languages, easy sharing, clean layout
  • Cons: no full debugger
  • Best for: sharing code and quick multi-language testing

5. Compiler Explorer — Best for Seeing the Assembly

Compiler Explorer (also called Godbolt) is a specialist tool. As you type C, it shows the exact assembly your code compiles to, side by side, across many compiler versions and optimisation levels. It is not for running programs so much as understanding what the compiler does with your code — fascinating once you are past the basics.

  • Pros: shows generated assembly, many compilers and flags
  • Cons: not meant for normal input/output programs
  • Best for: intermediate learners curious about compilation and optimisation

Limitations of Online Compilers

Online compilers are perfect for learning and quick tests, but they have limits you will eventually hit:

  • No local files — file I/O programs that read or write files on your disk will not work normally
  • Time and memory limits — long-running or heavy programs may be cut off
  • No external libraries — you generally cannot install third-party C libraries
  • Internet required — no connection, no compiler

For anything beyond practice — real projects, file handling, or using libraries — you will want a proper local setup.

Ready for a Proper Local Setup?

Once you are writing programs regularly, installing a compiler on your own machine is faster and has none of the limits above. It takes only a few minutes:

Prefer a full editor with code completion and one-click run? See our VS Code for C programming setup guide. For a comparison of full IDEs, see Best Free C IDEs for Beginners.

What’s Next

Whichever compiler you choose, the only way to learn C is to write code. Pick a program from our full list of C programs with examples, paste it into any compiler above, and run it. Then try changing it and see what happens — that is where real learning starts.


As an Amazon Associate we earn from qualifying purchases.

Recommended Book

Online compilers are great for practice, but a good book teaches you the language properly. For beginners we recommend C Programming: A Modern Approach by K. N. King — see our full list of the best C programming books for more picks.

Best C Programming Books for Beginners in 2026

Choosing the right book makes learning C far easier. This guide covers the best C programming books in 2026 — from absolute-beginner introductions to the definitive references serious programmers keep on their desk. Each recommendation explains who it is for, so you can pick the one that fits where you are right now.

Already have your compiler set up? Jump straight to writing code with our list of C programs with examples. If not, start with our guides on installing GCC for Windows or macOS — then pick a book below to learn the language properly.

This post contains affiliate links. If you buy through them, we may earn a small commission at no extra cost to you. It helps keep this site running — thank you.

Quick Pick — Which Book Should You Buy?

If you are… Buy this
A complete beginner who has never coded Head First C, or C Programming Absolute Beginner’s Guide
An Indian student / exam preparation Let Us C, or Programming in ANSI C
Someone who wants the best single modern textbook C Programming: A Modern Approach
A programmer who wants the definitive reference The C Programming Language (K&R)
Already know C, want to go deeper Expert C Programming: Deep C Secrets

Best Books for Absolute Beginners

1. Head First C — David and Dawn Griffiths

If you learn best with visuals, puzzles, and a conversational tone, Head First C is the friendliest way into the language. It uses the well-known Head First style — diagrams, exercises, and brain-teasers — to make concepts like pointers and memory stick. Best for people who find traditional textbooks dry or intimidating.

Best for: visual learners and first-time programmers.

2. C Programming Absolute Beginner’s Guide — Greg Perry and Dean Miller

C Programming Absolute Beginner’s Guide assumes zero prior programming experience. It moves in small, clear steps through variables, operators, input/output, functions, and pointers. If “Hello, World” is brand new to you, start here.

Best for: readers with no coding background at all.

Best Books for Students (Especially in India)

3. Let Us C — Yashavant Kanetkar

Let Us C is the best-selling C programming book in India and a fixture in engineering colleges for good reason. It explains concepts in plain language with plenty of worked examples, and the latest edition is updated for modern compilers and exam syllabi. If you are an Indian student learning C for your course, this is the book your seniors recommend.

Best for: Indian university students and self-learners who want simple explanations with lots of examples.

4. Programming in ANSI C — E. Balagurusamy

Programming in ANSI C is the other staple of Indian university courses. It maps closely to standard C syllabi, with review questions and programming exercises at the end of each chapter — ideal for exam preparation. Many students own both this and Let Us C.

Best for: students following a university C syllabus and preparing for exams.

Best Comprehensive Textbook

5. C Programming: A Modern Approach — K. N. King

Widely regarded as the best single book to learn C thoroughly, C Programming: A Modern Approach (2nd edition) is clear, complete, and genuinely modern — covering C89 and C99 with excellent explanations and a wealth of exercises. If you only buy one book to truly understand C, this is the one most experienced programmers recommend.

Best for: anyone who wants one book that takes them from beginner to confident.

The Definitive Reference

6. The C Programming Language — Brian Kernighan and Dennis Ritchie (K&R)

Written by the creators of C, The C Programming Language has been in print since 1988 and remains the definitive reference. It is concise and precise — every word counts. It is not the gentlest first book, but every serious C programmer eventually owns a copy. The famous exercises are still some of the best practice you can do.

Best for: programmers who already grasp the basics and want the authoritative, no-fluff reference.

All-in-One Reference

7. C: The Complete Reference — Herbert Schildt

C: The Complete Reference is a popular, comprehensive desk reference covering the language and the standard library in depth. It works well as a lookup companion alongside a tutorial-style book rather than as your very first read.

Best for: readers who want a thick all-in-one reference to keep nearby.

For Going Deeper

8. Expert C Programming: Deep C Secrets — Peter van der Linden

Once you are comfortable with C, Expert C Programming: Deep C Secrets teaches what the textbooks skip — how the compiler and linker really work, why declarations read the way they do, and the subtle traps that catch even experienced programmers. Witty, deep, and genuinely eye-opening.

Best for: intermediate programmers who want to truly master the language.

At a Glance — Comparison

Book Level Style
Head First C Beginner Visual, interactive
C Programming Absolute Beginner’s Guide Beginner Step-by-step, gentle
Let Us C Beginner → Intermediate Example-driven, exam-friendly
Programming in ANSI C Beginner → Intermediate University syllabus, exercises
C Programming: A Modern Approach Beginner → Advanced Thorough textbook
The C Programming Language (K&R) Intermediate Concise reference
C: The Complete Reference All levels Lookup reference
Expert C Programming Advanced Deep dive

How to Get the Most From Any C Book

Reading alone will not teach you C — you have to write code. As you work through any book above, type the examples into your own editor and run them. Set up your environment first with our guides for Windows or macOS, then practise with our worked examples:

The fastest way to learn is to read a chapter, then immediately implement what you learned. The algorithms K&R and the others teach come to life when you run them yourself and step through with a debugger.

VS Code for C Programming — Complete 2026 Setup Guide

Visual Studio Code (VS Code) is the most popular free editor for C programming in 2026. It gives you syntax highlighting, code completion (IntelliSense), one-click compile-and-run, and a visual debugger — all free and cross-platform. This guide sets it up for C from scratch on Windows, macOS, or Linux.

One thing to know up front: VS Code is not a compiler. It is an editor that drives a compiler you install separately (GCC). If you have not installed GCC yet, do that first:

If you just need to test a quick snippet, an online C compiler is faster than a full IDE setup. But for any real project, VS Code is worth the few minutes of configuration below.

Step 1 — Install VS Code

Download VS Code from the official site code.visualstudio.com and install it. It is free and open source, and runs on Windows, macOS, and Linux.

On Windows, during installation tick Add to PATH and Add “Open with Code” action — both make life easier later.

Step 2 — Verify GCC Is Installed

Open VS Code, then open its built-in terminal with Ctrl+` (backtick) — on macOS use Cmd+`. Type:

gcc --version

If you see a version number, you are ready. If you see command not found or not recognized, GCC is not on your PATH — go back to the install guide for your platform above.

Step 3 — Install the C/C++ Extension

  1. Click the Extensions icon in the left sidebar (or press Ctrl+Shift+X)
  2. Search for C/C++
  3. Install the one published by Microsoft (it has tens of millions of installs)

This extension adds IntelliSense (code completion), error squiggles, go-to-definition, and debugging support. Optionally, also install the C/C++ Extension Pack for a few extra tools, but the single C/C++ extension is enough to start.

Step 4 — Open a Folder and Create a File

VS Code works best when you open a folder, not a single file. Create a folder for your code (for example C:\code or ~/code), then in VS Code choose File → Open Folder and select it.

Create a new file called hello.c and type:

#include <stdio.h>

int main(void) {
    printf("Hello from VS Code!\n");
    return 0;
}

As you type, notice IntelliSense suggesting printf and showing its parameters — that is the C/C++ extension working.

Step 5 — Compile and Run with One Click

The simplest way to run your program:

  1. Open hello.c
  2. Click the Run triangle (▷) in the top-right corner, or press F5 / Ctrl+F5
  3. When prompted, choose C/C++: gcc build and debug active file

VS Code compiles your file with GCC and runs it in the integrated terminal. The output appears at the bottom:

Hello from VS Code!

VS Code automatically creates a .vscode folder with tasks.json (build settings) and launch.json (debug settings) the first time. You normally never need to touch these.

Step 6 — Use the Debugger

This is where VS Code beats the command line. Click in the gutter to the left of any line number to set a breakpoint (a red dot), then press F5. Execution pauses at that line and you can:

  • Inspect variable values in the left panel
  • Step through code line by line with F10 (step over) and F11 (step into)
  • Watch how loops and pointers change in real time

For learning C — especially pointers and arrays — stepping through with a debugger teaches more than any printf ever will.

Recommended Settings for C Beginners

Open tasks.json (inside the .vscode folder) and add these flags to the args array so every build catches more bugs:

"-Wall",
"-Wextra",
"-std=c17",
"-g",
Flag Why
-Wall -Wextra Turn on warnings — they catch real bugs early
-std=c17 Use a modern, well-defined C standard
-g Add debug info so breakpoints work

VS Code vs a Standalone IDE

VS Code needs a little setup (install GCC, install the extension, first-run config). If you want something that works the instant you install it — compiler already bundled, no PATH configuration — a standalone IDE may suit you better as a complete beginner. See our guide to Code::Blocks, which includes its own compiler and runs out of the box.

For a broader comparison of every option, see Best Free C IDEs for Beginners in 2026.

Common Issues

Problem Fix
“gcc not found” when you press F5 GCC is not on PATH — verify with gcc --version in the terminal, reinstall if needed
IntelliSense red squiggles everywhere but it compiles fine Run C/C++: Select IntelliSense Configuration from the Command Palette and pick your compiler
No “gcc build and debug” option appears Make sure the C/C++ extension by Microsoft is installed and enabled
Program window closes instantly Run with Ctrl+F5 (Run Without Debugging) to keep the terminal open

What’s Next

Your environment is fully set up. Time to write real programs — browse our full list of C programs with examples, from beginner exercises to sorting algorithms and data structures. Set a breakpoint inside one of the sorting programs and watch the array change step by step — it is the fastest way to understand how they work.


As an Amazon Associate we earn from qualifying purchases.

Recommended Book

With VS Code set up, the best book to actually learn the language is The C Programming Language by Brian Kernighan and Dennis Ritchie (K&R). Type its examples into VS Code and step through them with the debugger to see exactly how each one works.

How to Run a C Program on Windows 11 — Compile and Execute in Command Prompt

This guide shows you how to compile and run a C program on Windows 11 using GCC from the Command Prompt. If you have already installed a compiler, you are ready to go. If not, start with our guide on how to install GCC on Windows 11 first — it walks you through MSYS2 and MinGW-w64.

Just need to run one or two quick programs without installing anything? You can compile C in your browser instead — see our guide to online C compilers. No setup required.

The Two-Step Workflow

Running a C program on Windows is always two steps:

  1. Compile — turn your .c source file into an .exe executable
  2. Run — execute that .exe

C is a compiled language — you cannot run a .c file directly the way you would a Python script. GCC translates your source code into a Windows executable first.

Step 1 — Write Your C Program

Open Notepad (or any text editor) and type this program:

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}

Save it as hello.c. Important: in Notepad’s Save dialog, set Save as type to All Files — otherwise Notepad saves it as hello.c.txt, which will not compile. Save it somewhere easy to find, such as C:\code\.

Step 2 — Open Command Prompt in the Right Folder

The quickest way: open the folder containing hello.c in File Explorer, click the address bar, type cmd, and press Enter. A Command Prompt opens already pointed at that folder.

Alternatively, open Command Prompt from the Start menu and navigate with cd:

cd C:\code

Confirm your file is there with dir:

dir hello.c

Step 3 — Compile the Program

gcc hello.c -o hello.exe

Breaking this command down:

Part Meaning
gcc The MinGW-w64 GCC compiler
hello.c Your source file — the input
-o hello.exe Name the output executable hello.exe

If your code has no errors, the command finishes silently and creates hello.exe in the same folder. If you omit -o hello.exe, GCC names the output a.exe by default.

Step 4 — Run the Program

hello.exe

Output:

Hello, World!

On Windows you run the program by typing its name. (On macOS and Linux you need a ./ prefix — on Windows you do not, because the current directory is searched automatically.)

The Complete Sequence

cd C:\code
gcc hello.c -o hello.exe
hello.exe

Three commands every time: navigate, compile, run.

Recommended Compiler Flags

For learning C, always compile with warnings enabled — they catch real bugs early:

gcc -Wall -Wextra hello.c -o hello.exe
Flag What it does
-Wall Enable all common warnings
-Wextra Enable extra warnings -Wall misses
-std=c17 Use the C17 standard (or -std=c11, -std=c99)
-g Add debug info for use with gdb
-O2 Optimise the compiled program for speed

A good everyday command for students:

gcc -Wall -Wextra -std=c17 hello.c -o hello.exe

Compiling Multiple Source Files

As programs grow, you split them across files. Compile them together by listing each .c file:

gcc -Wall main.c utils.c math_helpers.c -o myprogram.exe
myprogram.exe

GCC combines all the source files into one executable. Header files (.h) are not listed — they are pulled in automatically by the #include directives in your code.

Reading Input While the Program Runs

If your program uses scanf(), just type the values when it runs:

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("You entered %d\n", n);
    return 0;
}
gcc -Wall input.c -o input.exe
input.exe
Enter a number: 42
You entered 42

Common Errors and Fixes

Error message Cause and fix
'gcc' is not recognized as an internal or external command GCC not installed or not on PATH — see our install guide
gcc: error: hello.c: No such file or directory Wrong folder — use cd to navigate to the file, check with dir
File saved as hello.c.txt Notepad added .txt — re-save with Save as type → All Files
undefined reference to 'function' You forgot to include a .c file in the compile command — list all of them
implicit declaration of function 'printf' You forgot #include <stdio.h> at the top

Tired of Typing Commands? Use an IDE

Running three commands for every change gets old fast. VS Code lets you compile and run with a single keypress and adds code completion plus a visual debugger. It is free and works directly with the MSYS2 GCC you installed.

What’s Next

You now know how to compile and run C on Windows 11. Time to practise — browse our full list of C programs with examples, from beginner exercises to sorting algorithms and data structures.


As an Amazon Associate we earn from qualifying purchases.

Recommended Book

Once you are comfortable compiling and running programs, the best book to actually learn the language is The C Programming Language by Brian Kernighan and Dennis Ritchie (K&R). Every example in it compiles and runs with the exact gcc workflow above.

How to Install GCC on Windows 11 — MSYS2 and MinGW-w64 Setup

This guide shows you how to install GCC on Windows 11 so you can compile and run C programs. Windows does not come with a C compiler, so we will install MinGW-w64 (the Windows port of GCC) using MSYS2 — the modern, actively maintained way to get GCC on Windows.

Not ready to install anything yet? You can write and run C programs directly in your browser — see our guide to online C compilers instead. No installation needed, ideal if you just have one or two programs to compile.

Why MSYS2 and Not the Old MinGW Installer?

If you have seen older tutorials pointing to “mingw-get” or a standalone MinGW installer, skip them. That project is no longer maintained and ships an ancient GCC version. MSYS2 gives you MinGW-w64 with a current GCC, security updates, and a simple package manager (pacman) to keep it up to date. This is what the GCC project itself recommends for Windows today.

Prerequisites

  • A PC running Windows 11 (these steps also work on Windows 10)
  • About 2 GB of free disk space
  • An internet connection

Step 1 — Download MSYS2

Go to the official site msys2.org and download the installer (a file named something like msys2-x86_64-XXXXXXXX.exe). Always download from the official site — never from a mirror or third party.

Step 2 — Run the Installer

  1. Run the downloaded .exe
  2. Accept the default install location (C:\msys64) — this keeps later commands simple
  3. Click through Next until installation finishes
  4. Leave Run MSYS2 now ticked and click Finish

A dark terminal window opens. This is the MSYS2 shell — you will run the next commands here.

Step 3 — Update MSYS2

Before installing GCC, update the package database. In the MSYS2 terminal, type:

pacman -Syu

When prompted, type Y and press Enter. The terminal may close itself at the end of the update — this is normal. Reopen it from the Start menu (search for MSYS2 MINGW64) and run the update once more to finish:

pacman -Su

Step 4 — Install the GCC Toolchain

Now install MinGW-w64 GCC and the essential build tools:

pacman -S mingw-w64-ucrt-x86_64-gcc

Press Enter to accept the default selection, then Y to confirm. This installs GCC, the C standard library, and supporting tools. The download is around a few hundred megabytes.

To also get gdb (the debugger) and make, install the full toolchain instead:

pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain

Step 5 — Add GCC to the Windows PATH

So you can run gcc from any terminal (Command Prompt, PowerShell, or VS Code) — not just the MSYS2 shell — add it to your PATH:

  1. Press Win and type environment variables
  2. Click Edit the system environment variables
  3. Click Environment Variables…
  4. Under System variables, select Path and click Edit
  5. Click New and add: C:\msys64\ucrt64\bin
  6. Click OK on all dialogs

Close and reopen any terminal windows for the change to take effect.

Step 6 — Verify the Installation

Open a regular Command Prompt or PowerShell (not the MSYS2 shell) and type:

gcc --version

You should see something like:

gcc.exe (Rev3, Built by MSYS2 project) 14.x.x
Copyright (C) 2024 Free Software Foundation, Inc.

If you see a version number, GCC is installed and on your PATH. If you get 'gcc' is not recognized, recheck Step 5 — the PATH entry must point to C:\msys64\ucrt64\bin.

Step 7 — Compile and Run Your First Program

Create a file called hello.c in any folder with this content:

#include <stdio.h>

int main(void) {
    printf("Hello from Windows 11!\n");
    return 0;
}

Open Command Prompt, navigate to that folder with cd, and run:

gcc hello.c -o hello.exe
hello.exe

Output:

Hello from Windows 11!

On Windows the executable ends in .exe, and you run it by typing its name (no ./ needed, unlike macOS and Linux).

Common Issues

Problem Fix
'gcc' is not recognized as an internal or external command PATH not set — recheck Step 5, then open a fresh terminal
'pacman' is not recognized You are in Command Prompt, not the MSYS2 shell — run pacman commands in the MSYS2 terminal
The MSYS2 terminal closed during update Normal during pacman -Syu — reopen and run pacman -Su
Antivirus blocks the download MSYS2 is safe — download only from msys2.org and allow it through
Old MinGW already on PATH Remove the old MinGW PATH entry so it does not shadow the new GCC

What’s Next

Now that GCC is installed, learn the full compile-and-run workflow — including warning flags and multiple source files — in our guide: How to Run a C Program on Windows 11.

Prefer a full IDE with code completion and one-click compiling instead of the command line? VS Code is the best free option and works seamlessly with the MSYS2 GCC you just installed.

Once your environment is ready, browse our full list of C programs with examples to start practising.


As an Amazon Associate we earn from qualifying purchases.

Recommended Book

The best book to learn C once your environment is set up — The C Programming Language by Brian Kernighan and Dennis Ritchie (K&R). Concise, precise, and still the definitive reference decades on.

How to Run a C Program on macOS Tahoe — Compile and Execute in Terminal

This guide shows you how to compile and run a C program on macOS Tahoe using the Terminal. If you have already installed a compiler, you are ready to go. If not, start with our guide on how to install GCC on macOS Tahoe first — it takes one command.

Just need to run one or two quick programs without setting anything up? You can compile C in your browser instead — see our guide to online C compilers. No installation required.

The Two-Step Workflow

Running a C program on macOS is always two steps:

  1. Compile — turn your .c source file into an executable program
  2. Run — execute that program

Unlike Python or JavaScript, C is a compiled language — you cannot run a .c file directly. The compiler (gcc, which is Apple’s Clang on macOS) translates your code into machine code first.

Step 1 — Write Your C Program

Open any text editor and create a file called hello.c. You can use the built-in nano editor right in the Terminal:

nano hello.c

Type this program:

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}

Save and exit nano with Ctrl+O, Enter, then Ctrl+X.

Step 2 — Navigate to Your File

Use cd to move into the folder where you saved hello.c. For example, if it is on your Desktop:

cd ~/Desktop

Confirm the file is there with ls:

ls hello.c

Step 3 — Compile the Program

gcc hello.c -o hello

Breaking this command down:

Part Meaning
gcc The compiler (Apple Clang on macOS)
hello.c Your source file — the input
-o hello Name the output executable hello

If your code has no errors, the command finishes silently and creates a new executable file named hello. If you omit -o hello, the compiler names the output a.out by default.

Step 4 — Run the Program

./hello

Output:

Hello, World!

The ./ prefix is required — it tells the shell to run the program from the current directory. Typing just hello will not work, because the current folder is not in your PATH by default.

The Complete Sequence

cd ~/Desktop
gcc hello.c -o hello
./hello

Three commands, every time: navigate, compile, run.

Recommended Compiler Flags

For learning C, always compile with warnings enabled. They catch real bugs before they bite:

gcc -Wall -Wextra hello.c -o hello
Flag What it does
-Wall Enable all common warnings
-Wextra Enable extra warnings -Wall misses
-std=c17 Use the C17 standard (or -std=c11, -std=c99)
-g Add debug info for use with a debugger
-O2 Optimise the compiled program for speed

A good everyday command for students:

gcc -Wall -Wextra -std=c17 hello.c -o hello

Compiling Multiple Source Files

As your programs grow, you will split them across files. Compile them together by listing each .c file:

gcc -Wall main.c utils.c math_helpers.c -o myprogram
./myprogram

The compiler combines all three source files into a single executable. Header files (.h) are not listed — they are pulled in automatically by the #include directives in your code.

Reading Input While the Program Runs

If your program uses scanf() to read input, just type the values when it runs:

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("You entered %d\n", n);
    return 0;
}
gcc -Wall input.c -o input
./input
Enter a number: 42
You entered 42

Common Errors and Fixes

Error message Cause and fix
gcc: command not found No compiler installed — see our install guide
hello.c: No such file or directory You are in the wrong folder — use cd to navigate to where the file is, check with ls
permission denied: ./hello Rare — fix with chmod +x hello then run again
undefined reference to 'function' You forgot to include a .c file in the compile command — list all of them
implicit declaration of function 'printf' You forgot #include <stdio.h> at the top

Tired of Typing Commands? Use an IDE

Running three commands for every change gets tedious. VS Code lets you compile and run with a single keypress, and adds code completion and a visual debugger. It is free and works great on Apple Silicon and Intel Macs.

If you prefer a faster, more modern Terminal experience, Warp Terminal adds autocomplete, command history search, and AI assistance — a nice upgrade for the compile-run-debug loop on macOS.

What’s Next

You now know how to compile and run C on macOS Tahoe. Time to practise — browse our full list of C programs with examples, from beginner exercises to sorting algorithms and data structures.


As an Amazon Associate we earn from qualifying purchases. The Warp Terminal link above is a referral link.

Recommended Book

Once you are comfortable compiling and running programs, the best book to actually learn the language is The C Programming Language by Brian Kernighan and Dennis Ritchie (K&R). Every example in it compiles and runs with the exact gcc workflow above.

How to Install GCC on macOS Tahoe — Xcode CLT and Homebrew

This guide shows you how to install GCC on macOS Tahoe so you can compile and run C programs from the Terminal. There are two methods — pick the one that suits you:

  • Method 1 — Xcode Command Line Tools (recommended for beginners): one command, installs Apple’s Clang compiler under the name gcc. No account needed.
  • Method 2 — Homebrew: installs actual GNU GCC alongside Clang. Better if you need the latest GCC version or are following a course that requires it specifically.

Not ready to install anything yet? You can write and run C programs directly in your browser — see our guide to online C compilers instead. No installation needed.

What You Are Actually Installing

On macOS, typing gcc in the Terminal runs Apple’s Clang compiler, not GNU GCC. Apple ships Clang under the gcc name because it is fully compatible for standard C programs. For learning C — and for everything on this site — Clang works perfectly. The only time you need actual GNU GCC is if a specific project or course requires it by name.

Prerequisites

  • A Mac running macOS Tahoe (these steps also work on Sequoia and Sonoma)
  • Terminal — open it from Applications → Utilities → Terminal, or press ⌘ Space and type Terminal
  • An internet connection for the download

Method 1 — Xcode Command Line Tools (Recommended)

This is the official Apple way. It installs Clang, Make, Git, and other developer tools in one shot.

Step 1 — Run the install command

Open Terminal and type:

xcode-select --install

A dialog box appears asking you to install the Command Line Developer Tools. Click Install, then Agree to the licence. The download is around 1–2 GB and takes a few minutes.

Step 2 — Verify the installation

gcc --version

You should see something like:

Apple clang version 17.0.0 (clang-1700.0.xx.x)
Target: arm64-apple-darwin26.0.0
Thread model: posix

The version numbers will vary. As long as you see a response without an error, GCC (Clang) is installed and ready.

Step 3 — Test with a quick C program

Create a file called hello.c:

#include <stdio.h>

int main(void) {
    printf("Hello from macOS Tahoe!\n");
    return 0;
}

Compile and run it:

gcc hello.c -o hello
./hello

Output:

Hello from macOS Tahoe!

That is all you need. Skip to What’s Next below.

Method 2 — Homebrew (Actual GNU GCC)

Homebrew is a package manager for macOS. It installs GNU GCC as gcc-14 (or the current version number) alongside Apple’s Clang.

Step 1 — Install Homebrew

If you do not have Homebrew yet:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Follow the on-screen prompts. On Apple Silicon Macs, Homebrew installs to /opt/homebrew/. The installer will tell you to add Homebrew to your PATH — run the two eval lines it shows you, or add them to your ~/.zshrc.

Step 2 — Install GCC

brew install gcc

Step 3 — Verify

gcc-14 --version
gcc-14 (Homebrew GCC 14.x.x) 14.x.x
Copyright (C) 2024 Free Software Foundation, Inc.

Note: Homebrew installs GNU GCC as gcc-14 (or gcc-15 depending on the current version), not plain gcc, so Apple’s Clang remains the default. Use gcc-14 explicitly when you need GNU GCC, and gcc for Apple Clang.

Apple Silicon vs Intel Macs

Apple Silicon (M1/M2/M3/M4) Intel Mac
xcode-select method Works — target is arm64 Works — target is x86_64
Homebrew path /opt/homebrew/ /usr/local/
gcc –version output Shows arm64-apple-darwin Shows x86_64-apple-darwin
C programs compile Yes, natively Yes, natively

Both work fine for learning C. The compiled programs run on your specific chip architecture.

Common Issues

Problem Fix
xcode-select: error: command line tools are already installed You already have them — run gcc --version to confirm
xcrun: error: invalid active developer path Run xcode-select --reset then try again
Dialog never appears after xcode-select --install Check System Settings → Software Update for a pending CLT update
Homebrew: zsh: command not found: brew Add Homebrew to PATH — run the eval line the installer showed you

What’s Next

Now that GCC is installed, the next step is learning how to compile and run C programs from the Terminal — including how to handle multiple source files and compiler flags. See our complete guide: How to Run a C Program on macOS Tahoe.

If you want a full IDE with code completion and debugging instead of the bare Terminal, VS Code is the best free option for macOS and works great on Apple Silicon.

Once your environment is ready, browse our full list of C programs with examples to start practising.


As an Amazon Associate we earn from qualifying purchases.

Recommended Book

The best book to learn C once your environment is set up — The C Programming Language by Brian Kernighan and Dennis Ritchie (K&R). Concise, precise, and still the definitive reference 35 years on.

Greedy Change Making Program in C

Problem Statement

Write a C program to solve ‘Change Making Problem’. Put simply, a solution to Change-Making problem aims to represent a value in fewest coins under a given coin system. This program was requested by one of readers on our Facebook Page.

Coin changing

Inputs to program

  • Number of different denominations available
  • List of numbers representing all the denominations
  • Amount to represent in the given coin system

Output

The program should output a way to represent the given amount using fewest number of coins. For example. if you have coins of value 1, 2, 5 and 10 and want to represent 26, the program should output the correct solution 10×2 5×1 2×0 1×1

Solution

The greedy approach is easy to understand and implement as well. We start with using the largest denomination coin/currency possible. Once the owed amount is less than the largest, we move to next largest coin, so on and so forth.

Assumptions

  • Denominations are entered in descending order. That is largest one first. Example: 100, 50, 20, 5, 1. We can add a sort method if it’s not, a minor change.
  • We always have denomination of 1(Just to make sure we have a solution for all the numbers).

Limitation

Greedy approach works best with Canonical Coin systems and may not produce optimal results in arbitrary coin systems. For example, if denominations are {4, 3, 1}, number 6 is represented as 4×1 3×0 1×2 by this program; taking 3 coins. The correct answer in this case is 4×0 3×2 1×0 with just 2 coins.

The Program

[gist id=”ba3675bad57dae3341713c23161ca318″]

Sample Output

Further reading

Infix to Postfix Conversion and Evaluation in C – With Example

Infix notation is the way humans write arithmetic: A + B, 5 * (2 + 3). The operator sits between its operands. Computers, however, evaluate expressions more efficiently in postfix notation (also called Reverse Polish Notation), where the operator comes after its operands: A B +, 5 2 3 + *.

This C program does both jobs in one pass: it converts an infix expression to postfix using a stack, then evaluates the postfix result to give the final answer.

Infix vs Postfix — The Key Difference

Expression Infix Postfix
A plus B A + B A B +
A plus B times C A + B * C A B C * +
Parenthesised (A + B) * C A B + C *
Complex 5 + ((2 + 6) * 9) - 8 5 2 6 + 9 * + 8 -

Why postfix? It eliminates the need for parentheses and operator precedence rules during evaluation. A simple left-to-right scan with a stack is all you need — no lookahead required. This is how compilers and calculators work internally.

Algorithm — Infix to Postfix Conversion

Uses a stack to hold operators temporarily. Operands go straight to output; operators wait on the stack until a lower-precedence operator or end of expression forces them out.

Rules:

  1. Scan left to right.
  2. Operand (letter or digit) → write to output immediately.
  3. ( → push onto stack.
  4. ) → pop and output until ( is found; discard both parentheses.
  5. Operator → pop and output all operators of equal or higher precedence first, then push the current operator.
  6. End of expression → pop and output everything remaining on the stack.

Precedence: * / (level 3) > + - (level 2) > ( (level 1) > # sentinel (level 0)

Walkthrough: Converting A + B * C

Token   Action                Stack       Output
A       operand → output      [#]         A
+       pr(#)=0 < pr(+)=2     [# +]       A
        push +
B       operand → output      [# +]       A B
*       pr(+)=2 < pr(*)=3     [# + *]     A B
        push *
C       operand → output      [# + *]     A B C
end     pop all: * then +     [#]         A B C * +

Result: A B C * +

Algorithm — Postfix Evaluation

  1. Scan left to right.
  2. Operand → push onto stack.
  3. Operator → pop two operands, apply operator, push result.
  4. End of expression → the single value on the stack is the answer.

Walkthrough: Evaluating 5 2 6 + 9 * + 8 -

Token   Stack after
5       [5]
2       [5, 2]
6       [5, 2, 6]
+       pop 6,2 → 2+6=8    [5, 8]
9       [5, 8, 9]
*       pop 9,8 → 8*9=72   [5, 72]
+       pop 72,5 → 5+72=77 [77]
8       [77, 8]
-       pop 8,77 → 77-8=69 [69]

Result: 69

C Program — Infix to Postfix Conversion and Evaluation

#define SIZE 50
#include <ctype.h>
#include <stdio.h>

char s[SIZE];
int top = -1;

void push(char elem) {
    s[++top] = elem;
}

char pop() {
    return s[top--];
}

/* Returns operator precedence */
int pr(char elem) {
    switch (elem) {
        case '#': return 0;
        case '(': return 1;
        case '+':
        case '-': return 2;
        case '*':
        case '/': return 3;
    }
    return -1;
}

/* Removes spaces from a string in-place */
void remove_spaces(char *src) {
    char *i = src, *j = src;
    while (*j != 0) {
        *i = *j++;
        if (*i != ' ')
            i++;
    }
    *i = 0;
}

void infix_to_postfix(char *infix, char *postfix) {
    char ch, elem;
    int i = 0, k = 0;

    remove_spaces(infix);
    push('#');

    while ((ch = infix[i++]) != '\n') {
        if (ch == '(')
            push(ch);
        else if (isalnum(ch))
            postfix[k++] = ch;
        else if (ch == ')') {
            while (s[top] != '(')
                postfix[k++] = pop();
            elem = pop();   /* discard the '(' */
        } else {            /* operator */
            while (pr(s[top]) >= pr(ch))
                postfix[k++] = pop();
            push(ch);
        }
    }

    while (s[top] != '#')
        postfix[k++] = pop();

    postfix[k] = '\0';
}

int eval_postfix(char *postfix) {
    char ch;
    int i = 0, op1, op2;

    while ((ch = postfix[i++]) != '\0') {
        if (isdigit(ch))
            push(ch - '0');
        else {
            op2 = pop();
            op1 = pop();
            switch (ch) {
                case '+': push(op1 + op2); break;
                case '-': push(op1 - op2); break;
                case '*': push(op1 * op2); break;
                case '/': push(op1 / op2); break;
            }
        }
    }
    return s[top];
}

int main() {
    char infx[50], pofx[50];

    printf("Enter infix expression: ");
    fgets(infx, 50, stdin);

    infix_to_postfix(infx, pofx);

    printf("Infix    : %s", infx);
    printf("Postfix  : %s\n", pofx);

    top = -1;   /* reset stack for evaluation */
    printf("Result   : %d\n", eval_postfix(pofx));

    return 0;
}

Code Explanation

  • Shared stack s[]: Used for both phases. After conversion, top is reset to -1 so the same array is reused cleanly for evaluation.
  • Sentinel '#': Pushed before scanning begins. Acts as a stack bottom marker with precedence 0, so the loop while (pr(s[top]) >= pr(ch)) always terminates safely without checking for an empty stack.
  • remove_spaces(): Strips spaces in-place so A + B and A+B are treated identically. Modifies the string character by character using two pointers.
  • Operand vs operator: isalnum(ch) covers both letters (variables) and digits. Single-digit numbers only — extend with a numeric stack for multi-digit support.
  • Evaluation — ch - '0': Converts a digit character to its integer value (e.g., '7' - '0' = 7). This works because digit characters are consecutive in ASCII.

Sample Input and Output

Enter infix expression: 5+((2+6)*9)-8

Infix    : 5+((2+6)*9)-8
Postfix  : 526+9*+8-
Result   : 69

Limitations of This Program

  • Single-digit operands only12 + 3 would treat 1, 2, and 3 as separate operands. Extend with an integer stack and string parsing for multi-digit numbers.
  • No error handling — mismatched parentheses or invalid characters cause undefined behavior.
  • Right-associative operators (like ^ for exponentiation) need a small tweak: use > instead of >= in the while loop when the current operator is right-associative.

Related Programs


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.