Introduction To Algorithms and Flowchart
Introduction To Algorithms and Flowchart
Computer is an electronic machine which performs computational and logical procedures as per the requirements of the user. Requirements of users are communicated to computer by the help of programs/software. Writing program and software is a pure engineering activity and all engineering products need a design to be prepared before going for actual implementation. For every program/software we always need to prepare a design, which is called algorithm.
1.1. Algorithm
Algorithm is the logical steps used to process the input data in order to produce the required information and results. In other words, it is a step by step procedure.
2)
The design of an algorithm to solve a specific problem needs high knowledge and big practical experience and good background about the details of the problem to be solved. For one problem as there can be multiple solutions, so there can be multiple algorithms for a problem.
2)
1.4. Flowcharts
A flowchart is a graphical representation of an algorithm and is very helpful in understanding the algorithm. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Flowcharts are usually drawn using some standard symbols. Following are some basic symbols:
Purpose
Start or End of the algorithm
Shape
b. c.
d. Only one flow line should Enter a decision symbol, but two flow lines, one for each possible answer (Yes and NO), should Exit from decision symbol.
No Yes
e.
Only one flow line will exit from Start and 1 will enter in End of algorithm.
Start End
f. g.
Multiple flows can be joined to 1 flow using Connector symbol It is useful to test the validity of the flowchart by passing through it with a simple test data.
1.5.
Problem 1: Write an algorithm and draw the flowchart for finding the average of two numbers Algorithm: Input: two numbers x and y Output: the average of x and y Steps: 1. 2. 3. 4. 5. input x input y sum = x + y average = sum /2 output average
END average = sum/2 Output average Input x and y sum = x + y START
Problem 2: Write an algorithm and draw the flowchart to compute a maximum of two numbers Algorithm: Input: two numbers N1 and N2 Output: the Max number Steps: No 1. 2. 3. 4. 5. Input N1,N2 if N1 > N2 go to step 3,otherwise go to step 4
Max=N2 N1>N2 Input N1 and N2 START
Yes
Max=N1
END
Problem 3: Write an algorithm to print Even numbers from 1 to 50. Algorithm: Input: Not required Output: Even numbers from 1- 50 Steps: 1. Counter = 2 2. Repeat Steps 3 and 4 While Counter <= 50 3. Output Counter 4. Counter = Counter+2
START
Counter = 2 Counter=Counter+2
Counter <=50
Yes
Output Counter
No
END
Exercise Problems
1. Write algorithms to find the area of a rectangle, triangle and square and draw the flowcharts for each. Draw a flowchart to calculate displacement, S = Vit + at
2
2. 3. 4.
Draw flowchart to find the sum and average of three numbers N1, N2, N3. Draw flowchart to solve the following problem: IF X > 0 IF X <= 0 S = 3X+2 S = 3X-2
5.
Draw a flowchart to Input Basic Salary, Allowances and Deductions. Do the required calculations and display the total take home Salary. Draw a flowchart to Input Item unit Price, discount and Quantity. After performing required calculations, Output the Amount to be paid. Draw a flowchart to Input three numbers and display the minimum. Draw a flowchart to Output all the even numbers from x to y, where x and y are variables. Draw a flowchart to take input of the year from the user and find out whether it is a Leap year or not. (Hint: any year divided by 4 fully is a leap year e.g. 2008 % 4 = 0) Draw a flowchart to take input temperature of Muscat from User and then output the result according to following criteria: Temperature >= 30 Temperature >= 25 and Temperature < 30 Temperature < 25 Hot Moderate Pleasant
6.
7. 8. 9.
10.
Programming in any language requires learning 2 major parameters. 1. Syntax of Programming language. Grammar or rules of language for writing instructions 2. Semantics Logics / problem solving ability or skills for doing programming
2. 3. 4. 5.
Develop algorithm and draw Flowchart Write the program in a computer language i.e. C using some IDE e.g. Turbo C ++. Test and debug the program. Run the program, input data, and get the results from the computer.
2.3. Compiler
Programming languages are like English language with some defined set of keywords and syntax, but it is not directly understandable by the computer machine. As Computer is a digital machine so it understands only language of 1s and 0s called machine language. So the program code written in C language is required to be converted in machine language (0s and 1s) so that computer can understand and perform that functionality. This Conversion/translation from C language to Machine language is done using software called Compiler. The IDE which we will use in this course for programming Turbo C has a compiler to perform this conversion.
10
2.
main():
main is a keyword in C language and it is the function which will be executed first always when you will run the program. Every program should have a main function otherwise it will not execute. 3. {}
Next, there is a curly bracket also called braces ("{ }"). Within these brackets will be the main program body (Instructions of the main function). 4. Comments
Comments in C are enclosed by /* .. comments .. */. Comments can go to multiple lines, just it is required to put /* symbol in the start and */ at the end. Whatever is written within comments symbol is not considered by the compiler as part of program so compiler will not also try to convert it to machine language. It is a good programming practice to put comments in your program for some explanation of the instructions. It will help you and other people who will read your program later on in understanding the code.
How to use data in C Programs: 2.5. Variables: memory places to store data
Computer machines cant process data until it is not stored in the memory of the computer. It is exactly like a Calculator where first we input numbers, which Calculator stores in its memory and then when we define operation to be performed on that data, calculator take/access data from memory and perform operation. In Computers data is stored in a memory location which is identified as a variable. The reason of calling it variable is that, we can store any value in it. For example for calculating displacement we need to store data of Initial Velocity (Vi), Time (t) and Acceleration (a) in the memory. Vi = 100 t = 5.2 a = 60
11
Method 1:
Data type
Variable Name
Initial Value ;
int n1 = 13;
Method 2:
Data type
Variable Name ;
int n1;
Method 3:
Data type
Examples:
float Vi = 100.4; char choice; double S, Vi, a, t ;
12
Variable Naming:
For naming the variables we must need to follow certain rules including: 1. 2. The variable names in C can only be started with a character or an underscore ( _ ). Keywords of C language cant be used as a Variable name. E.g. we learnt data types. The names of data types are keywords, so they cant be the name of variables. Important keywords are: int, float, double, char, long, main, return, case, switch, do, static, else, for, while etc. 3. 4. 5. Space is not allowed in the variable names. Special characters / symbols e.g. &, @, $ etc are not allowed in variable names. In one program 2 variables cant have the same name. But C language is a Case sensitive language, means VELOCITY is different from Velocity. So we can have 2 variables with same name but different case.
Examples:
Variable Name Value1 1value value_1 Value#1 _1value Long long Return return area(a) id-number _id Status
13
Now for Input and Output we are using: Requirement Output/Display on Monitor Input from Keyboard Function Name Printf scanf Library / Header file stdio.h stdio.h
Format specifiers:
Format Specifier %c %d %f %lf Data Type char int float double
14
Examples:
1. printf ("I am a student of HCT in Engineering department"); //String output Float gpa = 3.2; 2. 3. printf ("%f",gpa); printf ("My GPA in Programming = %f", gpa);
Example 1
Write a program that add two integers 30 and10 ?
Sum result of 30 and 10 = 40
#include<stdio.h> void main() { int n1, n2, sum; n1 = 30; n2 = 10; sum = n1 + n2; printf("Sum result of %d and %d = %d", n1, n2, sum); }
Example 2
100 -- 3.14 166.3456 -- A #include<stdio.h> void main() { int num = 100; float fnum = 3.14; double dnum = 166.3456; char ch = 'A'; printf(%d -- %f -- %lf -- %c, num, fnum, dnum, ch); }
15
Control characters are written with a backslash character \ followed in printf statement inside the String symbols " ". Following are two control characters used commonly. Control Character \n \t Purpose For New line For Tab (Creating space)
Example 1
# include <stdio.h> void main(){ printf(" I am studying in Diploma (First Year)\n " ); printf(" in Engineering department of\tHCT"); }
Syntax:
scanf ("format specifiers (with % symbols)", &variable1, &variable2, ..); Within String " ", only format specifiers of the variables which will be input will be written, and in second part the names of the variables which will be input will be written with & (address operator) symbol. Example: int a, b; scanf("%d%d", &a, &b);
16
Example:
Write a program that reads 2 integer numbers and print their sum?
# include<stdio.h> void main(){ int num1,num2,sum; printf("Enter First Number:\t"); scanf("%d",&num1 ); printf("Enter Second Number:\t"); scanf("%d",&num2); sum=num1+num2; printf(Sum\t=\t%d,sum); } Enter First Number: 15 Enter Second Number: 25 Sum = 40
17
Exercise Questions
1. We want to write a program to Input & store the marks of 5 courses and then calculate GPA of each course and Semester GPA. After calculation display the Marks, GPA and SGPA. Now keeping in mind all these answer following questions. a. b. c. d. 2. How many and which type of variables are required for above program? Write a Valid variable name for each variable which you will use in this program. Do we need to use scanf function in this program and where? Do we need to use printf function in this program and where?
Write programs to find the area of: a. b. c. d. Circle Triangle Square Rectangle
3.
Give 10 examples of Variable names which are Valid and 10 Invalid variable names.
18
19
As in C language all different type of processing and computations can be done so there are different types of Operators are available also. Following are the major types of Operators used in C language: 1. 2. 3. 4. 5. Assignment operators Arithmetic operators Relational operators Logical operators Increment & decrement operators
Here it is important to remember that on LHS only a variable can come, while on RHS we can write a variable, a constant or an expression.
20
Arithmetic Expressions Algebraic expression 3x2+2x+1 Vit+1/2at2 r2 C language expression 3*x*x+2*x+1 Vi*t+0.5*a*t*t 3.14*r*r
In Arithmetic expression if there are multiple operators of same precedence than evaluation will be done from left to right always. Examples Expression 10 + 10 * 5 5*3+6/3 4/2*2+3*2+1 10-4+2 11%3*2+3*0 Result 60 17 11 8 4
21
||
OR
10 >= 8 || 5 < 5
NOT
++
Prefix
Prefix
22
Exercise Questions
1. Write the result of following expressions. S. No 1 2 3 4 5 6 7 8 9 10 11 12 13 Expression 2+3 2*3+4 5 + (6 + 4) / 2 10 % 3 * 4 + 5 * 2 10 % 2 27 % 7 5/4 7.0 / 4.0 7.0 / 4 3+(++2) int A = 11; X = ++A % 3; int A = 11; X = A++ % 3; int A = 7; X = -A++; Result
23
24
Always the programs dont execute in a sequential flow. Some instructions are depending on certain condition to happen for execution. Due to Decision making the normal flow of execution of the program can be controlled. C language contains following decision making statements: 1. 2. 3. 4. if statement if else statement else if statement switch statement
As these statements are used to control the flow of execution, so they are also known as control structures/statements. In all these structures we use Relational operators to compare the operands and Logical operators are used for combining multiple conditions.
4.1. if statement
if statement is used to execute certain instructions on the result of the condition i.e. if the result of condition will be true, related instructions will execute otherwise not.
Syntax:
if (condition) { Statement(s) }
Example1: #include <stdio.h> void main() { int number; printf("Please Enter a Number:"); scanf("%d",&number); if(number > 0) printf("Number is Positive" ); }
If the number of statements in body is only 1 than curly bracket is optional. For multiple instructions in body, its Compulsory.
Example 2: #include <stdio.h> void main() { int number; printf("Please Enter a Number:"); scanf("%d",&number); if(number%2 == 0) printf("Number is Even" ); } Example 3: #include <stdio.h> void main() { int marks; printf("Please Enter C marks:"); scanf("%d",&marks); if(marks > 60) printf("You are Pass" ); }
In all these examples we saw we cant mention any instruction for execution if condition returns false.
25
If the number of instructions in body is only 1 than curly bracket is optional. For multiple instructions in body, its Compulsory.
If the number of instructions in body is only 1 than curly bracket is optional. For multiple instructions in body, its Compulsory. Example 3: /* Program to find Maximum of 3 numbers using if and if else statements*/ #include<stdio.h> void main() { int n1,n2,n3; printf("Input 3 numbers: "); scanf("%d%d%d",&n1,&n2,&n3); if(n1>n2) if(n1>n3) printf("Maximum = %d",n1); else printf("Maximum = %d",n3); else if(n2>n3) printf("Maximum = %d",n2); else printf("Maximum = %d",n3); }
Example2:
#include <stdio.h> void main() { int marks; printf("Please Enter C marks:"); scanf("%d",&marks); if(marks > 60) printf("You are Pass" ); else printf("You are Fail" ); }
26
. . .
else { Statement(s) Example 2: #include <stdio.h> void main() Example 1: { #include <stdio.h> int day; void main() printf("\n Please day number (0 to 7) : "); { scanf("%d",&day); int number; if(day= =1) printf("\Saturday"); printf("\n Please Enter a number : "); else if(day= =2) scanf("%d",&number); printf("Sunday"); if(number > 0) else if(day= =3) printf("\n You entered a Positive number."); printf("Monday"); else if(number < 0) else if(day= =4) printf("\n You entered a Negative number."); printf("Tuesday"); else else if(day= =5) printf("Wednesday"); printf("\n You entered 0."); else if(day= =6) } printf("Thursday"); else if(day= =7) printf("Friday"); else printf("You entered Wrong number"); } }
27
2.
Syntax: switch (variable/expression) { case value-1: block of statements; break; case value-2: block of statements; break;
. . .
default: block of statements; } default and its block of statements are optional. It is like else in else if statement.
Example 1: #include<stdio.h> void main() { int day; printf("\n Please day number (0 to 7) : "); scanf("%d",&day); switch(day) { case 1: printf("\Saturday"); break; case 2: printf("Sunday"); break; case 3: printf("Monday"); break;
case 4: printf("Tuesday"); break; case 5: printf("Wednesday"); break; case 6: printf("Thursday"); break; case 7: printf("Friday"); break; default: printf("You entered Wrong number"); } }
28
Example 2: / *An Arithmetic Calculator Program*/ #include<stdio.h> void main() { char operator; int n1,n2,result; printf( "Welcome to my Calculator"); printf ("\nEnter + for Addition"); printf("\nEnter for Subtraction"); printf ("\nEnter * for Multiplication"); printf("\nEnter / for Division"); printf ("\nEnter % for Modulus"); printf("\nEnter first number : "); scanf("%d",&n1); printf("Enter Second number: "); scanf("%d",&n2); flushall(); /* This function is to clear buffer stream before input of a character */ printf ("Enter the Operator: "); scanf("%c",&operator); switch(operator) { case '+': result = n1+n2; printf("\n \nThe addition of %d and %d gives %d",n1,n2,result); break; case '-': result = n1-n2; printf("\n \nThe subtraction of %d and %d gives %d",n1,n2,result); break; case '*': result = n1*n2; printf("\n\nThe multiplication of %d and %d gives %d",n1,n2,result); break; case '/': result=n1/n2; printf("\n \nThe division of %d and %d gives %d",n1,n2,result);break; case '%': result = n1%n2; printf("\n \nThe modulo of %d and %d gives %d",n1,n2,result);break; default: printf("\nInvalid Operator entered. "); break; } printf("\nThanks for using my calculator... "); }
29
Exercise Questions
1.
Enter a number: 374 The number 374 has 3 digits You may assume that the number has no more than four digits. Hint: use if statements to test the number. For example, if the number is between 0 and 9, it has one digit. If the number is between 10 and 99, it has two digits. 2. Write a program that asks the user for a 24-hour time, then displays the time in 12-hour form: Enter a 24- hour time: 21:11 Equivalent 12-hour time: 9:11 PM
3. Write a program that asks the user to enter a wind velocity (in knots), then display the corresponding description. Velocity (knots) <1 13 4 27 20 47 48 63 > 63 Description Calm Light air Breeze Gale Storm Hurricane
4. Write a program using Nested if else statement to accept the mark of a student in a course and display the letter grade and the grade point. The following table shows the relationship between the mark, letter grade and the grade point. Marks 90-100 80-89 70-79 60-69 0- 60 Grade A B C D F Grade points 4.0 3.0 2.0 1.0 0.0
30
31
Whenever we need to execute some instructions repeatedly, we can do it using the looping statements available in C programming language. There are 3 types of Loop constructs available in C language. 1. while loop It keeps on repeating instructions until the condition returns false. It is useful when we dont know in advance how many times the loop will be executed. It also executes the instructions until condition returns false but condition is checked after the loop body is executed. This ensures that the loop body runs at least once. It is commonly used in those problems where the loop will be executed for fixed number of times already known to programmer.
2.
do while loop
3.
for loop
32
Example 2 /*A program to print a sequence of first n natural numbers */ #include<stdio.h> void main() { int counter, number; printf("Enter the Number"); scanf("%d",&number); counter =0; while (counter <= number) { printf("%d \n", counter); counter++; } }
Example 3 / *Program to find the sum of the first 10 numbers (1+2+3+ +10) */ #include <stdio.h> void main() { int num,sum; num= 1; sum= 0; while (num <= 10) { sum =sum + num; num++; } printf("Sum of first 10 numbers=%d", sum); }
Example 4 / *Program to print Even numbers from 1 - 50 */ #include <stdio.h> void main() { int num = 1; while (num <= 50) { if(num%2 == 0) Printf("%d\t", num); num++; } }
33
34
Example 3: / *A program to demonstrate all the arithmetic operations */ #include<stdio.h> void main() { char choice, operation; int n1,n2,result; do{ printf( "Welcome to my Calculator"); printf ("\nEnter + for Addition\nEnter for Subtraction"); printf ("\nEnter * for Multiplication"); printf("\nEnter / for Division"); printf ("\nEnter %% for Modulus"); printf("\nEnter first number : "); scanf("%d",&n1); printf("Enter Second number: "); scanf("%d",&n2); flushall(); /* This function is to clear buffer stream before input of a character */ printf ("Enter the Operator: "); scanf("%c",&operation); switch(operation) { case '+': result = n1+n2; printf("\n \nThe addition of %d and %d gives %d",n1,n2,result); break; case '-': result = n1-n2; printf("\nThe subtraction of %d and %d gives %d",n1,n2,result); break; case '*': result = n1*n2; printf("\nThe multiplication of %d and %d gives %d",n1,n2,result);break; case '/': result=n1/n2; printf("\nThe division of %d and %d gives %d",n1,n2,result);break; case '%': result = n1%n2; printf("\nThe modulo of %d and %d gives %d",n1,n2,result);break; default: printf("\nInvalid Operator entered. "); break; } flushall(); printf("\nEnter Y/y to continue and N/n for Exit: "); scanf("%c", &choice); } while(choice != 'N' && choice!= 'n'); }
35
2. The condition is checked if it is true, the body of the loop is executed; otherwise the loop is terminated. 3. After completing 1 iteration, the increment/decrement will be done, condition will be checked, if true than same process will be repeated otherwise loop will be terminated. Example l /* program to print n numbers and their squares */ #include <stdio .h> void main() { int counter, number, square; printf(Enter the value till where you want to print Square:"); scanf("%d", &number); for(counter=0;counter<=number;counter++) { square = counter * counter; printf("Number = %d\tSquare = %d\n", number, square); } }
36
Example 3
/*Print multiplication table of a number entered by User.*/ #include<stdio.h> #include <stdio .h> void main() { void main() int number, counter; { printf("Enter a number for printing Table: "); int counter; scanf("%d",&number); for(counter =1; counter <=100; counter ++) for( counter=1;counter<=10;counter++) if(counter%2==0) printf("%d x %d = %d\n", number, counter, printf("%d\t", counter); number*counter); } }
Example 1 /*Print multiplication tables from 2 to 5*/ #include<stdio.h> void main() { int counter1,counter2; for(counter1 =2; counter1<=5; counter1++) for(counter2=1; counter2<=10; counter2++) printf("%d x %d = %d\n", counter1, counter2, counter1 * counter2); }
37
Example 3 /*Programs to print * ** *** **** ***** ****** */ #include<stdio.h> void main() { int counter1, counter2; for(counter1=1; counter1<=6; counter1++) { for(counter2=1; counter2<= counter1; counter2++) printf("*"); printf("\n"); } }
38
Exercise Questions
1. 2. a. Write a program using for loop to calculate product of numbers from 1 10. Write programs to print the following designs. ****** ***** **** *** ** * ** *** **** ***** ****** b. c.
1 12 123 1234 12345 1234 123 12 1
39
Chapter 6: Arrays
40
Array is a data structure which is used to store multiple data elements of the same data type. Following are the important characteristics of Array. 1. 2. 3. An Array is of a single data type. Array is always fixed sized. Array is always allocated sequential memory.
Arrays are very beneficial to store multiple data elements of the same type, otherwise we have to make separate variable for each data and it becomes very difficult to handle so many variables.
The elements in the array will be referred as: numbers[0], numbers[1], numbers[2], numbers[3], numbers[4] we can assign value to any element of array as: numbers[0] = 1; numbers[1] = 2; If the values are already known to be put in array than we can initialize the array as under: Int numbers[5] = {1,2,3,4,5}; Int numbers[ ] = {1,2,3,4,5}; If values are not known at the time of declaration of array than we can input elements of array using a loop, which makes the accessibility of array elements very easy, no matter whatever is the size of the array.
41
Without Arrays /*program to enter 5 numbers and then print*/ #include <stdio.h> void main() { int n1,n2,n3,n4,n5; printf("\nPlease Enter the five numbers : "); scanf("%d %d %d %d %d",&n1,&n2,&n3,&n4,&n5); printf("\nYour Entered numbers are : "); printf("\n%d %d %d %d %d",n1,n2,n3,n4,n5); }
Example 1 - With Array /*program to enter 5 numbers and then print*/ #include<stdio.h> void main() { int numbers[5], index; for(index =0;index < 5; index++) { scanf("%d",& numbers[index]); } printf("\nYour Entered numbers are : "); for(index =0;index<5;index++) { printf("%d\t", numbers[index]); } } Example 2 Example 3 /* Find sum of all the elements of an Array.*/ /*Find sum of all elements of array entered by #include<stdio.h> user*/ void main() #include<stdio.h> { void main() int numbers[5]={13,34,47,67, 102}; { int index, sum=0; int numbers[5]; for(index =0;index < 5; index++) int index, sum=0; sum = sum + numbers[index]; for(index =0; index < 5; index++) printf("\nSum = %d",sum); { } scanf("%d",& numbers[index]); sum = sum + numbers[index]; } printf("\nSum = %d",sum); } Example 4 Example 5: /* Input a number of multiple digits and print /*Find Largest value in Array*/ it in Reverse order.*/ #include<stdio.h> #include<stdio.h> void main() void main() { { int numbers[5], index, max ; int number[5], index; for(index=0;index<=4;index++) printf("Please Enter the 5 integers\t"); scanf("%d",&numbers[index]); for(index =0;index <5; index++) max=numbers[0]; scanf("%d",&number[index]); for(index=0;index<=4;index++) printf("The values in reverse order are\t"); if (max<numbers[index]) for(index =4;index >=0; index--) max=numbers[index]; printf("%d",number[index]); printf("Maximum Number in this array = %d } ",max); }
42
Example 1 /*Input values in Two, 2-dimensional Arrays (Matrix) of size [3][3], add them & print resultant matrix.*/ #include<stdio.h> void main() { int matrix1[3][3], matrix2[3][3],sum[3][3], row, col; printf("Input elements of the first matrix : "); for(row=0;row<3;row++) for(col=0;col<3;col++) scanf("%d",& matrix1[row][col]); printf("Input elements of the second matrix : "); for(row=0;row<3;row++) for(col=0;col<3;col++) scanf("%d",& matrix2[row][col]); for(row=0;row<3;row++) for(col=0;col<3;col++) sum[row][col] = matrix1[row][col]+matrix2[row][col]; printf("Resultant matrix is : \n"); for(row=0;row<3;row++) { for(col=0;col<3;col++) printf("%d\t",sum[row][col]); printf("\n"); } }
43
Exercise Questions
1. Write a program to accept 4 integers from the user, store in an array & display the contents of the array. 2. Write a program to store 7 integers into array a, search any stored number from array & find the position of this number in array. 3. Write a program to store 3 quiz marks of 5 students, and then calculate the average quiz marks of each student store it in another 1-dimensional array and display it.
44
Chapter 7: Functions
45
When the size of program gets big and in same program so many different operations we are doing than it becomes difficult to track, understand and debug the program. So we need to adopt some modular technique, in which we can divide our program into multiple segments. C language provides us a technique for this purpose called functions.
7.1. Function:
A Function is a block of statements that perform a particular task and it can be called as many numbers of times as required without repeating the complete code.
In C language functions are of Two types: 1. Built-in functions / Library functions: These functions are ready made and we can directly use them. Example are printf(), scanf(), sqrt, strcpy, etc. 2. User defined functions: These functions are written by programmers for their own usage in their programs.
Syntax of function definition: Return_type function_name (list of Arguments) { Body of function (statements) return statement; }
2.
Calling of function (inside the main or any other user defined function) Example: sum = addition(23,45); or printf(Sum = %d, addition(23,45)); or int num1 = 23, num2 = 45, sum; sum = addition (num1, num2); or printf(Sum = %d,addition(num1,num2);
46
Examples:
Example 1: /*Input 2 numbers from User and add them using a function.*/ #include<stdio.h> int addition(int n1,int n2) { int sum; sum=n1+n2; return sum; } void main() { int num1,num2,sum; printf("Input two numbers: "); scanf("%d%d",&num1, &num2); sum = addition(num1,num2); printf("Addition result of %d and %d = %d", num1, num2, sum); } Example 2: /*Input a number from User and display its square using a function.*/ #include<stdio.h> int square(int num) { int result; result = num*num; return result; } void main() { int number, sqr; printf("Input a number for finding its Square: "); scanf("%d",&number); sqr = square(number); printf("Square of %d = %d", number, sqr); }
47
Exercise Questions
1. 2. 3. 4.
Write a program using a function to add, subtract and multiply two numbers. Write a C program using a function to find factorial of given number. Write a program to accept two numbers and display the average using a function. Write a menu driven C program to make calculator for functions +,-, /,* using functions.
48