Function Assignment 1 — Find the Sum of Two Integers Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Sum of Two Integers Using a Function

📑 On this page:
  • Why write a function for addition?
  • Designing the function signature
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to declare a function prototype before main()
  • How to define a function with two int parameters and an int return value
  • How to call the function and use its return value
  • What happens on the call stack when the function is invoked
  • Why the parameters inside the function are copies of the arguments passed in

Why write a function for addition?

It sounds almost silly at first: you can add two numbers with a single line — sum = a + b; — so why build a function around it? Because this is the smallest possible example of the pattern that powers every larger C program. A function that takes inputs, does something with them, and returns a result is the basic unit of reusable code. Starting with addition lets you see the entire mechanism — the prototype, the definition, the parameters, the return value, the call site — without any other logic getting in the way.

Once you've written add(a, b) and it works, you have the template for subtract(a, b), multiply(a, b), max(a, b), power(a, b), and every other two-argument function you'll ever write. The shape is the same. Only the body changes. That's the reason this is assignment #1 — it's the foundation everything else sits on.

There's a second reason, too: it teaches you to think in terms of inputs and outputs. Before you write a single line of code, you ask: what does this function need to know (parameters), and what does it need to give back (return type)? For addition, that's obvious — two integers in, one integer out. For a more complex function, it might take some thought. Training that instinct early pays off later.

💡 In one line: write a function int add(int a, int b) that returns a + b. Read two integers from the user, call the function, print the result. That's the whole program — but the pattern behind it is the whole point.

A function called add takes two integer parameters, adds them, and returns the result to main().

Designing the function signature

Before writing the body, decide three things: the function name, its parameter types, and its return type. For addition, these are obvious but worth spelling out:

Part Choice Why
Function nameaddShort, descriptive, and doesn't clash with any standard library name.
Parametersint a, int bYou're adding integers, so both inputs should be int. Using float or double would be wrong for this problem.
Return typeintThe sum of two integers is an integer. If the inputs were double, the return type should be double too.

That gives the prototype:

int add(int a, int b);
                                

And the definition:

int add(int a, int b) {
    return a + b;
}
                                

Notice that a and b are local variables inside add. When you call add(x, y) from main, C copies the value of x into a and the value of y into b. Changes to a and b inside the function don't affect x and y in main. This is what "pass by value" means — and it's why the function can't accidentally corrupt your variables.

🎯 Key idea: the parameters of a function are freshly created variables. They happen to be initialized with the values you passed in, but they are separate from the caller's variables. That separation is the whole point of "pass by value."

Complete C Program

Program: read two integers, call add, print the result

#include <stdio.h>

/* Function prototype */
int add(int a, int b);

int main(void) {
    int x, y, sum;

    printf("Enter two integers: ");
    scanf("%d %d", &x, &y);

    sum = add(x, y);

    printf("Sum of %d and %d is %d\n", x, y, sum);

    return 0;
}

/* Function definition */
int add(int a, int b) {
    return a + b;
}
                                    

And here's a slightly more compact version that reads the values directly inside the printf call. It's shorter, but it's less readable — the first version is better style. Still worth seeing both:

Variant: inline call, no temporary variable

#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main(void) {
    int x, y;

    printf("Enter two integers: ");
    scanf("%d %d", &x, &y);

    printf("Sum = %d\n", add(x, y));

    return 0;
}
                                    

The inline version skips the sum variable entirely — it passes the return value of add(x, y) straight into printf. This works because add(x, y) is an expression that evaluates to an int, and printf's %d format specifier accepts an int expression. It's a perfectly valid pattern, but the named-variable version is easier to debug — if the sum is wrong, you can print sum before the final printf.

Notice also that in the second version, the prototype is gone. That's because the definition of add appears before main. When the compiler reaches the call to add inside main, it has already seen the function's signature, so it knows what to expect. The prototype is only necessary when the function is defined after the caller.

Program Output

A typical run:

Enter two integers: 12 30
Sum of 12 and 30 is 42
                                

Another run with negative numbers:

Enter two integers: -5 8
Sum of -5 and 8 is 3
                                

And with larger numbers:

Enter two integers: 1000 2500
Sum of 1000 and 2500 is 3500
                                

Nothing surprising in the output — which is fine. The point of this first program isn't the output; it's the mechanism. Once you can trace how 12 and 30 get from main into add, and how 42 gets back, you understand functions.

Step-by-Step Explanation

Let's walk through the program piece by piece, paying attention to what happens in memory.

1. The prototype

int add(int a, int b); tells the compiler: "There's a function called add, it takes two int arguments, and it returns an int." No body yet. Without this line, the compiler would see the call to add inside main and complain that it doesn't know what add is. With this line, the compiler is satisfied and waits for the definition elsewhere in the file.

2. Variable declarations

int x, y, sum; creates three local variables in main. Each is uninitialized — they hold whatever garbage was left on the stack. scanf will fill x and y next, and add will produce the value for sum.

3. Reading input

scanf("%d %d", &x, &y) reads two integers and stores them in x and y. The & is important — scanf needs the address of each variable so it can write into it. If you forget the &, you get undefined behavior (usually a crash).

4. The call to add

sum = add(x, y); is where the interesting stuff happens. Here's what C does, in order:

  1. Evaluate x — say it's 12. Evaluate y — say it's 30.
  2. Create two new local variables a and b inside the function's stack frame.
  3. Initialize a = 12 and b = 30.
  4. Jump to the body of add.
  5. Evaluate a + b, which is 12 + 30 = 42.
  6. Return 42 to the caller.
  7. Destroy the local variables a and b.
  8. Assign 42 to sum.

After the call returns, a and b no longer exist. Only the value 42 survives. That's the whole lifecycle of a function call.

5. The function definition

int add(int a, int b) { return a + b; } — the body is a single return statement. In C, return both computes the expression and hands it back to the caller. The function terminates immediately at that point. There's no implicit "end of function" return value — if a function that's supposed to return int ends without hitting a return, behavior is undefined.

6. Why "pass by value" matters here

Suppose you modified add to do a = a + 1; before returning. That change would only affect the local copy a inside the function — x in main would be unchanged. This is a deliberate safety feature: functions can't accidentally corrupt your data. If you ever want a function to modify the caller's variable, you pass a pointer instead — but that's a separate topic.

7. The %d format specifier

printf("Sum of %d and %d is %d\n", x, y, sum) — three %d specifiers, three integer arguments. The order matters: the first %d takes x, the second takes y, the third takes sum. If you swapped the arguments, the numbers would print in the wrong places. It's a common bug when copy-pasting printf calls.

8. The void in int main(void)

main(void) means main takes no arguments. Without void, int main() technically means "takes unspecified arguments" in older C dialects — an oddity worth knowing but not worth losing sleep over. Modern C (since C99) treats both as equivalent, but void is clearer about intent.

🔍 Trace it yourself: open a debugger (or add printf statements inside add). Print a and b inside the function. You'll see the same values as x and y. Then add a = 0; inside the function and print x in main afterward — x is unchanged. That's pass-by-value in action.

Frequently Asked Questions

1. Do I need the function prototype if the definition is before main?

No. If add is fully defined before main, the compiler has already seen its signature when it reaches the call inside main. The prototype is only needed when the definition comes after the caller. Many style guides still recommend always writing prototypes at the top of the file, because it makes the function inventory visible at a glance.

2. What happens if I use float instead of int?

The function would compute the floating-point sum. You'd change int add(int a, int b) to float add(float a, float b), and %d in printf to %f. The rest of the structure stays identical. This is a good exercise — you'll see how the signature dictates the arithmetic.

3. What if I pass more than two arguments to add?

The compiler will complain: "too many arguments to function add." The prototype and definition both say two parameters, so the compiler enforces exactly two. This is one of the benefits of prototypes — they catch mistakes at compile time rather than runtime.

4. Why does main return 0?

Returning 0 from main signals to the operating system that the program ran successfully. Any non-zero value usually indicates an error code. Shells and build systems rely on this convention — it's how make knows whether a compile succeeded.

5. Can add call itself (recursion)?

Technically yes, but it would be pointless: adding a number to itself recursively doesn't simplify the problem. Recursion is useful when the problem naturally breaks into smaller sub-problems — Fibonacci, factorials, tree traversal. Addition has no such structure. If you're curious, write a recursive add(a, b) using add(a, b-1) + 1 as a base case, but know that you'd never do it in real code.

6. What's the difference between int add(int, int) and int add(int a, int b) in a prototype?

Nothing to the compiler — both declare the same function. The first omits the parameter names, which is fine in a prototype because the names don't affect the signature. The second includes them for readability, so readers of the prototype can see what each parameter means. Most style guides prefer including the names.

💡 Tip: Once this works, try writing subtract, multiply, and divide using the same pattern. Then build a tiny "calculator" that asks the user for an operator (+, -, *, /) and dispatches to the right function. That's the next step — and it's a natural extension of this first program.

📖 Related Tutorials

  • Introduction to Functions in C
  • Need for User-Defined Functions
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Elements of a User-Defined Function
  • All 33 Function Assignments

All Assignments: -->> All 33 Function Assignments   ||   Next Topic: -->> 2. Check Whether a Number Is Prime Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.