SlideShare a Scribd company logo
1 of 47
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
// Addition of two integers using
//Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0;
}
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Dr. Yousaf, PIEAS
// Addition of two integers using
//Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
printf(“%d”, z) // Error
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
printf(“%d”, num1) // Error
return z;
}
Dr. Yousaf, PIEAS
Any variable declared in a function is
not visible inside main and vice versa.
Dr. Yousaf, PIEAS
Example of Function
// To determine the even or odd using
// a function
#include<stdio.h>
void EvenOrOdd(int num);
int main()
{
int num;
printf("Enter a number to know even
or oddn");
printf("Enter -100 to exitn");
while (1)
{
scanf("%d", &num);
if (num == -100)
break;
EvenOrOdd(num);
}
printf("OK");
getchar(); return 0; }
void EvenOrOdd(int num)
{
if(num%2==0)
printf("Evenn");
else
printf("Oddn");
}
Dr. Yousaf, PIEAS
Example of Function
#include<stdio.h>
void printLine(void)
{
printf("n*****************n");
}
void main ()
{
int num;
printLine();
printf("Enter a Number :");
scanf("%d",&num);
if(num%2==0)
printf("Even Number");
else
printf("Odd Number");
printLine();
getchar();
}
Output
*****************
Enter a Number :13
Odd Number
*****************
Returning a value using if else statement
A single value is returned, however, multiple
return statements can be used within a single
function using “if-then-else” statement.
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
// Returning a value and if else
#include<stdio.h>
int myfunc(int x, int y);
int main()
{
int num1, num2, smaller;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
smaller = myfunc(num1, num2);
printf("%d is smallern",smaller);
getchar();
getchar();
return 0;
}
int myfunc(int x, int y)
{
if(x < y )
return x;
else
return y;
}
Home/Lab Assignments
Write a function that returns the greater of the two numbers i.e.
make a function that takes two integer arguments and returns the
greater of the two. Write program to use this function.
(Try Yourself)
Write a function should accept two arguments i.e. length and
width of the rectangle and should return the area of the
rectangle, the prototype of the function is as under:
float areaRect(float, float);
(Try Yourself)
Develop a function that accepts two values as length and width of
a shape and returns 0 or 1. A 1 will be returned if the shape is a
square otherwise a 0 will be returned.
(Try Yourself).
Dr. Yousaf, PIEAS
Home/Lab Assignments
A normal dice has 6 sides numbered from 1 to 6, when the dice is
rolled the number on top side of the dice is considered to be the
result of rolling the dice. Dices are used in many games etc. Your
task is to write a function int rollDice(), the function should return
an integer value ranging from 1 to 6, to make function return a
random number each time use the library function rand() and
srand() (. Write a program that allow the user to call this function
multiple times , display the value returned by the function.
(Try Yourself)
Dr. Yousaf, PIEAS
Pass by Value Versus Pass by Reference
Dr. Yousaf, PIEAS
// Addition of two integers using Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1, num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Dr. Yousaf, PIEAS
Pass by Value
Dr. Yousaf, PIEAS
/* Passing arguments by value */
//Page Example 366
#include <stdio.h>
void by_value(int x, int y, int z);
int main()
{
int x = 2, y = 4, z = 6;
printf("n Before calling by_value,
x = %d, y = %d, z = %d.", x, y, z);
by_value(x, y, z);
printf("nn After calling by_value, x
= %d, y = %d, z = %d.",
x, y, z);
getchar();
return(0);
}
void by_value(int x, int y, int z)
{ printf("nn Within function
by_value, x = %d, y = %d, z =
%d.", x, y, z);
x = 0; y = 0; z = 0;
printf("nn Again within
function by_value , x = %d, y =
%d, z = %d.", x, y, z); }
Before calling by_value,
x = 2, y = 4, z = 6.
// Within function by_value,
x = 2, y = 4, z = 6.
// Again Within function
by_value,
x = 0, y = 0, z = 0.
//After calling y_value(),
x = 2, y = 4, z = 6.
Pass by Value
Calling Functions:
Call by Value and Call by Reference
• Used when invoking functions
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
• At this stage, we focus on call by value
• We will discuss call by reference later.
Dr. Yousaf, PIEAS
Parameters Passed by Value
• Parameters passed by
value!!
– This means they are
basically local variables
initialized to the values
that the function is
called with.
– They can be modified
as you wish but these
modifications will not
be seen in the calling
routine!
#include<stdio.h>
int twice(int x);
int main()
{
int x=10,y;
y=twice(x);
printf("%d,%dn",x,y);
getchar(); retun 0;
}
int twice(int x)
{
x=x+x;
return x;
}
Dr. Yousaf, PIEAS
Functions can Access Other Functions
Dr. Yousaf, PIEAS
Functions can access other functions
Once you have written a function, it can be accessed
from other functions. We can therefore build more
complex functions from simpler functions
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
// Function calling other function
#include <stdio.h>
float getavg(float x, float y, float z, int totnum);
float calavg(float sum_res, int totalnum);
int main() { float num1 = 3.5, num2 = 5.9, num3 = 1.7, avg;
int totnumbers = 3;
avg = getavg(num1,num2,num3,totnumbers);
printf("Average is %fn",avg); getchar(); return 0; }
float getavg(float x, float y, float z, int totnum)
{ float sum = x + y + z, average;
average = calavg(sum, totnum);
return average;
}
float calavg(float sum_res, int totalnum)
{ float avrg = sum_res/totalnum;
return avrg; }
Calling a function by Another Function
void a(void)
{
printf(“Function a”);
b();
}
void b(void)
{
printf(“Function b”);
}
void main()
{
a();
b();
}
Dr. Yousaf, PIEAS
Can we call function b() inside function a() ?
No, as function a() does not know anything
about function b().
A function can call only those functions
which are defined or declared before it.
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 integern");
scanf("%d", &num1);
fact = 1;
for (i = num1; i >=1; i--)
{
fact = fact * i;
}
printf("Factorial of %d is %dn",num1, fact);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
// Calculate factorial using
//Functions
#include<stdio.h>
int cal_fac(int x);
int main()
{
int i, fact, num1;
printf("Enter a positive integren");
scanf("%d", &num1);
fact = cal_fac(num1);
printf("Factorial of %d is
%dn",num1, fact);
getchar();
return 0;
}
int cal_fac(int x)
{
int i, fact;
fact = 1;
if(x == 0)
fact = 1;
else
{
for (i = x; i >=1; i--)
{
fact = fact*i;
}
}
return fact;
}
Dr. Yousaf, PIEAS
/* demonstrates a function that does
not take any arguments and does not
provide output to main. */
#include <stdio.h>
void stars (); //function declaration
// (prototype)
int main()
{
int x = 5, y = 13;
stars (); //call to function
x = x+10;
y = x*x + (10/2);
stars (); //call to function
getchar(); return 0;
}
// function definition
void stars ()
{
int j;
for(j=0; j < 10; j++)
printf("*");
printf("n");
}
Printing stars through a function
Dr. Yousaf, PIEAS
// demonstrates of passing
//constants to a function
#include <stdio.h>
void stars (char ch, int n) ;
int main()
{
int x = 5, y = 13, z;
stars (‘%’, 7); //call to function
x = x+10;
y = x*x + (10/2);
stars (‘$’, 18); //call to function
z = x + y;
return 0;
}
// function definition
void stars (char ch, int n)
{
int j;
for(j=0; j < n; j++)
printf(“%c“, ch);
printf("n");
}
Printing any symbol any times
Dr. Yousaf, PIEAS
// demonstrates of passing values from
//variables to a function
#include <stdio.h>
void stars (char ch, int n) ;
int main()
{
char chp;
int nt ;
printf(“Please enter a symbol you want
to printn”);
chp = getchar();
printf(“Please enter the number of times
you want to print the charactern”);
scanf(“%d”, nt);
stars (chp, nt); //call to function
// Rest of the code here
return 0;
}
// function definition
void stars (char ch, int n)
{
int j;
for(j=0; j < n; j++)
printf(“%c“, ch);
printf("n");
}
Passing Variables
Dr. Yousaf, PIEAS
// Demonstration of missing arguments
#include <stdio.h>
void stars (char ch = ‘*’, int n = 10) ;
int main()
{
char chp;
int nt ;
// Rest of the code
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
return 0; }
// function definition
void stars (char ch, int n)
{
int j;
for(j=0; j < n; j++)
printf(“%c“, ch);
printf("n");
}
Missing Arguments
Returning a value from function
Dr. Yousaf, PIEAS
/* Program that will pass temperature in
centigrade to a function that converts it
into Fahrenheit and returns the value to
the main function*/
#include <stdio.h>
float ctof (float); //declaration
int main()
{
float centi, farhen;
printf("nEnter temperature in
centigraden");
scanf("%f",&centi);
farhen = ctof(centi);
printf(“ %f Centigrade = %f Faherenheit”,
centi, fahren);
getchar();
return 0;
}
/* converts centigrade to
Fahrenheit */
float ctof (float cgrade)
{
float fgrade;
fgrade = (9/5)*cgrade+ 32.0;
return fgrade;
}
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: %dn", 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
Passing string to a function
#include <stdio.h>
void Display(char ch[]);
int main()
{
char c[50];
printf("Enter string: ");
gets(c);
Display(c); // Passing string c to function.
getchar(); return 0;
}
// Function definition
void Display(char ch[]) // It will automatically fix its size
{
printf("String Output: ");
puts(ch);
}
Dr. Yousaf, PIEAS
#include <stdio.h>
void func1(void);
int main()
{
int count;
for (count = 0; count < 20; count++)
{
printf("At iteration %d: ", count);
func1();
}
getchar(); return 0;
}
void func1(void)
{
int x = 0;
int y = 0;
printf("x = %d, y = %dn", x, y);
x++;
y++;
}
Dr. Yousaf, PIEAS
• At iteration 0: x = 0, y = 0
• At iteration 1: x = 0, y = 0
• At iteration 2: x = 0, y = 0
• At iteration 3: x = 0, y = 0
• At iteration 4: x = 0, y = 0
• At iteration 5: x = 0, y = 0
• At iteration 6: x = 0, y = 0
• At iteration 7: x = 0, y = 0
• At iteration 8: x = 0, y = 0
• At iteration 9: x = 0, y = 0
• and so on
Scope of Variables
Dr. Yousaf, PIEAS
//Concept of local variables
#include <stdio.h>
void demo(void);
int main()
{
int x = 1, y = 2;
printf("nnBefore calling demo(), x = %d and y = %d", x, y); //x=1, y=2
demo();
printf("nnAfter calling demo(), x = %d and y = %dn", 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("nnWithin demo(), x = %d and y = %d", x, y); // x=88, y=89
}
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
#include <stdio.h>
void print_stars(int);
int main()
{
int i;
for (i= 0; i < 5; i++)
print_stars(5);
return 0;
}
void print_stars (int n)
{
int i;
for (i= 0; i < n; i++)
printf ("*");
printf ("n");
}
This program prints five rows of
five stars
This prints 'n' stars and then
a new line character
Loop around 5 times to
print the stars
*****
*****
*****
*****
*****
Variables here are LOCAL variables
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 nn", x); // x = 10
demo(x);
printf("in main, after demo x = %d nn", x); // x = 10
getchar(); return 0;
}
void demo (int x)
{
x = x+20;
printf("inside demo x= %d nn", 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 nn", x); // x = 10
demo();
printf("in main, after demo x = %d nn", x); // x = 30
getchar();
return 0;
}
void demo ()
{
x = x + 20; // x has not been declared in demo
printf("in demo x = %d nn", 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 nn", x); // x = 10
demo(x);
printf("in main, after demo x = %d nn", 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 nn", 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 nn", x); // x = 10
demo(x);
printf("nin main, after demo x = %d nn", 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 nn", x); // x = 30
} Dr. Yousaf, PIEAS
Example: Global Variable
Dr. Yousaf, PIEAS
#include <stdio.h>
float total = 0.0;
void caltot (float num1, float num2,
float num3); //declaration
void printtot ();
int main()
{
float x = 4.5, y = 3.7, z = 8.1;
caltot(x, y, z);
printtot();
printf(“Total is %fn”, total);
getchar();
return 0;
}
void caltot (float num1,
float num2, float num3)
{
total = num1 + num2 +
num3;
}
void printtot ()
{
printf(“Total is %fn”, total);
}
Example: Previous Example Without
Global Variable // Error
Dr. Yousaf, PIEAS
#include <stdio.h>
void caltot (float num1, float num2,
float num3); //declaration
void printtot ();
int main()
{
float x = 4.5, y = 3.7, z = 8.1;
float total = 0.0;
caltot(x, y, z);
printtot();
printf(“Total is %fn”, total);
getchar();
return 0;
}
void caltot (float num1,
float num2, float num3)
{
total = num1 + num2 +
num3; // error
}
void printtot ()
{
printf(“Total is %fn”, total);
// error
}
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

More Related Content

What's hot

Datastructures asignment
Datastructures asignmentDatastructures asignment
Datastructures asignment
sreekanth3dce
 

What's hot (20)

3. chapter ii
3. chapter ii3. chapter ii
3. chapter ii
 
C programms
C programmsC programms
C programms
 
C PROGRAMS
C PROGRAMSC PROGRAMS
C PROGRAMS
 
C programming
C programmingC programming
C programming
 
c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointers
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
C lab programs
C lab programsC lab programs
C lab programs
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
Array
ArrayArray
Array
 
SPL 6.1 | Advanced problems on Operators and Math.h function in C
SPL 6.1 | Advanced problems on Operators and Math.h function in CSPL 6.1 | Advanced problems on Operators and Math.h function in C
SPL 6.1 | Advanced problems on Operators and Math.h function in C
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shorting
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
C Prog - Array
C Prog - ArrayC Prog - Array
C Prog - Array
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
Fucntions & Pointers in C
Fucntions & Pointers in CFucntions & Pointers in C
Fucntions & Pointers in C
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
Double linked list
Double linked listDouble linked list
Double linked list
 
Datastructures asignment
Datastructures asignmentDatastructures asignment
Datastructures asignment
 

Similar to C Language Lecture 17

PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
amrit47
 
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESUnit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
LeahRachael
 

Similar to C Language Lecture 17 (20)

7 functions
7  functions7  functions
7 functions
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
C Language Lecture 16
C Language Lecture 16C Language Lecture 16
C Language Lecture 16
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
6. function
6. function6. function
6. function
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
C Language Lecture 5
C Language Lecture  5C Language Lecture  5
C Language Lecture 5
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
Array Cont
Array ContArray Cont
Array Cont
 
Functions
FunctionsFunctions
Functions
 
Assignment on Numerical Method C Code
Assignment on Numerical Method C CodeAssignment on Numerical Method C Code
Assignment on Numerical Method C Code
 
C Language Lecture 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
Functions
FunctionsFunctions
Functions
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESUnit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTES
 
C programs
C programsC programs
C programs
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
LAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAMLAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAM
 

More from Shahzaib Ajmal (16)

C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
C Language Lecture 20
C Language Lecture 20C Language Lecture 20
C Language Lecture 20
 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
 
C Language Lecture 14
C Language Lecture 14C Language Lecture 14
C Language Lecture 14
 
C Language Lecture 13
C Language Lecture 13C Language Lecture 13
C Language Lecture 13
 
C Language Lecture 12
C Language Lecture 12C Language Lecture 12
C Language Lecture 12
 
C Language Lecture 11
C Language Lecture  11C Language Lecture  11
C Language Lecture 11
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
C Language Lecture 9
C Language Lecture 9C Language Lecture 9
C Language Lecture 9
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
C Language Lecture 7
C Language Lecture 7C Language Lecture 7
C Language Lecture 7
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
C Language Lecture 4
C Language Lecture  4C Language Lecture  4
C Language Lecture 4
 
C Language Lecture 2
C Language Lecture  2C Language Lecture  2
C Language Lecture 2
 
C Language Lecture 1
C Language Lecture  1C Language Lecture  1
C Language Lecture 1
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

C Language Lecture 17

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 2. // Addition of two integers using //Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; } Dr. Yousaf, PIEAS
  • 3. // Addition of two integers using //Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); printf(“%d”, z) // Error getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; printf(“%d”, num1) // Error return z; } Dr. Yousaf, PIEAS Any variable declared in a function is not visible inside main and vice versa.
  • 4. Dr. Yousaf, PIEAS Example of Function // To determine the even or odd using // a function #include<stdio.h> void EvenOrOdd(int num); int main() { int num; printf("Enter a number to know even or oddn"); printf("Enter -100 to exitn"); while (1) { scanf("%d", &num); if (num == -100) break; EvenOrOdd(num); } printf("OK"); getchar(); return 0; } void EvenOrOdd(int num) { if(num%2==0) printf("Evenn"); else printf("Oddn"); }
  • 5. Dr. Yousaf, PIEAS Example of Function #include<stdio.h> void printLine(void) { printf("n*****************n"); } void main () { int num; printLine(); printf("Enter a Number :"); scanf("%d",&num); if(num%2==0) printf("Even Number"); else printf("Odd Number"); printLine(); getchar(); } Output ***************** Enter a Number :13 Odd Number *****************
  • 6. Returning a value using if else statement A single value is returned, however, multiple return statements can be used within a single function using “if-then-else” statement. Dr. Yousaf, PIEAS
  • 7. Dr. Yousaf, PIEAS // Returning a value and if else #include<stdio.h> int myfunc(int x, int y); int main() { int num1, num2, smaller; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); smaller = myfunc(num1, num2); printf("%d is smallern",smaller); getchar(); getchar(); return 0; } int myfunc(int x, int y) { if(x < y ) return x; else return y; }
  • 8. Home/Lab Assignments Write a function that returns the greater of the two numbers i.e. make a function that takes two integer arguments and returns the greater of the two. Write program to use this function. (Try Yourself) Write a function should accept two arguments i.e. length and width of the rectangle and should return the area of the rectangle, the prototype of the function is as under: float areaRect(float, float); (Try Yourself) Develop a function that accepts two values as length and width of a shape and returns 0 or 1. A 1 will be returned if the shape is a square otherwise a 0 will be returned. (Try Yourself). Dr. Yousaf, PIEAS
  • 9. Home/Lab Assignments A normal dice has 6 sides numbered from 1 to 6, when the dice is rolled the number on top side of the dice is considered to be the result of rolling the dice. Dices are used in many games etc. Your task is to write a function int rollDice(), the function should return an integer value ranging from 1 to 6, to make function return a random number each time use the library function rand() and srand() (. Write a program that allow the user to call this function multiple times , display the value returned by the function. (Try Yourself) Dr. Yousaf, PIEAS
  • 10. Pass by Value Versus Pass by Reference Dr. Yousaf, PIEAS
  • 11. // Addition of two integers using Function #include<stdio.h> int addnumbers(int x, int y); int main() { int num1, num2, add_result; printf("Enter first numbern"); scanf("%d", &num1); printf("Enter second numbern"); scanf("%d", &num2); add_result = addnumbers(num1, num2); printf("Addition result is %dn",add_result); getchar(); return 0; } int addnumbers(int x, int y) { int z; z = x +y; return z; } Dr. Yousaf, PIEAS Pass by Value
  • 12. Dr. Yousaf, PIEAS /* Passing arguments by value */ //Page Example 366 #include <stdio.h> void by_value(int x, int y, int z); int main() { int x = 2, y = 4, z = 6; printf("n Before calling by_value, x = %d, y = %d, z = %d.", x, y, z); by_value(x, y, z); printf("nn After calling by_value, x = %d, y = %d, z = %d.", x, y, z); getchar(); return(0); } void by_value(int x, int y, int z) { printf("nn Within function by_value, x = %d, y = %d, z = %d.", x, y, z); x = 0; y = 0; z = 0; printf("nn Again within function by_value , x = %d, y = %d, z = %d.", x, y, z); } Before calling by_value, x = 2, y = 4, z = 6. // Within function by_value, x = 2, y = 4, z = 6. // Again Within function by_value, x = 0, y = 0, z = 0. //After calling y_value(), x = 2, y = 4, z = 6. Pass by Value
  • 13. Calling Functions: Call by Value and Call by Reference • Used when invoking functions • Call by value – Copy of argument passed to function – Changes in function do not effect original – Use when function does not need to modify argument • Avoids accidental changes • Call by reference – Passes original argument – Changes in function effect original – Only used with trusted functions • At this stage, we focus on call by value • We will discuss call by reference later. Dr. Yousaf, PIEAS
  • 14. Parameters Passed by Value • Parameters passed by value!! – This means they are basically local variables initialized to the values that the function is called with. – They can be modified as you wish but these modifications will not be seen in the calling routine! #include<stdio.h> int twice(int x); int main() { int x=10,y; y=twice(x); printf("%d,%dn",x,y); getchar(); retun 0; } int twice(int x) { x=x+x; return x; } Dr. Yousaf, PIEAS
  • 15. Functions can Access Other Functions Dr. Yousaf, PIEAS
  • 16. Functions can access other functions Once you have written a function, it can be accessed from other functions. We can therefore build more complex functions from simpler functions Dr. Yousaf, PIEAS
  • 17. Dr. Yousaf, PIEAS // Function calling other function #include <stdio.h> float getavg(float x, float y, float z, int totnum); float calavg(float sum_res, int totalnum); int main() { float num1 = 3.5, num2 = 5.9, num3 = 1.7, avg; int totnumbers = 3; avg = getavg(num1,num2,num3,totnumbers); printf("Average is %fn",avg); getchar(); return 0; } float getavg(float x, float y, float z, int totnum) { float sum = x + y + z, average; average = calavg(sum, totnum); return average; } float calavg(float sum_res, int totalnum) { float avrg = sum_res/totalnum; return avrg; }
  • 18. Calling a function by Another Function void a(void) { printf(“Function a”); b(); } void b(void) { printf(“Function b”); } void main() { a(); b(); } Dr. Yousaf, PIEAS Can we call function b() inside function a() ? No, as function a() does not know anything about function b(). A function can call only those functions which are defined or declared before it.
  • 19. More discussion on input and output of Functions Dr. Yousaf, PIEAS
  • 20. // Calculate factorial without function #include<stdio.h> int main() { int i, fact, num1; printf("Enter a positive integern"); scanf("%d", &num1); fact = 1; for (i = num1; i >=1; i--) { fact = fact * i; } printf("Factorial of %d is %dn",num1, fact); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 21. Dr. Yousaf, PIEAS // Calculate factorial using //Functions #include<stdio.h> int cal_fac(int x); int main() { int i, fact, num1; printf("Enter a positive integren"); scanf("%d", &num1); fact = cal_fac(num1); printf("Factorial of %d is %dn",num1, fact); getchar(); return 0; } int cal_fac(int x) { int i, fact; fact = 1; if(x == 0) fact = 1; else { for (i = x; i >=1; i--) { fact = fact*i; } } return fact; }
  • 22. Dr. Yousaf, PIEAS /* demonstrates a function that does not take any arguments and does not provide output to main. */ #include <stdio.h> void stars (); //function declaration // (prototype) int main() { int x = 5, y = 13; stars (); //call to function x = x+10; y = x*x + (10/2); stars (); //call to function getchar(); return 0; } // function definition void stars () { int j; for(j=0; j < 10; j++) printf("*"); printf("n"); } Printing stars through a function
  • 23. Dr. Yousaf, PIEAS // demonstrates of passing //constants to a function #include <stdio.h> void stars (char ch, int n) ; int main() { int x = 5, y = 13, z; stars (‘%’, 7); //call to function x = x+10; y = x*x + (10/2); stars (‘$’, 18); //call to function z = x + y; return 0; } // function definition void stars (char ch, int n) { int j; for(j=0; j < n; j++) printf(“%c“, ch); printf("n"); } Printing any symbol any times
  • 24. Dr. Yousaf, PIEAS // demonstrates of passing values from //variables to a function #include <stdio.h> void stars (char ch, int n) ; int main() { char chp; int nt ; printf(“Please enter a symbol you want to printn”); chp = getchar(); printf(“Please enter the number of times you want to print the charactern”); scanf(“%d”, nt); stars (chp, nt); //call to function // Rest of the code here return 0; } // function definition void stars (char ch, int n) { int j; for(j=0; j < n; j++) printf(“%c“, ch); printf("n"); } Passing Variables
  • 25. Dr. Yousaf, PIEAS // Demonstration of missing arguments #include <stdio.h> void stars (char ch = ‘*’, int n = 10) ; int main() { char chp; int nt ; // Rest of the code 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 return 0; } // function definition void stars (char ch, int n) { int j; for(j=0; j < n; j++) printf(“%c“, ch); printf("n"); } Missing Arguments
  • 26. Returning a value from function Dr. Yousaf, PIEAS /* Program that will pass temperature in centigrade to a function that converts it into Fahrenheit and returns the value to the main function*/ #include <stdio.h> float ctof (float); //declaration int main() { float centi, farhen; printf("nEnter temperature in centigraden"); scanf("%f",&centi); farhen = ctof(centi); printf(“ %f Centigrade = %f Faherenheit”, centi, fahren); getchar(); return 0; } /* converts centigrade to Fahrenheit */ float ctof (float cgrade) { float fgrade; fgrade = (9/5)*cgrade+ 32.0; return fgrade; }
  • 27. 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
  • 28. // 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: %dn", 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
  • 29. Passing string to a function #include <stdio.h> void Display(char ch[]); int main() { char c[50]; printf("Enter string: "); gets(c); Display(c); // Passing string c to function. getchar(); return 0; } // Function definition void Display(char ch[]) // It will automatically fix its size { printf("String Output: "); puts(ch); } Dr. Yousaf, PIEAS
  • 30. #include <stdio.h> void func1(void); int main() { int count; for (count = 0; count < 20; count++) { printf("At iteration %d: ", count); func1(); } getchar(); return 0; } void func1(void) { int x = 0; int y = 0; printf("x = %d, y = %dn", x, y); x++; y++; } Dr. Yousaf, PIEAS • At iteration 0: x = 0, y = 0 • At iteration 1: x = 0, y = 0 • At iteration 2: x = 0, y = 0 • At iteration 3: x = 0, y = 0 • At iteration 4: x = 0, y = 0 • At iteration 5: x = 0, y = 0 • At iteration 6: x = 0, y = 0 • At iteration 7: x = 0, y = 0 • At iteration 8: x = 0, y = 0 • At iteration 9: x = 0, y = 0 • and so on
  • 31. Scope of Variables Dr. Yousaf, PIEAS
  • 32. //Concept of local variables #include <stdio.h> void demo(void); int main() { int x = 1, y = 2; printf("nnBefore calling demo(), x = %d and y = %d", x, y); //x=1, y=2 demo(); printf("nnAfter calling demo(), x = %d and y = %dn", 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("nnWithin demo(), x = %d and y = %d", x, y); // x=88, y=89 } Dr. Yousaf, PIEAS
  • 33. 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
  • 34. 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
  • 35. The print stars example #include <stdio.h> void print_stars(int); int main() { int i; for (i= 0; i < 5; i++) print_stars(5); return 0; } void print_stars (int n) { int i; for (i= 0; i < n; i++) printf ("*"); printf ("n"); } This program prints five rows of five stars This prints 'n' stars and then a new line character Loop around 5 times to print the stars ***** ***** ***** ***** ***** Variables here are LOCAL variables Dr. Yousaf, PIEAS
  • 36. Local and Global Variables Dr. Yousaf, PIEAS
  • 37. // 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 nn", x); // x = 10 demo(x); printf("in main, after demo x = %d nn", x); // x = 10 getchar(); return 0; } void demo (int x) { x = x+20; printf("inside demo x= %d nn", x); // x = 30 } • Dr. Yousaf, PIEAS
  • 38. // 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 nn", x); // x = 10 demo(); printf("in main, after demo x = %d nn", x); // x = 30 getchar(); return 0; } void demo () { x = x + 20; // x has not been declared in demo printf("in demo x = %d nn", x); // x = 30 } Dr. Yousaf, PIEAS
  • 39. 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
  • 40. // 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 nn", x); // x = 10 demo(x); printf("in main, after demo x = %d nn", 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 nn", x); // x = 30 } Dr. Yousaf, PIEAS
  • 41. // Still Local variable #include<stdio.h> void demo(int x); int x = 10; int main() { printf("nin main, before demo x = %d nn", x); // x = 10 demo(x); printf("nin main, after demo x = %d nn", 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 nn", x); // x = 30 } Dr. Yousaf, PIEAS
  • 42. Example: Global Variable Dr. Yousaf, PIEAS #include <stdio.h> float total = 0.0; void caltot (float num1, float num2, float num3); //declaration void printtot (); int main() { float x = 4.5, y = 3.7, z = 8.1; caltot(x, y, z); printtot(); printf(“Total is %fn”, total); getchar(); return 0; } void caltot (float num1, float num2, float num3) { total = num1 + num2 + num3; } void printtot () { printf(“Total is %fn”, total); }
  • 43. Example: Previous Example Without Global Variable // Error Dr. Yousaf, PIEAS #include <stdio.h> void caltot (float num1, float num2, float num3); //declaration void printtot (); int main() { float x = 4.5, y = 3.7, z = 8.1; float total = 0.0; caltot(x, y, z); printtot(); printf(“Total is %fn”, total); getchar(); return 0; } void caltot (float num1, float num2, float num3) { total = num1 + num2 + num3; // error } void printtot () { printf(“Total is %fn”, total); // error }
  • 44. 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
  • 45. 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
  • 46. 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
  • 47. 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