Commit 6efdccd2 authored by Erik Strand's avatar Erik Strand
Browse files

Add a program that adds numbers from the command line

parent 887c0528
# Change your compiler here if you're not using gcc. CC is for C, and CXX is for C++.
CC = gcc
CXX = g++
CFLAGS = -Wall -O3
.PHONY: all
all: add_integers
add_integers: add_integers.c
$(CC) $(CFLAGS) -o add_integers add_integers.c
# This rule deletes all the binaries. It's declared "phony" which means it doesn't actually make
# anything. Otherwise Make would get confused about when it should run this rule.
.PHONY: clean
rm add_integers
# Basic Input
If you want to pass arguments to your program, you can add them to `main`.
#include <stdio.h>
#include <stdlib.h>
// To accept command line input, we add two arguments to main. The first will contain the number of
// inputs on the command line, and the second is an array of C strings (pointers to characters) that
// contain what was written. Main is special and has to take no arguments, or these two arguments.
// (Other functions can take whatever arguments they like.)
int main(int argc, const char* argv[]) {
// If the user didn't give us two numbers, we exit.
if (argc < 3) {
printf("Please type two numbers.\n");
return 0;
// If the user gave us more than two numbers, we just ignore the rest.
// Can you change the program so it adds all the numbers?
if (argc > 3) {
printf("Woah, there, that's a lot of numbers.\n");
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = a + b;
printf("%i + %i = %i\n", a, b, c);
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment