You are on page 1of 49

Computing Fundamentals

Dr. Muhammad Yousaf Hamza


Deputy Chief Engineer, PIEAS
More discussion on input and output of
Functions

Dr. Yousaf, PIEAS


// Calculate factorial without function
#include<stdio.h>
int main()
{
int i, fact, num1;
printf("Enter a positive integer\n");
scanf("%d", &num1);
fact = 1;
for (i = num1; i >=1; i--)
{
fact = fact * i;
}
printf("Factorial of %d is %d\n",num1, fact);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
// Calculate factorial using int cal_fac(int x)
//Functions {
#include<stdio.h> int i, fact;
int cal_fac(int x); fact = 1;
int main() if(x == 0)
{ fact = 1;
int i, fact, num1; else
printf("Enter a positive integre\n"); {
scanf("%d", &num1); for (i = x; i >=1; i--)
fact = cal_fac(num1); {
printf("Factorial of %d is fact = fact*i;
%d\n",num1, fact); }
}
getchar();
return 0; return fact;
} }
Dr. Yousaf, PIEAS
// Calculate factorial using int cal_fac(int x)
//Functions {
#include<stdio.h> int i, fact;
int cal_fac(int x); fact = 1;
int main() if(x == 0)
{ fact = 1;
int i, fact; else
{
fact = cal_fac(5)+cal_fac(3) ; // Valid for (i = x; i >=1; i--)
{
printf(“Sum of factorials is %d\n", fact = fact*i;
fact); }
}
getchar();
return 0; return fact;
} }
Dr. Yousaf, PIEAS
Printing stars through a function
/* demonstrates a function that does // function definition
not take any arguments and does not void stars ()
provide output to main. */ {
#include <stdio.h> int j;
void stars (); //function (Prototype)
int main()
for(j=0; j < 10; j++)
{
printf("*");
int x = 5, y = 13;
stars (); //call to function printf("\n");

x = x+10; }
y = x*x + (10/2);
stars (); //call to function
getchar(); return 0;
}

Dr. Yousaf, PIEAS


Printing any symbol any times
// demonstrates of passing // function definition
//constants to a function void stars (char ch, int n)
#include <stdio.h> {
void stars (char ch, int n) ; int j;

int main() for(j=0; j < n; j++)


{ printf(“%c“, ch);
int x = 5, y = 13, z; printf("\n");
stars (‘%’, 7); //call to function
x = x+10; }
y = x*x + (10/2);
stars (‘$’, 18); //call to function
z = x + y;
return 0;
}
Dr. Yousaf, PIEAS
Scanning Values to Pass
// demonstrates of passing values from // function definition
//variables to a function void stars (char ch, int n)
#include <stdio.h>
void stars (char ch, int n) ;
{
int main() int j;
{
char chp; for(j=0; j < n; j++)
int nt ; printf(“%c“, ch);
printf(“Please enter a symbol you want
to print\n”);
printf("\n");
chp = getchar();
printf(“Please enter the number of times }
you want to print the character\n”);
scanf(“%d”, nt);
stars (chp, nt); //call to function
// Rest of the code here
getchar(); return 0;
}
Dr. Yousaf, PIEAS
Missing Arguments
// Demonstration of missing arguments // function definition
#include <stdio.h> void stars (char ch, int n)
void stars (char ch = ‘*’, int n = 10) ; {
int main() int j;
{
for(j=0; j < n; j++)
char chp;
printf(“%c“, ch);
int nt ;
// Rest of the code printf("\n");
stars (); //call to function
stars (‘#’); //call to function }
stars (‘+’, 5); //call to function
chp = ‘~’;
nt = 12;
stars (chp, nt); //call to function
stars();
// Rest of the code here
getchar(); return 0; }
Dr. Yousaf, PIEAS
Returning a value from function
/* Program that will pass temperature in /* converts centigrade to
centigrade to a function that converts it Fahrenheit */
into Fahrenheit and returns the value to
the main function*/ float ctof (float cgrade)
#include <stdio.h> {
float ctof (float); //declaration float fgrade;
int main() fgrade = (9/5)*cgrade+ 32.0;
{ return fgrade;
float centi, farhen; }
printf("\nEnter temperature in
centigrade\n");
scanf("%f",&centi);
farhen = ctof(centi);
printf(“ %f Centigrade = %f Faherenheit”,
centi, fahren);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Arguments and Parameters
• stars (‘%’, 7); //call to function
• Arguments: The values as ‘%’, 7 that are passed to a
function are called arguments.
• void stars (char ch, int n)
• The variables within the function that hold the
arguments are called parameters. In this example, ch
and n are parameters.
• We should note that many programmers use the
terms argument and parameter somewhat
interchangeably.
• When the function is called, its parameters are
automatically initialized to the values passed by the
calling program.

Dr. Yousaf, PIEAS


// Finding the maximum of three numbers using a function
#include<stdio.h>
int maximum( int, int, int );
int main()
{
int a, b, c;
printf("Enter three integers: " );
scanf("%d%d%d", &a, &b, &c );
printf( "Maximum is: %d\n", maximum( a, b, c ) );
getchar(); return 0;
}
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
Dr. Yousaf, PIEAS
#include <stdio.h>
void func1(void); • At iteration 0: x = 0, y = 0
int main()
{ • At iteration 1: x = 0, y = 0
int count; • At iteration 2: x = 0, y = 0
for (count = 0; count < 20; count++) • At iteration 3: x = 0, y = 0
{
printf("At iteration %d: ", count);
• At iteration 4: x = 0, y = 0
func1(); • At iteration 5: x = 0, y = 0
} • At iteration 6: x = 0, y = 0
getchar(); return 0;
}
• At iteration 7: x = 0, y = 0
void func1(void) • At iteration 8: x = 0, y = 0
{ • At iteration 9: x = 0, y = 0
int x = 0;
• and so on
int y = 0;
printf("x = %d, y = %d\n", x, y);
x++;
y++;
}
Dr. Yousaf, PIEAS
Scope of Variables

Dr. Yousaf, PIEAS


//Concept of local variables
#include <stdio.h>
void demo(void);
int main()
{
int x = 1, y = 2;
printf("\nBefore calling demo(), x = %d and y = %d", x, y); //x=1, y=2
demo();
printf("\nAfter calling demo(), x = %d and y = %d\n", x, y); //x=1,y=2
getchar(); return 0;
}
void demo(void) // Function header and definition
{
/* Declare and initialize two local variables. */
int x = 88, y = 99;
/* Display their values. */
printf("\n\nWithin demo(), x = %d and y = %d", x, y); // x=88, y=99
}
Dr. Yousaf, PIEAS
What is scope?
• The scope of a variable is where it can be used in
a program

LOCAL VARIABLES
• Normally variables are local in scope - this
means they can only be used in the function
where they are declared.
• All variables declared inside functions are
local variables
– Known only in function defined

Dr. Yousaf, PIEAS


Local Variables
• Local Variables

int func1 (int y)


{
int a, b = 10;
float rate;
double cost = 12.55;
.......
}

• Those variables declared “within” the function are


considered “local variables”.
• They values can only be used inside the function they
were declared in, and not elsewhere.

Dr. Yousaf, PIEAS


The print stars example
This program prints five rows of
five stars *****
#include <stdio.h>
void print_stars(int); *****
*****
int main() *****
{ *****
int i;
for (i= 0; i < 5; i++) Loop around 5 times to
print_stars(5); print the stars
return 0;
} Variables here are LOCAL variables

void print_stars (int n) This prints 'n' stars and then


{
int i; a new line character
for (i= 0; i < n; i++)
printf ("*");
printf ("\n");
}

Dr. Yousaf, PIEAS


Local and Global Variables

Dr. Yousaf, PIEAS


// Scope of variables, Page 80
//Local versus global (external) variables, pages; 207-209
// Local Variable
#include<stdio.h>
void demo(int x);
int main()
{
int x = 10;
printf("\n in main, before demo x = %d \n\n", x); // x = 10
demo(x);
printf("in main, after demo x = %d \n\n", x); // x = 10
getchar(); return 0;
}
void demo (int x)
{
x = x+20;
printf("inside demo x= %d \n\n", x); // x = 30
}

Dr. Yousaf, PIEAS
// Global variable
#include<stdio.h>
void demo();
int x = 10; // note the declaration above the main
int main()
{
printf("\nin main, before demo x = %d \n\n", x); // x = 10
demo();
printf("in main, after demo x = %d \n\n", x); // x = 30
getchar();
return 0;
}

void demo ()
{
x = x + 20; // x has not been declared in demo
printf("in demo x = %d \n\n", x); // x = 30
}
Dr. Yousaf, PIEAS
Global Variables
• We can also declare global variables.

• If we declare a variable outside a function it


can be used in any function beneath where it
is declared, hence called global variables.

• Global variables are also sometimes called


external variables, since they are defined
external to any function.
Dr. Yousaf, PIEAS
// Again x is global variable
#include<stdio.h>
void demo(int y); // y is local variable
int x = 10; // x is global variable
int main()
{
printf("\nin main, before demo x = %d \n\n", x); // x = 10
demo(x);
printf("in main, after demo x = %d \n\n", x); // x = 30
getchar();
return 0;
}

void demo (int y) // y has been declared in demo


{
x = y + 20; // x has not been declared in demo
printf("in demo x = %d \n\n", x); // x = 30
}
Dr. Yousaf, PIEAS
// Still Local variable
#include<stdio.h>
void demo(int x);
int x = 10;
int main()
{
printf("\nin main, before demo x = %d \n\n", x); // x = 10
demo(x);
printf("\nin main, after demo x = %d \n\n", x); // x = 10
getchar();
return 0;
}

void demo (int x) // demo has its own x, so now local for this function.
{
x = x + 20;
printf("in demo x = %d \n\n", x); // x = 30
} Dr. Yousaf, PIEAS
Example: Global Variable
#include <stdio.h> void caltot (float num1,
float total = 0.0; float num2, float num3)
void caltot (float num1, float num2, {
float num3); //declaration total = num1 + num2 +
void printtot (); num3;
int main() }
{
float x = 4.5, y = 3.7, z = 8.1; void printtot ()
caltot(x, y, z); {
printtot(); printf(“Total is %f\n”, total);
}
printf(“Total is %f\n”, total);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Example: Previous Example Without
Global Variable // Error
#include <stdio.h>
void caltot (float num1, float num2, void caltot (float num1,
float num3); //declaration float num2, float num3)
void printtot (); {
int main() total = num1 + num2 +
{ num3; // error
float x = 4.5, y = 3.7, z = 8.1; }
float total = 0.0;
caltot(x, y, z); void printtot ()
printtot(); {
printf(“Total is %f\n”, total); printf(“Total is %f\n”, total);
getchar(); // error
return 0; }
}
Dr. Yousaf, PIEAS
Notes About Global Variables
– Global variables are also called extern
variables.
– Global variables are known in any
function
• A global variable is used when it must be accessible to
more than one function in a program.
• Global variables are often the most important
variables in procedural programs.
• However, global variables create organizational
problems because they can be accessed by any
function.
• The wrong functions may access them, or functions
may access them incorrectly.

Dr. Yousaf, PIEAS


Notes About Global Variables

Question:
Can there be a local and a global variable of
same name?
Ans:
Yes, if a function has a variable whose name is
same as previously declared global variable,
then the local variable will take precedence
inside such a function

Dr. Yousaf, PIEAS


Home Take Assignment
(1) Declare a global array of 10 integers, declare a variable size that
will store the size of the array, now write the following functions.
A. void PrintArray(void) : This function should print the global array
B. void SumArray(void): This function should print the sum of all
elements of the array

(2) A palindrome is a number that reads the same from left to right or
from right to left. For example 121 , 222, 62226 are all palindrome
numbers.
Write a program (without function) that should accept three digits
number from the user. You code should tell whether the given number
is palindrome or not?

(3) Modify the above program such that it should accept three digits
number from the user. Write a function isPalindrome. Pass the
number provided by the user from main to this function. This function
should determine whether the number is palindrome or not? The
function should return the result to the main. The main should display
it. Dr. Yousaf, PIEAS
Home Take Assignment
A stack is a container of objects such that objects are placed on top of
each other just like dishes are placed on top of each other.

Write a program that declares a global array of 10 integers, name this


array as stack. 2‐ Write the following functions

1‐push: This function should put the value of a variable to the stack.
2‐pop: This function should return the first element of the array
3‐show: The function should display the contents of the array stack
4-shift_right : This function should shift the elements of the array 1
place toward right i.e. element at index 0 will move to index 1 ,
element at index 1 will move to index 2 and so on till the last array
element is processed
5. void shift_left(void) : this function should shift the elements of the
array 1 place towards left i.e. element at index 1 will be shifted to
index 0, element at index 2 will be shifted to index 1.

Dr. Yousaf, PIEAS


Automatic Versus Static Variables

Dr. Yousaf, PIEAS


// Auto Variables
#include <stdio.h>
void func1(void); • At iteration 0: x = 0, y = 0
int main() • At iteration 1: x = 0, y = 0
{
• At iteration 2: x = 0, y = 0
int count;
for (count = 0; count < 20; count++) • At iteration 3: x = 0, y = 0
{ • At iteration 4: x = 0, y = 0
printf("At iteration %d: ", count); • At iteration 5: x = 0, y = 0
func1();
} • At iteration 6: x = 0, y = 0
getchar(); return 0; • At iteration 7: x = 0, y = 0
} • At iteration 8: x = 0, y = 0
void func1(void)
{ • At iteration 9: x = 0, y = 0
int x = 0; • and so on
int y = 0;
printf("x = %d, y = %d\n", x, y);
x++;
y++;
} Dr. Yousaf, PIEAS
//Automatic versus Static Variables, pages 209-211
// Example Page 211 Static Variables
#include <stdio.h> • At iteration 0: x = 0, y = 0
void func1(void); • At iteration 1: x = 1, y = 0
int main()
{ • At iteration 2: x = 2, y = 0
int count; • At iteration 3: x = 3, y = 0
for (count = 0; count < 20; count++) • At iteration 4: x = 4, y = 0
{
printf("At iteration %d: ", count); • At iteration 5: x = 5, y = 0
func1(); • At iteration 6: x = 6, y = 0
} • At iteration 7: x = 7, y = 0
getchar(); return 0;
} • At iteration 8: x = 8, y = 0
void func1(void) • At iteration 9: x = 9, y = 0
{ • and so on
static int x = 0;
int y = 0;
printf("x = %d, y = %d\n", x, y);
x++;
y++; }
Dr. Yousaf, PIEAS
// static.c
// demonstrates static variables // finds average of old plus
#include <stdio.h> new data
float getavg(float); //declaration float getavg(float newdata)
int main() {
{ static float total = 0;
float data=1, avg; /*static variables are
while( data != 0 ) initialized*/
{ static int count = 0;
printf("Enter a number: "); count++; //increment count
scanf("%f",&data); total += newdata; /*add
avg = getavg(data); new data to total*/
printf("New average is %f\n",avg); return total / count;
} //return the new average
return 0; }
}
Dr. Yousaf, PIEAS
Automatic Storage
• Storage class specifiers (auto or static) decide
Storage duration which means how long an
object exists in memory
• Automatic storage
– Object created and destroyed within its block
– auto: default for local variables
auto double x, y;
Variables that are automatically created and
automatically destroyed are called automatic or
auto variables. Non‐static variables that are
declared inside a function are automatically
created and destroyed so non‐static local variables
are auto variables

Dr. Yousaf, PIEAS


Static Storage
• Static storage
– Variables exist for entire program execution
– Default value of zero

static: local variables defined in functions.


• Keep value after function ends
• Only known in their own function

Dr. Yousaf, PIEAS


exit() function

Dr. Yousaf, PIEAS


exit()
// About exit() function. Page 236
#include<stdio.h>
#include<stdlib.h> // to use exit() function.
int main()
{
int i, j, k;
for (i = 0; i<5; i++)
printf("%d\n", i);
getchar();
exit(0); // it will exit the program
j = 23;
printf("j = %d\n", j);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
exit()
// Following program without exit()
// In the next slide, we will use exit() within a function
#include<stdio.h>
#include<stdlib.h>
int add(int x, int y);
int main()
{
int i = 10, j, k;
printf ("i = %d\n", i);
j = add(10,20);
printf ("j = %d\n", j);
getchar(); return 0;
}
int add(int x, int y)
{
int z;
z = x+y;
return z;
} Dr. Yousaf, PIEAS
exit()
// Use of exit() within a function
#include<stdio.h>
#include<stdlib.h> // to use exit function
int add(int x, int y);
int main()
{
int i = 10, j, k;
printf ("i = %d\n", i);
getchar();
j = add(10,20);
printf ("j = %d\n", j);
getchar(); return 0;
}
int add(int x, int y)
{
int z;
z = x+y;
exit(0); // It will exit the entire program (not the function only).
return z;
Dr. Yousaf, PIEAS
}
Recursion

‫ﺗﮑرار‬

Dr. Yousaf, PIEAS


Recursion
Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
Write a recursive function int fact(int num) that should return
the factorial of given number num

Dr. Yousaf, PIEAS


//Calculate Factorial using Recursion int factorial (int a)
{
# include<stdio.h> if (a==1) // base case
int factorial(int num);
return 1;
int main ()
else
{
int f,x; {
printf("Enter integer value in the range 1 a *= factorial(a-1);
to 10: "); return a;
scanf("%d", &x); }
if (x > 10 || x < 1) }
printf ("Illegal input!\n");
else
{
f = factorial(x);
printf ("%d factorial equals %d\n", x,f);
}
getchar(); return 0; }
Dr. Yousaf, PIEAS
Recursion
• Recursive functions
• A function that calls itself inside its body is called a
recursive function
• Can only solve a base case
– Divide a problem into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step) to
solve what it cannot do

– Eventually base case gets solved


• Gets plugged in, works its way up and solves whole problem

Dr. Yousaf, PIEAS


Example Using Recursion
/*This function prints all the number between zero and a given
number that is greater than zero. */
#include <stdio.h>
void printSeries(int num);
int main()
{
printSeries(6);
getchar(); return 0;
}
void printSeries(int num)
{
if(num<=0)
return;
printf("%d", num);
printSeries(num-1);
} Dr. Yousaf, PIEAS
Example Using Recursion:
The Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, ...
– Each number is the sum of the previous two
– fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Write a recursive function that can print first N terms
of Fibonacci series ,
– Can be solved recursively:
Code for the fibaonacci function
int fibonacci(int n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci(n - 1)+ fibonacci(n – 2);
} Dr. Yousaf, PIEAS
Example Using Recursion:
The Fibonacci Series
• Set of recursive calls to function fibonacci
f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

Dr. Yousaf, PIEAS


// To generate Fibonacci series // Function Definition
//using Recursion int fibonacci(int n)
#include<stdio.h> {
int fibonacci(int n); if ( n == 0 || n == 1 )
int main() return n;
{ else
int i, terms, result; return fibonacci( n - 1 ) +
printf("Please enter the number of fibonacci( n - 2 );
terms from 1 to 20: "); }
scanf("%d",&terms);
for ( i = 0; i<= terms; i++)
{
result = fibonacci(i);
printf("%d, ", result);
}
getchar(); return 0; }
Dr. Yousaf, PIEAS
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls

• Termination
– Iteration: loop condition fails
– Recursion: base case recognized

Dr. Yousaf, PIEAS

You might also like