Now that you know how C language works,I will show you how to create a function, I will tell you how to work with functions, and why are functions so important in any programming language. I will start with a very simple example, I will gather two numbers using a function.
#include "stdafx.h" #include <stdio.h> int amount(int, int); int main() { int a = 0,b =0; printf("a:"); scanf("%d", &a); printf("b:"); scanf("%d", &b); printf("%d + %d = %d",a,b,amount(a,b)); getchar(); return 0; } int amount(int a, int b) { int c; c = a + b; return c; }
This was a very simple example, now let’s try to do something more fun and more complex.
#include "stdafx.h" #include <stdio.h> int amount(int, int); int subtract(int, int); int multiplication(int,int); int division(int,int); void menu(); int main() { int a; int b; printf("a:"); scanf("%d", &a); printf("b:"); scanf("%d", &b); menu(); int option; do{ printf("\\nChoose Option:"); scanf("%d",&option); switch(option) { case 1: printf("a + b = %d", amount(a,b)); break; case 2: printf("a - b = %d", subtract(a,b)); break; case 3: printf("a * b = %d", multiplication(a,b)); break; case 4: printf("a / b = %d", division(a,b)); break; default: printf("Invalid Input"); } }while(option != 5); getchar(); return 0; } int amount(int a, int b) { int c; c = a + b; return c; } int subtract(int a, int b) { int c; c = a - b; return c; } int multiplication(int a, int b) { int c; c = a * b; return c; } int division(int a, int b) { int c; c = a / b; return c; } void menu() { printf("**********************"); printf("\\n1. +"); printf("\\n2. -"); printf("\\n3. *"); printf("\\n4. /"); printf("\\n**********************"); }
Well, is not so complex after all, but is a very good example of how functions works. I don’t know what to tell you more, but if you have any kind of questions don’t hesitate to ask me. I will answer, and I will try to help you as much as I can. Working with functions is very important and you need to understand this very well in order to progress with any programing language.
I made you another very simple and short example, look at this code:
#include "stdafx.h" #include <stdio.h> int max2(int, int); int max3(int, int, int); int main() { int a,b,c; printf("a="); scanf("%d", &a); printf("b="); scanf("%d", &b); printf("c="); scanf("%d", &c); printf("\\nMax2(%d,%d) = %d", a,b, max2(a,b)); printf("\\nMax3(%d,%d,%d) = %d", a,b,c, max3(a,b,c)); getchar(); getchar(); return 0; } int max2(int a, int b) { return a > b ? a:b; } int max3(int a, int b, int c) { int m = max2(a,b); m = max2(m,c); return m; }
Maybe you don’t understand this line:
return a > b ? a:b;
This means: If a > b return a else return b
One Reply to “Getting started with C [4]”