Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

CS111 Introduction to Computer Science

Computer Science Dept.


Helwan University
Lecture 12
Solved Examples
[ 2nd Set ]
Solved Examples on:
12.1 Functions [ Part A ]; Function Declaration & Prototype,
Function Call, Parameters versus Arguments, Returning Values,
Local Variables, & Pass-by-Value vs. Pass-by-Reference.
12.2 Functions [ Part B ]; Function Declaration & Prototype,
Function Call, Parameters versus Arguments, Returning Values,
Local Variables, & Pass-by-Value vs. Pass-by-Reference.
12.3 Recursion, Base Cases (and Recursion without a Base Faculty of
Case), & Recursive Functions. Computers &
12.4 Number Systems, Number Systems Conversions, Artificial Intelligence
Binary Notation, & Bitwise Operations.
FALL 2021
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set) Course & Lectures are based on their counterparts in the following:
o Harvard University's CS50; An introduction to the intellectual
enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The
University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction
to C++ (2011), and 6.S096 Introduction to C and C++ (2013), MIT
by (Massachusetts Institute of Technology) OpenCourseWare.
Dr. Amr S. Ghoneim
Lecture 12: Solved Examples [ 2nd Set ]
Solved Examples on:

12.1 Functions [ Part A ]; Function Declaration (Definition), Function Prototype,


Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.
12.2 Functions [ Part B ]; Function Declaration (Definition), Function Prototype,
Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.

12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.1: C function to CALCULATE EMI (Equated


Monthly Installment)
o An EMI or Equated Monthly Installment is defined as "A fixed
payment amount made by a borrower to a lender at a specified date
each calendar month. Equated monthly installments are used to pay
off both interest and principal each month, so that over a specified
number of years, the loan is fully paid off along with interest."
o This program will read total loan amount (principal), rate (in years),
& time (in years), & prints the per month EMI of that loan amount.
o The formula used in this program is:
o ( P * R * ( 1 + R )T ) / ( ( ( 1 + R )T ) - 1 )
o P is a loan amount.
o R is the interest rate per month (we will read it as a yearly rate
and convert it to a monthly rate in our program).
o T is loan time period in year (we will read it as years and
convert it to months in our program). 4
Please pause the video and try to answer the question on your own!

12.1: C function to CALCULATE EMI (Equated


Monthly Installment)

Enter principal: 20000


Enter rate: 10
Enter time in year: 2
Monthly EMI is = 922.899536

5
/*EMI Calculator (C program to calculate EMI).*/
#include <stdio.h>
#include <math.h>

float calculate_emi( float p, float r, float t) {


float value;
value = ( p * r * pow( 1 + r, t ) ) / ( pow( 1 + r, t ) -1 );
return value; }

int main() {
float principal, rate, time, emi;
printf("Enter principal: "); scanf( "%f", &principal );
printf("Enter rate: "); scanf( "%f", &rate);
printf("Enter time in year: "); scanf( "%f", &time);
rate = rate / ( 12 * 100 ); /*one month interest*/
time = time * 12; /*one month period*/
emi = calculate_emi( principal, rate, time );
printf("Monthly EMI is = %f\n", emi );
return 0;
6
}
Please pause the video and try to answer the question on your own!

12.2: C function to check whether NUMBER IS


PALINDROME or not
o A Palindrome Number - A number which is equal to its reverse is
know as Palindrome Number. For example, the number 12321 is a
Palindrome Number, because 12321 is equal to it’s reverse; which
is also 12321.

o In this program, we will read an integer number and check whether


it is a Palindrome Number or not. To check whether a number is
Palindrome or not, we will firstly calculate its Reverse Number. If
the input number is equal to its reverse number then that number
is considered to be a Palindrome.

7
Please pause the video and try to answer the question on your own!

12.2: C function to check whether NUMBER IS


PALINDROME or not

First run:
Enter an integer number: 12321
12321 is a palindrome.

Second run:
Enter an integer number: 1234
1234 is not a palindrome.

8
/* C program to check whether a number is palindrome or not */
#include <stdio.h>
/*function to check Palindrome Number*/
int isPalindrome( int num ) {
int tempNumber = num; int dig, revNumber;
/*getting reverse number*/
revNumber = 0;
while(num > 0) {
dig = num % 10;
revNumber = ( revNumber * 10 ) + dig;
num/=10; }
if( revNumber == tempNumber )
return 1; /*Palindrome Number*/
else
return 0; /*Not a Palindrome Number*/
}
int main() {
int number;
printf("Enter an integer number: "); scanf("%d", &number);
if( isPalindrome( number ) ) printf("%d is a palindrome.", number);
else printf("%d is not a palindrome.", number);
9
return 0; }
Please pause the video and try to answer the question on your own!

12.3: C function to COUNT TOTAL NUMBER OF


DIGITS of an Integer number

o This program will read an integer number and count the total
number of digits in that number. For example, the total number of
digits in the integer 1234 is 4.

o The logic behind implementing this program is to successively


divide the number by 10 and count the digits until the number is
zero. Before using the counter variable, initialize it to 0.

Enter a number: 28765


Total numbers of digits are: 5 in the number: 28765.

10
/* C program to count digits in a number.*/
#include <stdio.h>
/*function to count digits*/
int countDigits( int num ) {
int count = 0;
while( num > 0 ) {
count++;
num/=10;
}
return count;
}

int main() {
int num, cnt;
printf("Enter a number: ");
scanf("%d", &num);
cnt = countDigits( num );
printf("Total numbers of digits are: %d in the number: %d.", cnt, num);
return 0;
11
}
Lecture 12: Solved Examples [ 2nd Set ]
Solved Examples on:

12.1 Functions [ Part A ]; Function Declaration (Definition), Function Prototype,


Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.
12.2 Functions [ Part B ]; Function Declaration (Definition), Function Prototype,
Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.

12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.4: C function to COUNT THE OCCURRENCE


OF A PARTICULAR DIGIT in a number

o In this program, we will read an integer number and a digit then


print the total number of occurrences of that input digit in that
number.

o For example, if the user entered the number 12311, in which (s)he
wants to find the occurrence of the digit 1, the occurrence of 1 will
be 3 in the given number (12311).

Enter a number: 23111


Enter a digit to search: 1
Total occurrence of the digit is: 3 in the number: 23111.

13
/*C program to print occurrence of a particular digit in a number.*/
#include <stdio.h>
/*function to get occurrence of a digit in a number*/
int findOccurrence( int num, int dig ) {
int rem, cnt; cnt = 0;
while( num > 0) {
rem = num%10;
if( rem == dig )
cnt++;
num/=10;
}
return cnt;
}
int main() {
int num, digit, cnt;
printf("Enter a number: "); scanf("%d", &num);
printf("Enter a digit to search: "); scanf("%d", &digit);
cnt = findOccurrence( num, digit);
printf("Total occurrence of the digit is: %d in number: %d.", cnt, num);
14
}
Please pause the video and try to answer the question on your own!

12.5: C function to find whether a given integer


is AN ARMSTRONG NUMBER or not
o An Armstrong number can be defined as a number that is equal to
the sum of the cubes of its digits. For example 0, 1, 153, 370, 371,
and 407 are all Armstrong numbers. Let's try to understand why -
for example - 153 is an Armstrong number:
o here 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ).

o This program will read an integer number and check whether it is


an Armstrong Number or Not. To check an Armstrong number, we
have to calculate the sum of each digit’s cube, and then compare
the number to the calculated sum of cubes. If a number and the
sum of its digit’s cubes are equal, then the number is an Armstrong
Number, otherwise it's not.
15
Please pause the video and try to answer the question on your own!

12.5: C function to find whether a given integer


is AN ARMSTRONG NUMBER or not

First run:
Enter an integer number: 153
153 is an Armstrong number.

Second run:
Enter an integer number: 167
167 is not an Armstrong number.

16
/* C program to check whether a number is armstrong or not */
#include <stdio.h>
/*function to check Armstrong Number*/
int isArmstrong( int num ) {
int tempNumber = num; int rem; int sum = 0; /*sum of digit's cube*/
while( tempNumber != 0) {
rem = tempNumber % 10;
sum = sum + ( rem * rem * rem );
tempNumber /= 10;
}
if( sum == num) return 1; /*Armstrong Number*/
else return 0; /*Not an Armstrong Number*/
}
int main() {
int number;
printf("Enter an integer number: "); scanf("%d", &number);
if( isArmstrong( number ) )
printf("%d is an Armstrong number.", number);
17
else printf("%d is not an Armstrong number.", number);
return 0; }
Please pause the video and try to answer the question on your own!

12.6: Write a C Program to Calculate ..


Permutation (nPr) .. and .. Combination (nCr)
nC and nPr are statistical quantities regarding possible subsets of a
r
set of objects, and they are defined as:
nP ( n, r ) = n! / ( n − r )!
r
nC ( n, r ) = nP ( n, r ) / r! = n! / ( r! ( n − r )! )
r r

Using sets to help define them:


