SlideShare a Scribd company logo
1 of 25
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
After studying the functions,
once again we discuss the
Anatomy of a C-Program
Dr. Yousaf, PIEAS
Anatomy of a C program
Dr. Yousaf, PIEAS
#include <stdio.h>
int main( )
{
int x, y, z;
x = 5;
y = 7;
z = x + y;
printf(“%d", z);
getchar();
return 0;
}
//Anatomy of a C Program
Lines that begin with a # in column 1 are
called preprocessor directives (commands).
• When we write our programs, including
libraries of functions help us that we do not
have to write the same code over and over.
• Example: the #include <stdio.h> directive
causes the preprocessor to include a copy
of the standard input/output header file
stdio.h at this point in the code.
• Some of the functions are very complex
and long. Not having to write them
ourselves make it easier and faster to write
programs.
Dr. Yousaf, PIEAS
Preprocessor Directives
#include <stdio.h>
#include <math.h>
#include <string.h>
• Lines that begin with a # in column 1 are called
preprocessor directives (commands).
• To access the functions which are stored in the library, it is
necessary to tell the compiler, about the file to be
accessed.
• These files contain information about some library
functions used in the program.
Dr. Yousaf, PIEAS
Preprocessor Directives
• # include Directive provides instructions to the
compiler to link (link section) function from the
system library.
• The #include directives “paste” the contents of
the files, e.g., stdio.h, math.h and string.h
into your source code, at the very place where the
directives appear.
• Syntax:-
#include<stdio.h>
stdio.h is header file.
Dr. Yousaf, PIEAS
Preprocessor Directives
• stdio stands for “standard I/O”, stdlib stands for
“standard library”, and string.h includes useful string
manipulation functions.
• #include<stdio.h> header file is included because it
contains information about the printf ( ) function that is
used in this program.
• This header file was included because it contains
information about the printf ( ) function that is used in
this program.
• printf function saves you from the complexity of writing
your own function of how to display text on the
computer screen.
• Hence you are more productive with the actual program
rather than worrying about such issues.
Dr. Yousaf, PIEAS
The printf() function
printf(“The values of x = %dn", x);
• printf() is a library function declared in
<stdio.h>
• Syntax: printf( FormatString, Expr,
Expr...)
– FormatString: String of text to print
– Exprs: Values to print
– FormatString has placeholders to show
where to put the values (note: #placeholders
should match #Exprs)
Dr. Yousaf, PIEAS
The printf() function
– Placeholders:
%d (print as integer),
%f (print as floating-point)
%s (print as string)
%c (print as char)
– n indicates a newline character
Make sure you pick
the right one!
Dr. Yousaf, PIEAS
#include <stdio.h>
int main( )
{
int x, y, z;
x = 5;
y = 7;
z = x + y;
printf(“%d", z);
getchar();
return 0;
}
//Anatomy of a C Program
Lines that begin with a # in column 1 are
called preprocessor directives (commands).
Main function
int main ( )
{
statement(s)
return 0;
}
Dr. Yousaf, PIEAS
The main() function
• Every ‘C’ program must have one main() function
section.
• main() is always the first function called in a
program execution.
• Every program must have a function called main.
This is where program execution begins.
Dr. Yousaf, PIEAS
The main() function
int main(void)
{ …
}
• The parentheses following the reserved word “main”
indicate that it is a function.
• void indicates that the function takes no arguments
• The reserved word “int” indicates that main() returns
an integer value.
Dr. Yousaf, PIEAS
Main() function section
“main” function basically serves as
the entry point of the core
program.
It contains two parts
1) Declaration part:
It declares all variables
used in the executable
part.
2) Executable part:
It has atleast one
statement.
#include <stdio.h>
#include "stdafx.h“
int main( )
{
int x, y, z;
x = 5;
y = 7;
z = x + y;
printf(“%d", z);
getchar();
return 0;
}
The Function Body
• A left brace { -- begins the body of
every function. A corresponding right
brace -- } -- ends the function body.
• The style is to place these braces on
separate lines in column 1 and to
indent the entire function body 3 to 5
spaces.
Dr. Yousaf, PIEAS
#include <stdio.h>
#include "stdafx.h“
int main( )
{
int x, y, z;
x = 5;
y = 7;
z = x + y;
printf(“%d", z);
getchar();
return 0;
}
return 0 ;
• Because function main() returns an integer value,
there must be a statement that indicates what this
value is.
• The statement
return 0 ;
indicates that main() returns a value of zero to the
operating system.
• A value of 0 indicates that the program execution
terminated successfully.
Dr. Yousaf, PIEAS
Hello World
#include <stdio.h>
/* My C program which prints Hello World */
int main ()
{
printf ("Hello World!n");
return 0;
}
Preprocessor directive
Library command
main() means “start here”
Comments are good
Return 0 from main means our program
finished without errorsBrackets
define code blocks
Dr. Yousaf, PIEAS
Comment Delimiters
• We can use // for a single line comment.
• We can use /* */ for single line as well as multiline
comments.
• These are called comment delimiters
Dr. Yousaf, PIEAS

More Related Content

What's hot (16)

Python basics
Python basicsPython basics
Python basics
 
Python advance
Python advancePython advance
Python advance
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Pointer to function 2
Pointer to function 2Pointer to function 2
Pointer to function 2
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
Python basics
Python basicsPython basics
Python basics
 
Functions
FunctionsFunctions
Functions
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 

Similar to Add Two Integers Using Functions

Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The BasicsRanel Padon
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4MKalpanaDevi
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
headerfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdfheaderfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdfjazzcashlimit
 

Similar to Add Two Integers Using Functions (20)

CHAPTER 6
CHAPTER 6CHAPTER 6
CHAPTER 6
 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
C function
C functionC function
C function
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
Function
FunctionFunction
Function
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
C programming
C programmingC programming
C programming
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Header files in c
Header files in cHeader files in c
Header files in c
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Array Cont
Array ContArray Cont
Array Cont
 
headerfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdfheaderfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdf
 

More from Shahzaib Ajmal

More from Shahzaib Ajmal (18)

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 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
C Language Lecture 18
C Language Lecture 18C Language Lecture 18
C Language Lecture 18
 
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 5
C Language Lecture  5C Language Lecture  5
C Language Lecture 5
 
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

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 

Recently uploaded (20)

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 

Add Two Integers Using Functions

  • 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. After studying the functions, once again we discuss the Anatomy of a C-Program Dr. Yousaf, PIEAS
  • 11. Anatomy of a C program Dr. Yousaf, PIEAS
  • 12. #include <stdio.h> int main( ) { int x, y, z; x = 5; y = 7; z = x + y; printf(“%d", z); getchar(); return 0; } //Anatomy of a C Program Lines that begin with a # in column 1 are called preprocessor directives (commands). • When we write our programs, including libraries of functions help us that we do not have to write the same code over and over. • Example: the #include <stdio.h> directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code. • Some of the functions are very complex and long. Not having to write them ourselves make it easier and faster to write programs. Dr. Yousaf, PIEAS
  • 13. Preprocessor Directives #include <stdio.h> #include <math.h> #include <string.h> • Lines that begin with a # in column 1 are called preprocessor directives (commands). • To access the functions which are stored in the library, it is necessary to tell the compiler, about the file to be accessed. • These files contain information about some library functions used in the program. Dr. Yousaf, PIEAS
  • 14. Preprocessor Directives • # include Directive provides instructions to the compiler to link (link section) function from the system library. • The #include directives “paste” the contents of the files, e.g., stdio.h, math.h and string.h into your source code, at the very place where the directives appear. • Syntax:- #include<stdio.h> stdio.h is header file. Dr. Yousaf, PIEAS
  • 15. Preprocessor Directives • stdio stands for “standard I/O”, stdlib stands for “standard library”, and string.h includes useful string manipulation functions. • #include<stdio.h> header file is included because it contains information about the printf ( ) function that is used in this program. • This header file was included because it contains information about the printf ( ) function that is used in this program. • printf function saves you from the complexity of writing your own function of how to display text on the computer screen. • Hence you are more productive with the actual program rather than worrying about such issues. Dr. Yousaf, PIEAS
  • 16. The printf() function printf(“The values of x = %dn", x); • printf() is a library function declared in <stdio.h> • Syntax: printf( FormatString, Expr, Expr...) – FormatString: String of text to print – Exprs: Values to print – FormatString has placeholders to show where to put the values (note: #placeholders should match #Exprs) Dr. Yousaf, PIEAS
  • 17. The printf() function – Placeholders: %d (print as integer), %f (print as floating-point) %s (print as string) %c (print as char) – n indicates a newline character Make sure you pick the right one! Dr. Yousaf, PIEAS
  • 18. #include <stdio.h> int main( ) { int x, y, z; x = 5; y = 7; z = x + y; printf(“%d", z); getchar(); return 0; } //Anatomy of a C Program Lines that begin with a # in column 1 are called preprocessor directives (commands). Main function int main ( ) { statement(s) return 0; } Dr. Yousaf, PIEAS
  • 19. The main() function • Every ‘C’ program must have one main() function section. • main() is always the first function called in a program execution. • Every program must have a function called main. This is where program execution begins. Dr. Yousaf, PIEAS
  • 20. The main() function int main(void) { … } • The parentheses following the reserved word “main” indicate that it is a function. • void indicates that the function takes no arguments • The reserved word “int” indicates that main() returns an integer value. Dr. Yousaf, PIEAS
  • 21. Main() function section “main” function basically serves as the entry point of the core program. It contains two parts 1) Declaration part: It declares all variables used in the executable part. 2) Executable part: It has atleast one statement. #include <stdio.h> #include "stdafx.h“ int main( ) { int x, y, z; x = 5; y = 7; z = x + y; printf(“%d", z); getchar(); return 0; }
  • 22. The Function Body • A left brace { -- begins the body of every function. A corresponding right brace -- } -- ends the function body. • The style is to place these braces on separate lines in column 1 and to indent the entire function body 3 to 5 spaces. Dr. Yousaf, PIEAS #include <stdio.h> #include "stdafx.h“ int main( ) { int x, y, z; x = 5; y = 7; z = x + y; printf(“%d", z); getchar(); return 0; }
  • 23. return 0 ; • Because function main() returns an integer value, there must be a statement that indicates what this value is. • The statement return 0 ; indicates that main() returns a value of zero to the operating system. • A value of 0 indicates that the program execution terminated successfully. Dr. Yousaf, PIEAS
  • 24. Hello World #include <stdio.h> /* My C program which prints Hello World */ int main () { printf ("Hello World!n"); return 0; } Preprocessor directive Library command main() means “start here” Comments are good Return 0 from main means our program finished without errorsBrackets define code blocks Dr. Yousaf, PIEAS
  • 25. Comment Delimiters • We can use // for a single line comment. • We can use /* */ for single line as well as multiline comments. • These are called comment delimiters Dr. Yousaf, PIEAS