Function and Scope of Variables in C - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Function and Scope of Variables in C

Share This

A function is a block of program code that is written to perform a specific task. A function is a reusable code block, which can be called many times according to the requirements. If we define a function, we don't need to write the same code block in many places within our program. Hence, we need to understand, how a function works.
  • A function receives input data as a parameter.
  • It performs operations on that data.
  • The generated result is returned to the caller function (not always).
In a program, prototypes of functions are declared before defining any function. The main function is the starting point of the program. Thus, the main function is defined as the first function (but it is not mandatory).

The functions, which have been declared, must be defined. This definition means writing the logic of the function to perform a specific task.

After the declaration and definition of the functions, these functions can be called from the main or other functions according to the requirements.

Note that the functions should have a unique name in C language.


Function Declaration


If a function performs the addition of two integer numbers and returns the result. The function can be declared in two ways as shown below. A declaration should have three segments: the first part is the return type of the function, the second part is the function name, and the types of parameters are the last part.

int add(int, int);
or
int add(int x, int y);


Function Definition


In this context, we are defining the function as below.
int add (int x, int y) { int z = x + y; return z; }
Hence, we are giving the following code for a calculator.

Code for Calculator
#include <stdio.h> int add (int, int); int sub (int, int); int mul (int, int); int div (int, int); void print(int z); int main(void) { int x, y, z; char op; printf("Calculator Program!\n"); while(1) { printf("Enter expression: x op y \n\t\t\t"); scanf("%d %c %d", &x, &op, &y); switch(op) { case '+': z = add (x, y); print(z); break; case '-': z = sub (x, y); print(z); break; case '*': z = mul (x, y); print(z); break; case '/': z = div (x, y); print(z); break; default: printf("Invalid operator!"); } } return 0; } void print(int z) { printf("The result is %d \n\n", z); } int add (int x, int y) { return x + y; } int sub (int x, int y) { return x - y; } int mul (int x, int y) { return x * y; } int div (int x, int y) { return x / y; }

A Program to calculate nCr + nCr+1 + ... + nCp
#include <stdio.h> int fact (int n); int main (void) { int i, n, r, p, res = 0; printf("Series!!!\n"); printf("Enter values of n, r, p"); scanf("%d %d %d", &n, &r, &p); if (r <= p && p <= n) { /* write the logic */ for (i = r; i <= p; i++) { res = res + fact (n) / (fact (i) * fact (n-i)); } printf("The result is %d\n", res); } else { printf("Invalid input."); } return 0; } int fact (int f) { int i, res = 1; for (i = 2; i <= f; i++) { res = res * i; } return res; }

Pascal Triangle
#include <stdio.h> #include <stdlib.h> #include <process.h> int b, i, j, n, p[20][20]; int choice(); int calculation(); int main() { printf("\n\t A Programe To Display Pascal's Triangle\n"); choice(); return 0; } int choice() { printf("\n\t Press"); printf("\n\t 1 : Left aligned\n\t 2 : Centre aligned"); printf("\n\t 3 : Right aligned\n\t 0 : To Quit\n\t "); b = getche() - '0'; if (!b) exit(1); if (b != 1 && b != 2 && b != 3) { printf("\n\t Invalid Choice\n\n"); choice(); } printf("\n Enter line number : "); scanf("%d", &n); calculation(); return 0; } int calculation() { printf("\n The Pascal's Triangle is...\n"); for (i = 0; i < n; i++) { for (j = 3 * n; j >= 3 * i; j--) { if (b == 2) printf(" "); if (b == 3) printf(" "); } for (j = 0; j <= i; j++) if (j == 0 || j == i) { p[i][j] = 1; printf("%6d", p[i][j]); } else { p[i][j] = p[i - 1][j - 1] + p[i - 1][j]; printf("%6d", p[i][j]); } printf("\n"); } choice(); return 0; }

Perfect number checking
/* A perfect number is a positive integer whose value is equal to the sum of all its positive factors, excluding itself. The first two perfect numbers are 6 (6=1+2+3) and 28 (28=1+2+4+7+14). The Greek Mathematician Euclid (c. 300 BCE) showed that if (2n -1) is prime, then (2n -1)2n-1 is a perfect number (check this out for 6 & 28). This program is written to find first k perfect numbers. */ #include <stdio.h> int isPrime(unsigned long input) { unsigned long i; for (i = 2; i < input; i++) { if (input % i == 0) return 0; } return 1; } int isPerfect(unsigned long input) { unsigned long factorSum = 1, i; for (i = 2; i < input; i++) { if (input % i == 0) factorSum += i; } printf("\nInput=%lu and the factorSum=%lu\n", input, factorSum); if (input == factorSum) return 1; else return 0; } unsigned long toThePower(unsigned long base, unsigned long index) { unsigned long result = 1, i; for (i = 1; i <= index; i++) result *= base; return result; } int main() { unsigned long temp, n; for (n = 2; n <= 100; n++) { if (isPrime(toThePower(2, n) - 1) == 1) { printf("\n 2^%d-1 is prime and ", n); temp = (toThePower(2, n) - 1) * toThePower(2, (n - 1)); if (isPerfect(temp) == 1) printf("and %lu is a perfect number.\n", temp); else printf("but %lu is not a perfect number\n", temp); } } return 0; }



Scope of Variables 


Local Scope of Variable 

If a variable is declared in a function, the variable is accessible within the function only. Though we can pass its address in another function to process. 

If a variable is declared inside a function, its scope is local to that function. The variable is not accessible in other functions until the variable is passed to that function. In this program, variable x is declared as a local variable. In the following program in function fun accessing x is not permitted as variable x is local to the main function.
#include <stdio.h> void fun (); int main (void) { int x = 10; x++; printf("\n%d", x); fun(); } void fun () { //x += 3; //printf("\n%d", x); }
Hence, the value of x should be passed in function, fun, if the function performs any operation on variable x. So the program should be updated as follow.
#include <stdio.h> void fun (int x); int main (void) { int x = 10; x++; printf("\n%d", x); fun(x); } void fun (x) { x += 3; printf("\n%d", x); }

Global Scope of Variable 

If a variable is outside of any function, the variable is accessible from anywhere within the file. This variable is known as the global variable. 

If a variable is declared outside of any function, its scope is global. In this program, variable x is declared as a global variable. Hence, the variable is accessible in both of the functions in the file.
#include <stdio.h> void fun (); int x = 10; int main (void) { x++; printf("\n%d", x); fun(); } void fun () { x += 3; printf("\n%d", x); }
We will suggest you avoid global variables. Global variables are generally used in multi-file programs.

Happy Exploring!

No comments:

Post a Comment