o nPr is the formula to find permutations of n objects taking r at a
time. This answers the question of how many possible groups of
r objects from a set of n objects. And, ..
o nCr is the formula to find the unique permutations, otherwise
known as combinations, of n objects taking r at a time. This
answers the question of how many unique possible groups of r
objects can be made from n objects.
Please pause the video and try to answer the question on your own!

12.6: Write a C Program to Calculate ..


Permutation (nPr) .. and .. Combination (nCr)
Example: Take the set { 1, 2, 3, 4} and find all combinations and
permutations taking 2 at a time:

We can make this set of sets making every possible combination of


the 4 objects in the set taking 2 at a time (we aren't allowed to
reuse an object once we've use it):
------- {2, 1} {3, 1} {4, 1}
{1, 2} ------- {3, 2} {4, 2}
{1, 3} {2, 3} ------- {4, 3}
{1, 4} {2, 4} {3, 4} -------

This result of 12 sets is the calculation of nPr( 4, 2), the total number
of permutations of 4 objects taking 2 at a time. We can confirm that
the formula produces 12:
nP ( 4, 2) = 4! / ( 4 − 2 )! = ( 4 ∗ 3 ∗ 2 ∗ 1 ) / ( 2 ∗ 1 ) = 24 / 2 = 12
r
Please pause the video and try to answer the question on your own!

12.6: Write a C Program to Calculate ..


Permutation (nPr) .. and .. Combination (nCr)
Example: Take the set { 1, 2, 3, 4} and find all combinations and
permutations taking 2 at a time:

Now, if we want to look at unique sets, then { 1, 2} = { 2, 1} and


likewise for all sets with the same numbers in them. Or, for this
case, we can remove half of the grid we've created.

------- {2, 1} {3, 1} {4, 1}


------- ------- {3, 2} {4, 2}
------- ------- ------- {4, 3}
------- ------- ------- -------

This leaves us with 6 unique groups, and we can confirm with


the nCr formula that we get 6:
nC ( 4, 2) = nP ( 4, 2) / r! = 12 / ( 2 ∗ 1 ) = 12 / 2 = 6
r r
12.6: Write a C Program to Calculate ..
Permutation (nPr) .. and .. Combination (nCr)
#include<stdio.h>

// Function Prototype Declarations


long factorial( int );
long find_npr( int, int ); Enter the values of n and r respectively :
long find_ncr( int, int ); 42

int main() { 4C2 = 6


int n, r; 4P2 = 12
long npr, ncr;
printf("Enter the value of n and r respectively: \n");
scanf("%d%d", &n, &r);
// Function Calls
npr = find_npr( n, r );
ncr = find_ncr( n, r );
printf("\n\t %dC%d = %ld\n", n, r, ncr );
printf("\n\t %dP%d = %ld\n", n, r, npr );
return 0;
}
// Function for Calculating nCr
long find_ncr( int a, int b )
{
return ( factorial( a ) / ( factorial( b ) * factorial( a - b ) ) );
}

// Function for Calculating nPr


long find_npr( int a, int b )
{
return ( factorial( a ) / factorial( a - b ) );
}

// Recursive Function for Calculating the Factorial


long factorial( int c )
{
if( c == 1 || c == 0 )
return 1;
else
return c * factorial( c - 1 );
}
Lecture 12: Solved Examples [ 2nd Set ]
Solved Examples on:

12.1 Functions [ Part A ]; Function Declaration (Definition), Function Prototype,


Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.
12.2 Functions [ Part B ]; Function Declaration (Definition), Function Prototype,
Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.

12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.7: What is the output of the following code


segment?
What will be the output of the program?
#include <stdio.h>
int fun1( int no ) {
if( no == 0 )
return 0;
else
printf("%d,", no );
fun1( no-- ); }

int main() {
int no = 5;
fun1( no );
return 0; }

24
12.7: What is the output of the following code
segment?
What will be the output of the program?
#include <stdio.h>
int fun1( int no ) {
if( no == 0 )
return 0;
else
printf("%d,", no );
fun1( no-- ); }

int main() {
int no = 5;
fun1( no );
return 0; }

Infinite loop. 5, 5, 5, 5, ……
25
Please pause the video and try to answer the question on your own!

12.8: What is the output of the following code


segment?
What will be the output of the program?
#include <stdio.h>
int fun1( int no ) {
if( no == 0 )
return 0;
else
printf("%d,", no );
fun1( --no ); }

int main() {
int no = 5;
fun1( no );
return 0; }

26
12.8: What is the output of the following code
segment?
What will be the output of the program?
#include <stdio.h>
int fun1( int no ) {
if( no == 0 )
return 0;
else
printf("%d,", no );
fun1( --no ); }

int main() {
int no = 5;
fun1( no );
return 0; }

Print 5, 4, 3, 2, 1.

27
Please pause the video and try to answer the question on your own!

12.9: Write a C Program to find whether a


Number is Prime or Composite using Recursion

o Prime Number: A number that is only divisible by 1 and


itself.
o Composite Number: A number that is not a prime number.
o Note: 1 is neither prime nor composite.

Enter a positive number to check if it's a Prime Number: 13


13 is a Prime Number.

Enter a positive number to check if it's a Prime Number: 20


20 is a Composite Number.
#include<stdio.h>

int isPrime( int, int ); // Prototype; Declaring the Recursive Function

int main()
{
int num, prime;
printf("Enter a positive number to check if it's a Prime Number: ");
scanf("%d", &num);
prime = isPrime( num, num / 2 );
if( prime == 1 )
{ printf("\n%d is a Prime Number.\n", num); }
else
{ printf("\n%d is a Composite Number.\n", num); }
return 0;
}

int isPrime( int n, int i ) // Function definition


{
if( i == 1 ) return 1; // Base-Case 1: terminates the recursion
else if( n % i == 0 ) return 0; // Base-Case 2: terminates recursion
else isPrime( n, i - 1 ); // Recursive Call
}
Lecture 12: Solved Examples [ 2nd Set ]
Solved Examples on:

12.1 Functions [ Part A ]; Function Declaration (Definition), Function Prototype,


Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.
12.2 Functions [ Part B ]; Function Declaration (Definition), Function Prototype,
Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.

12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.10: C program to CONVERT A DECIMAL


NUMBER TO BINARY

o Write a program in C to
convert a decimal number into
binary.

31
Please pause the video and try to answer the question on your own!

12.10: C program to CONVERT A DECIMAL


NUMBER TO BINARY

For Example:

Convert Decimal to Binary:


-------------------------
Enter a number to convert : 25

The Binary of 25 is 11001.

32
#include <stdio.h>
void main()
{
int n, i, j, binno = 0, dn;
printf("\n\nConvert Decimal to Binary:\n ");
printf("-------------------------\n");
printf("Enter a number to convert : ");
scanf("%d", &n);
dn = n;
i = 1;
for( j = n; j > 0; j = j / 2)
{
binno = binno + ( n % 2 ) * i;
i = i * 10;
n = n / 2;
}
printf("\nThe Binary of %d is %d.\n\n", dn, binno);
} 33
Please pause the video and try to answer the question on your own!

12.11: C program to CONVERT A BINARY


NUMBER TO A DECIMAL using for loop

o Write a program in
C to convert a
binary number into
a decimal number.

34
Please pause the video and try to answer the question on your own!

12.11: C program to CONVERT A BINARY


NUMBER TO A DECIMAL using for loop

Convert Binary to Decimal:


-------------------------
Input a binary number :11001

The equivalent Decimal Number : 25

35
#include <stdio.h>
void main() {
int n1, n, p = 1;
int dec = 0, i = 1, j, d;
printf("\n\n Convert Binary to Decimal:\n ");
printf("-------------------------\n");
printf("Input a binary number :");
scanf("%d", &n);
n1 = n;
for ( j = n; j > 0; j = j / 10) {
d = j % 10;
if( i == 1 )
p = p * 1;
else
p = p * 2;
dec = dec + ( d * p );
i++;
}
printf("\nThe equivalent Decimal Number : %d \n\n", dec); 36

}
Please pause the video and try to answer the question on your own!

12.12: Write a C Program to find the Binary


Representation of an Integer using Bitwise
Operators
In this C program, we will read an integer (decimal) number, and
print its Binary Value (Binary Representation).

In this program, we are finding the Binary values of 16 bits


numbers. The logic is very simple – we have to just traverse each
bit using the Bitwise AND operator. To traverse each bit – we will
run loop from 15 to 0 (we are doing this to print the Binary
representation in a proper format).

Enter an Integer Number : 13


The Binary Value of 13 is = 0000000000001101
#include <stdio.h>
void getBinary( int );
int main()
{
int num = 0;
printf("Enter an Integer Number : ");
scanf("%d", &num );
printf("\nThe Binary Value of %d is = ", num );
getBinary( num );
return 0;
}

void getBinary( int n ) /* Function Definition : getBinary() */


{
int loop;
/* loop = 15, for representing a 16 bits value, 15th bit to 0th bit */
for( loop = 31; loop >= 0; loop-- )
{
if( ( 1 << loop ) & n )
printf("1");
else
printf("0");
}
}
Up Next ..
This was CS112
CS111

an Introduction to
Computer Science

Thank you!

You might also like