- Functions allow programmers to split code into separate reusable segments that each perform a specific task. The document discusses different types of functions including user-defined and library functions.
- Key aspects of functions like function definitions, declarations, parameters, return values, and calling functions are explained. Different ways of passing data to functions like passing arrays and strings are also covered.
- The document provides examples to illustrate concepts like passing arguments by value versus reference and categorizing functions based on their use of arguments and return values.
Introduction of arrays, Declaration of array, Initialization of array, Sorting, Multidimensional array. Some code examples that will make you clear about the concept of arrays.
https://github.com/ashim888/csit-c
An operator is a symbol designed to operate on data.
They can be a single symbol, di-graphs, tri-graphs or keywords.
Operators can be classified in different ways.
This is similar to function overloading
Introduction of arrays, Declaration of array, Initialization of array, Sorting, Multidimensional array. Some code examples that will make you clear about the concept of arrays.
https://github.com/ashim888/csit-c
An operator is a symbol designed to operate on data.
They can be a single symbol, di-graphs, tri-graphs or keywords.
Operators can be classified in different ways.
This is similar to function overloading
Branching, Looping, Conditional Statement, Exit function, Difference between break and exit. Some of the codes and some of the branching techniques are covered in this unit. Check conditional statement looping and exit functions too
https://github.com/ashim888/csit-c
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
Branching, Looping, Conditional Statement, Exit function, Difference between break and exit. Some of the codes and some of the branching techniques are covered in this unit. Check conditional statement looping and exit functions too
https://github.com/ashim888/csit-c
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
Introduction, Array of structure, Passing structure to function, Passing array of structure to function, Structure within structure ( Nested Structure), Union, Pointer to structure
Introduction, The & and * operator, Declaration of pointer, Pointer to pointer, Pointer arithmetic, Pointer and array, Pointer with multidimensional array, Pointer and strings, Array of pointer with string, Dynamic memory allocation.
For all who wish to learn c graphics programming, no knowledge of graphics concepts is required. C Graphics programming is very easy and interesting. You can use graphics programming for developing your own games, in making projects, for animation etc. It's not like traditional C programming in which you have to apply complex logic in your program and then you end up with a lot of errors and warnings in your program. In C graphics programming you have to use standard library functions ( need not worry if you don't know functions ) to get your task done. Just you pass arguments to the functions and it's done. On this website you will find almost all functions with detailed explanation and a sample program showing the usage of a function. To make things easy you are provided with executable files which you can download and execute. Firstly you should know the function initgraph which is used to initialize the graphics mode . To initialize graphics mode we use initgraph function in our program. initgraph function is present in "graphics.h" header file, so your every graphics program should include "graphics.h" header file. We will discuss initgraph withe help of following sample program:-
C Tokens, Escape sequence, Delimiters, Variables, Data types, Constants/ Literals, Expressions, Statements and Comments
https://github.com/ashim888/csit-c
Concept of file, Opening and closing of file, Modes, Input/ output function, Random access in file, Printing a file
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.....
a. Concept and Definition
b. Binary Tree
c. Introduction and application
d. Operation
e. Types of Binary Tree
• Complete
• Strictly
• Almost Complete
f. Huffman algorithm
g. Binary Search Tree
• Insertion
• Deletion
• Searching
h. Tree Traversal
• Pre-order traversal
• In-order traversal
• Post-order traversal
Slides at myblog
http://www.ashimlamichhane.com.np/2016/07/tree-slide-for-data-structure-and-algorithm/
Assignments at github
https://github.com/ashim888/dataStructureAndAlgorithm/tree/dev/Assignments/assignment_7
a. Concept and Definition✓
b. Inserting and Deleting nodes ✓
c. Linked implementation of a stack (PUSH/POP) ✓
d. Linked implementation of a queue (Insert/Remove) ✓
e. Circular List
• Stack as a circular list (PUSH/POP) ✓
• Queue as a circular list (Insert/Remove) ✓
f. Doubly Linked List (Insert/Remove) ✓
For more course related material:
https://github.com/ashim888/dataStructureAndAlgorithm/
Personal blog
www.ashimlamichhane.com.np
Queues
a. Concept and Definition
b. Queue as an ADT
c. Implementation of Insert and Delete operation of:
• Linear Queue
• Circular Queue
For More:
https://github.com/ashim888/dataStructureAndAlgorithm
http://www.ashimlamichhane.com.np/
https://github.com/ashim888/dataStructureAndAlgorithm
Stack
Concept and Definition
• Primitive Operations
• Stack as an ADT
• Implementing PUSH and POP operation
• Testing for overflow and underflow conditions
Recursion
• Concept and Definition
• Implementation of:
¬ Multiplication of Natural Numbers
¬ Factorial
¬ Fibonacci Sequences
The Tower of Hanoi
Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. Big O specifically describes the worst-case scenario, and can be used to describe the execution time required or the space used (e.g. in memory or on disk) by an algorithm.
For further information
https://github.com/ashim888/dataStructureAndAlgorithm
References:
https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation
http://web.mit.edu/16.070/www/lecture/big_o.pdf
https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/
https://justin.abrah.ms/computer-science/big-o-notation-explained.html
Concept and Definition of Data Structures
Introduction to Data Structures: Information and its meaning, Array in C++: The array as an ADT, Using one dimensional array, Two dimensional array, Multi dimensional array, Structure , Union, Classes in C++.
https://github.com/ashim888/dataStructureAndAlgorithm
Problem analysis, Algorithms and Flowchart, Coding, Compilation and Execution, History of C, Structure of C program, Debugging, Testing and Documentation
https://github.com/ashim888/csit-c
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
2. • A function is a group of statements that together perform a task.
• Every C program has at least one function, which is main(), and all the
most trivial programs can define additional functions.
• You can divide up your code into separate functions.
• How you divide up your code among different functions is up to you,
but logically the division is such that each function performs a specific
task.
2/29/2016 Ashim Lamichhane 2
3. • Suppose a program where a set of operations has to be repeated
often, though not continuously.
• Loops seems like a better option.
• Instead of inserting the program statements for these operations at so
many places, a separate program segment is written and compiled it
separately.
• As many times as it is needed, the segment program is called.
• The separate program segment is called a function.
2/29/2016 Ashim Lamichhane 3
4. • Suppose we have to calculate a nCr
nCr = n!/(n-r)!r!
• Without using function:
for(i=1;i<=n;i++){
f1*=1;
}
for(i=1;i<=(n-r);i++){
f2*=1;
}
for(i=1;i<=r;i++){
f3*=1;
}
comb=f1/(f2*f3);
2/29/2016 Ashim Lamichhane 4
5. Advantages of Function
• Manageability
• Easier to write and keep track of.
• Easier to understand and maintain
• Code Reusability
• Can be used multiple times
• Non-redundant programming
• Same function can be called when needed.
• Logical Clarity
• Reduced number of code in main function.
• Easy to divide the work to many different programmers.
• Large work can be divided by writing different functions.
2/29/2016 Ashim Lamichhane 5
6. • The C Functions can be classified into two categories:
1. User defined function
2. Library Functions
2/29/2016 Ashim Lamichhane 6
7. Library functions (Built-in functions)
• These are the functions which are already written, compiled and
placed in C library and they are not required to be written by a
programmer.
• The function’s name, its return type, their argument number and types
have been already defined.
• We can use these functions as required.
• Ex: printf(), scanf(), sqrt(), getch() are example of library functions.
2/29/2016 Ashim Lamichhane 7
8. User – defined functions
• These are functions which are defined by user at the time of writing a
program.
• The user has choice to choose its name, return type, arguments and
their types.
• The job of each user-defined function is as defined by the user
• A complex C problem can be divided into a number of user-defined
functions.
2/29/2016 Ashim Lamichhane 8
9. main() function
• The function main() is an user defined function except that the name
of function is defined or fixed by the language.
• The return type, argument and body of the function are defined by the
programmer as required.
• The function is executed first, when the program starts execution.
2/29/2016 Ashim Lamichhane 9
10. Components associated with function
• Function Definition
• Function declaration or prototype
• Return Statement
• Accessing/Calling a function
2/29/2016 Ashim Lamichhane 10
11. Function definition
• The collection of program statements that describes the specific task to be
done by the function is called function definition.
• It consists of function header, which defines function’s name, its
return type and its argument list and a function body, which is
a block of code enclosed in parenthesis.
• Syntax:
return_type function_name(data_type variable1, data_type variable2,…..) {
…...
statements;
.....
}
2/29/2016 Ashim Lamichhane 11
12. All the parts of a function
• Return Type:
• A function may return a value.
• The return_type is the data type of the value the function returns.
• Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
• Function Name
• This is the actual name of the function.
• The function name and the parameter list together constitute the function
signature.
2/29/2016 Ashim Lamichhane 12
13. • Parameters (data_type variable1, data_type variable2,….. )
• A parameter is like a placeholder.
• When a function is invoked, you pass a value to the parameter.
• This value is referred to as actual parameter or argument.
• The parameter list refers to the type, order, and number of the parameters of a
function.
• Parameters are optional; that is, a function may contain no parameters.
• Function Body
• The function body contains a collection of statements that define what the
function does.
2/29/2016 Ashim Lamichhane 13
14. int add(int a,int b){ //function header
int sum; // function body (statements)
sum=a+b; // function body (statements)
return sum; // returns value of sum to whoever called
}
----------------------------------------------------------------------------------------------
float areaOfCircle(float radius){ //function header
return 3.1428*radius*radius; // returns radius to whoever called
}
2/29/2016 Ashim Lamichhane 14
15. Function Declaration or Prototype
• The function declaration or prototype is model or blueprint of the
function.
• If functions are used before they are defined, then function
declaration or prototype is necessary which provides the following
information to the compiler
• The name of the function
• The type of the value returned by the function
• The number and the type of arguments that must be supplied when calling the
function.
2/29/2016 Ashim Lamichhane 15
16. Function Declaration or Prototype (cont…)
• A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
• A function declaration has the following parts −
return_type function_name( parameter list );
• For the above defined function add(),the function declaration is as follows−
int add(int num1, int num2);
float areaOfCircle(float radius);
int max(int n1,int n2);
2/29/2016 Ashim Lamichhane 16
17. Return Statement
• It is the statement that is executed just before the function completes
its job and control is transferred back to the calling function.
• The job of return statement is to hand over some value given by
function body to the point where the call was made.
• Two purposes of return statement:
• Immediately transfer the control back to the calling program
• It returns the value to the calling function.
• SYNTAX:
return (expression);
• A function may or may not return a value. If a function doesn't return
a value the return type in the function definition and declaration is
specified as void.
2/29/2016 Ashim Lamichhane 17
18. Accessing/Calling a function
• A function can be called or accessed by specifying its name, followed by a
list of arguments enclosed in parenthesis and separated by commas.
• Ex:
• a function add() with two arguments is called by add(a,b) to add two numbers.
• If function call doesn’t require any arguments any empty pair of parenthesis must
follow the name of function.
• General Form:
• If function has parameters but it doesn’t return value
• function_name(variable1, variable2…);
• If function has no arguments and it doesn’t return value
• function_name();
• If function has parameters but it returns value
• variable_name=function_name(variable1, variable2…);
• If function has no arguments and it does return value
• variable_name=function_name();
2/29/2016 Ashim Lamichhane 18
19. /* function definition of add() function which takes two
integers and returns sum of them as integer */
#include <stdio.h>
int add(int a,int b){
int sum;
sum=a+b;
return sum;
}
float areaOfCircle(float radius){
return 3.1428*radius*radius;
}
int main(void){
int a,b,mysum; float myfloat;
printf("Enter two numbersn");
scanf("%d%d",&a,&b);
mysum=add(a,b);
printf("VALUE: %dn", mysum);
myfloat=areaOfCircle(mysum);
printf("So area of circle is: %fn",myfloat );
}
/* function definition of add() function which takes two integers and returns
sum of them as integer */
#include <stdio.h>
int add(int , int ); // Int add(int a, int b);
float areaOfCircle(float ) //float areaOfCircle(float r)
int main(void){
int a,b,mysum; float myfloat;
printf("Enter two numbersn");
scanf("%d%d",&a,&b);
mysum=add(a,b);
printf("VALUE: %dn", mysum);
myfloat=areaOfCircle(mysum);
printf("So area of circle is: %fn",myfloat );
}
int add(int a,int b){
int sum;
sum=a+b;
return sum;
}
float areaOfCircle(float radius){
return 3.1428*radius*radius;
}
2/29/2016 Ashim Lamichhane 19
20. Question
• Define a function whatIsYourName() which asks for your and returns
your name to main function and you print that name in the main
function.
• Define a function myPercentage() which calculates the percentage of
the marks in two subjects and marksGotInExams() asks for marks in
two subjects and returns your marks and percentage to the main
function.
2/29/2016 Ashim Lamichhane 20
21. #include <stdio.h>
int total(float a,float b){
return a+b;
}
float percentage(float total){
return total/2;
}
int main(void){
float a,b,mysum;
float myfloat;
printf("Enter marks in two subjects: n");
scanf("%f%f",&a,&b);
mysum=total(a,b);
printf("My total in two subjects: %.2fn", mysum);
myfloat=percentage(mysum);
printf("My percentage is: %.2f n",myfloat );
}
2/29/2016 Ashim Lamichhane 21
22. Category of functions according to the return value and arguments
• Category 1: Functions with no arguments and no return values
• Category 2: Functions with arguments and no return values
• Category 3: Function with arguments and return values
2/29/2016 Ashim Lamichhane 22
23. Category 1: Functions with no arguments and no return values
• When function has no arguments, it does not receive any data from
the calling function.
• Similarly when it doesn’t return a value, the calling function does not
receive any data from the called function.
• Thus, in such type of function’s there is no data transfer between the
calling function and the called function.
2/29/2016 Ashim Lamichhane 23
24. void function_name()
{
/* body of function */
}
• Keyword void means the function doesn’t return any value.
• There is no arguments within parenthesis which implies function has
no argument and it doesn’t receive any data from the called function.
2/29/2016 Ashim Lamichhane 24
25. Ex:
void addition(){
Int a,b,sum;
Printf(“enter any two numbers: t”);
Scanf(“%d%d”,&a,&b);
sum=a+b;
Printf(“n the sum is : t”,sum);
}
void main(){
clrscr();
addition();
getch();
}
2/29/2016 Ashim Lamichhane 25
26. Category 2: functions with arguments but no return value
void function_name(argument list)
{
Body of a function
}
• We pass arguments while calling a function but nothing is returned to
the calling function from.
2/29/2016 Ashim Lamichhane 26
27. Ex:
void addition(int a,int b){
int sum=0;
sum=a+b;
printf(“n the sum is : t”,sum);
}
void main(){
int a ,b;
clrscr();
printf(“enter any two numbers: t”);
Scanf(“%d%d”,&a,&b);
addition(a,b);
getch();
}
2/29/2016 Ashim Lamichhane 27
28. Category 3: Function with arguments and return values
• We pass arguments
• We expect a return value
return_type function_name(argument_list)
{
/* Body of the function */
return something;
}
2/29/2016 Ashim Lamichhane 28
29. Ex:
int addition(int a,int b){
int sum=0;
sum=a+b;
return sum;
}
void main(){
int a ,b,sum;
clrscr();
printf(“enter any two numbers: t”);
scanf(“%d%d”,&a,&b);
sum=addition(a,b);
printf(“n the sum is : ”,sum);
getch();
}
2/29/2016 Ashim Lamichhane 29
30. Passing arrays to function
• It is possible to pass the value of an array element and even an entire
array as an argument to a function.
• To pass an entire array to a function, the array name must appear by
itself, without brackets or subscripts, as an actual argument in
function call statement.
• When declaring a one-dimensional array as a formal argument, the
array name is written with a pair of empty square brackets. The size
of the array is not specified within the formal argument declaration.
Ashim Lamichhane 302/29/2016
31. • Syntax for function call passing array as argument,
function_name(array_name)
• Syntax for function prototype which accepts array
return_type function_name(data_type array_name[]);
Or
return_type function_name(data_type *pointer_variable);
• When array is passed to a function, the values of the array elements are not
passed to the function rather the array name is interpreted as the address
of the first array element.
• The address assigned to the corresponding formal argument when the
function is called.
• The formal argument therefore becomes a pointer to the first array
element.
Ashim Lamichhane 312/29/2016
32. #include <stdio.h>
void display(int n){
printf("%dt", n );
}
int main(void){
int nums[5]={100,23,44,3,65},i;
printf("nThe content of array is: n");
for (int i = 0; i < 5; i++){
display(nums[i]);
}
}
Ashim Lamichhane 322/29/2016
33. WAP to illustrate passing an entire array to a function
#include <stdio.h>
void change(int a[]){
a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50;
}
int main(void){
int nums[5]={100,23,44,3,65},i;
printf("nBEFORE FUNCTION CALL: n");
for (int i = 0; i < 5; i++) {
printf("t%d",nums[i]);
}
printf("n");
change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */
printf("nAFTER FUNCTION CALLn");
for (int i = 0; i < 5; i++) {
printf("t%d",nums[i]);
} printf("n");
}
Ashim Lamichhane 332/29/2016
34. Passing Strings to Functions
#include <stdio.h>
void Display(char ch[]);
int main(){
char c[50];
printf("Enter string: ");
gets(c);
Display(c); // Passing string c to function.
return 0;
}
void Display(char ch[]){
printf("String Output: ");
puts(ch);
}
• Here, string c is passed from main() function to user-defined function Display(). In function
declaration, ch[] is the formal argument.
Ashim Lamichhane 342/29/2016
35. Different types of function call
• The arguments in function can be passed in two ways:
• Pass arguments by value
• Pass arguments by address or reference or points
2/29/2016 Ashim Lamichhane 35
36. Function call by Value (Pass arguments by value)
• When values of actual arguments are passed to the function as
arguments, its known as function call by value.
• In this call, the value of each actual argument is copied into
corresponding formal argument of the function definition.
2/29/2016 Ashim Lamichhane 36
37. /* A program to illustrate function call by value */
#include <stdio.h>
void swap(int, int);
/* function prototype */
int main(void){
int a=99,b=98;
printf("BEFORE function calling a and b are: %d t %dn",a,b);
swap(a,b); /* function call by value */
printf("After calling function, a and b are: %dt %dn",a,b );
}
void swap(int x, int y){
int temp;
temp=x;
x=y;
y=temp;
printf("The values within functions are %dt%dn",x,y);
}
2/29/2016 Ashim Lamichhane 37
38. #include <stdio.h>
void swap(int x, int y); /* function declaration */
int main () {
int a = 100; int b = 200; /* local variable definition */
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
swap(a, b); /* calling a function to swap the values */
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
/* function definition to swap the values */
void swap(int x, int y) {
int temp; temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
2/29/2016 Ashim Lamichhane 38
39. Function Call by Reference (Pass argument by address)
• In this type of function call, the address of variable is passed as an argument instead of
actual value of variable.
• Using this method, the original values are changed if they are changed within the function
• We need pointer for this. Detail study of pointer will be on next unit.
• Pointer: a pointer is a variable that stores a memory address of a variable.
• Pointer is declared in the same fashion like other variables but is always preceded by ‘*’
(asterisk) operator.
Ex. int *a; float *b; char *c;
• Here a,b and c are pointer variables which stores address of integer, float and char
variables
2/29/2016 Ashim Lamichhane 39
40. int *a; float *b ; char *c;
int x; float y; char z;
/* now we can do */
a=&x; /* the address of x is assigned to pointer variable a */
b=&y; /* the address of float variable y is stored in pointer variable b */
c=&z; /* the address of char variable z is stored in pointer variable c */
2/29/2016 Ashim Lamichhane 40
41. WAP to swap the values of two variables using call by reference
void swap(int *,int *);
void main(){
int a=99,b=98;
printf("BEFORE function calling a and b are: %d t %dn",a,b);
swap(&a,&b); /* function call by reference*/
printf("After calling function, a and b are: %dt %dn",a,b );
}
void swap(int *x, int *y){
int temp;
temp=*x;
*x=*y;
*y=temp;
}
2/29/2016 Ashim Lamichhane 41
42. #include <stdio.h>
void swap(int *x, int *y); /* function declaration */
int main () {
int a = 100; int b = 200; /* local variable definition */
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values.
&a indicates pointer to a ie. address of variable a and
&b indicates pointer to b ie. address of variable b. */
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
void swap(int *x, int *y) { /* function definition to swap the values */
int temp; temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
2/29/2016 Ashim Lamichhane 42
43. Recursive function
• A recursive function is one which calls itself.
• Recursive functions are useful in evaluating certain types of
mathematical function.
• The function is called recursive function if it calls to itself and
recursion is a process by which a function calls itself repeatedly until
some specified condition is satisfied.
2/29/2016 Ashim Lamichhane 43
44. Recursive function
• To solve a problem using recursive method, two conditions must be
satisfied. They are:
• Problem could be written or defined in term of its previous
result.
• Problem statement must include a stopping condition i.e. we
must have an if statement somewhere to force the
function to return without the recursive call being executed,
otherwise the function will never return.
2/29/2016 Ashim Lamichhane 44
45. Ex: Suppose you have numbers from 0 to 9 and you need to calculate the sum of
these numbers in the following way :
• you can see that we start with 0 and 1
• sum them up and add the result into next
number ie 2
• then again we add this result to 3 and continue
like this.
• Now lets see the code….
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15
15 + 6 = 21
21 + 7 =28
28 + 8 = 36
36 + 9 = 45
2/29/2016 Ashim Lamichhane 45
46. #include <stdio.h>
int count = 1;
void func(int sum) {
sum = sum + count;
count ++;
if(count <=9){
func(sum);
} else {
printf("nSum is [%d] n", sum);
} return;
}
int main(void) {
int sum = 0;
func(sum);
return 0;
}
Explanation
• When func() was called through main(), ‘sum’
was zero.
• For every call to func(), the value of ‘sum’ is
incremented with ‘count’ (which is 1 initially),
which itself gets incremented with every call.
• The condition of termination of this recursion
is when value of ‘count’ exceeds 9. This is
exactly what we expect.
• When ‘count’ exceeds 9, at this very moment,
the value of ‘sum’ is the final figure that we
want and hence the solution.
2/29/2016 Ashim Lamichhane 46
47. #include <stdio.h>
int func(int num) {
int res = 0;
if(num <= 0){
printf("n Error n");
}else if(num ==1){
return num;
}else {
res = num * func(num -1);
return res;
}
return 0;
}
int main(void) {
int num = 5 ;
int fact = func(num);
if (fact > 0)
printf("n The factorial of [%d] is [%d]n", num, fact);
return 0;
}
• res = 5 * func(5 -1); // This is func() stack 1
• res = 4 *func(4-1); // This is func() stack 2
• res = 3 *func(4-1); // This is func() stack 3
• res = 2 *func(2-1); // This is func() stack 4
• return 1; // This is func() stack 5
Take an example of sum
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
2/29/2016 Ashim Lamichhane 47
48. WAP a program to find the factorial of a number using recursive
method
#include <stdio.h>
long int factorial(int i) {
if(i <= 1)
return 1;
else
return i * factorial(i - 1);
}
int main() {
int i = 5;
printf("Factorial of %d is %dn", i, factorial(i));
return 0;
}
5!
5*4!
5*4*3!
5*4*3*2!
5*4*3*2*1!
5*4*3*2*1
2/29/2016 Ashim Lamichhane 48
49. Recursion Iteration
A function is called from the definition of the same
function to do repeated task.
Loop is used to do repeated task
Recursion is a top-down approach to problem solving;
it divides the problem into pieces
Iterations is like a bottom-up approach; it begins with
what is known and from this it constructs the solution
step by step
In recursion, a function calls to itself until some
condition will be satisfied
In iteration, a function does not call to itself.
Problem could be written or defined in term of its
previous result to solve a problem using recursion
It is not necessary to define a problem in term of its
previous result to solve using iteration
All problems can not be solved using recursion All problems can be solved using iteration
2/29/2016 Ashim Lamichhane 49
50. Types of variables
• Local variable (automatic or internal variable)
• Global variables(External)
• Static variables
• Register variables
2/29/2016 Ashim Lamichhane 50
51. Local variables (automatic or internal)
• Are always declared within a function or block.
• Are local to the particular function or block in which they are declared.
• Other functions cannot access these variables.
• Compiler shows errors in case other functions try to access the variables.
• Are created when the function is called and destroyed automatically when the
function is exited.
• Scopeof a variable can be defined as the region over which the variable is
visible or valid
2/29/2016 Ashim Lamichhane 51
52. long int fact(int n){
int i;
long int f=1;
for(i=1; i<=n;i++){
f*=1;
return f;
}
void main(){
Int num=5;
printf(“factorial of %d is %ld”,num,f);
getch()
}
• here the variables n, i and f are local to function
fact() and are unknown to main()
function.
• Similarly num is local variable to the function
main() and unknown to the function fact()
2/29/2016 Ashim Lamichhane 52
53. Global variables (External)
• Variables that are both alive and active throughout the entire program.
• These are declared outside any block or function
• Can be accessed by any function in the program
• The scope is global. i.e within the program
• The life time is as long as the program execution doesn’t come to an
end.
2/29/2016 Ashim Lamichhane 53
54. int roll;
float marks;
main(){
…..;
…..;
…..;
}
func1(){
…..;
…..;
…..;
}
int a=10;
Void fun(){
a=20;
printf(“%d”,a++);
}
Void main(){
printf(“%d”,a);
fun();
printf(“%d”,a)
}
OUTPUT:
10
20
21
• Here, a is global variable and
is recognized within main() as
well as user-defined function
fun() and can be used
anywhere in the program.
2/29/2016 Ashim Lamichhane 54
55. Static variable
• Static variable can only be accessed from the function in which it is declared, just
like local variable.
• The static variable is not destroyed on exit from the function; instead its value is
preserved and becomes available again when the function is next called.
• Eg. static int counter;
• Can be initialized as normal variable.
• Its scope is local to the block in which the variable is defined.
• Its lifetime is global i.e. its value persists between different function calls.
2/29/2016 Ashim Lamichhane 55
57. Register Variable
• Register variables are special case of automatic variables.
• Accessing data in memory is considerably slower than processing in the CPU.
• Computes often have small amounts of storage within the CPU itself where data can be
stored and accessed quickly.
• These storage cells are called registers.
• C provides storage class register for some variables to be allocated to CPU registers , if
possible.
• Thus register variables provide a certain control over efficiency of program execution.
2/29/2016 Ashim Lamichhane 57
58. Register Variable
• Variables which are used repeatedly or whose access times are critical
may be declared to be of storage register.
• It behaves just like automatic variables.
• They are allocated storage upon entry to a block and the storage is
freed when the block is exited.
• Scope of register variable is local to the block in which they are
declared.
2/29/2016 Ashim Lamichhane 58
59. #include<stdio.h>
int main() {
int num1,num2;
register int sum;
printf("nEnter the Number 1 : ");
scanf("%d",&num1);
printf("nEnter the Number 2 : ");
scanf("%d",&num2);
sum = num1 + num2;
printf("nSum of Numbers : %d",sum);
return(0);
}
2/29/2016 Ashim Lamichhane 59
60. Difference between local, global and static variables
Local Variables Global Variables Static Variables
The variables are declared within
function or blocks. The scope is
only within the function or block in
which they are defined
Global variables are defined
outside the functions so that their
scope is throughout the program
Static variables are special case of
local variables. Thus, static
variables are also defined inside
the functions or blocks
The initial value is unpredictable or
garbage value.
The initial value is zero The initial value is zero
The life time is till the control
remains within the block or
function in which the variable is
defined. The variable is destroyed
when function returns to the
calling function or block ends
The life time is till programs
execution doesn't come to an i.e.
variables are created when
program starts and destroyed when
program ends.
Its value persists between different
function calls. Thus life time is
same as global variables.
The keyword auto is used The keyword extern is used The keyword static is used.
2/29/2016 Ashim Lamichhane 60
61. Tower of Hanoi (TOH) problem
• Well known game
• Played with three poles and number of different sized disks.
• Each disk has hole in the center, allowing it to be stacked around any
of the poles.
• Initially disks are stacked on the leftmost pole in an order. i.e. Largest
on the bottom and the smallest on the top
2/29/2016 Ashim Lamichhane 61
62. Tower of Hanoi (TOH) problem
2/29/2016 Ashim Lamichhane 62
63. Objective on TOH problem
• Transfer the disks from the left most pole to the rightmost pole
without ever placing a larger disk on top of a smaller disk.
• Only one may be moved at a time and each disk must always be placed
around one of the poles.
• The problem can be solved in recursive method in three steps.
1. Move the top n-1 disks from the left pole to the center pole
2. Move nth disk(largest) to the right
3. Move the n-1 disk on the center pole to the right pole
2/29/2016 Ashim Lamichhane 63
64. TOH problem
/*C program for Tower of Hanoi using Recursion */
#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the
Tower of Hanoi are :n");
towers(num, 'A', 'C', 'B');
return 0;
}
2/29/2016 Ashim Lamichhane 64
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("Move disk 1 from peg %c to peg %cn",
frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("Move disk %d from peg %c to peg %cn",
num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
65. Questions
• Write a function CalculateRoots() which receives three coefficients a,b,c of
quadratic equation ax2+bx+c=0 as its arguments and then calculates and
displays its roots.
• Write a recursive function like int findsum(int n) which receives an integer n
and returns sum of first n natural numbers.
• Write three functions: convertFromFeetToInches() which converts feet value
to inches, convertFromInchesToCentimeters() which converts inches to
centimeters and convertFromCentimetersToMeter() which converts
centimeters to meters. Write a program that prompts a user for a
measurement in feet and then converts and displays this value in meters.
[Hint: 1 feet = 12 inches, 1 inch=2.54cm and 100cm = 1m]
2/29/2016 Ashim Lamichhane 65