0% found this document useful (0 votes)
8 views67 pages

Code Tricks

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views67 pages

Code Tricks

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

‫استراحة بقى انتوا ماتعبتوش وال ايه ‪‬‬

PRACTICE TIME
Practice 1
Suppose n is defined as inetger number and n>1.
Trace this code carefully and write the output for
a) n = 2
b) n = 3
c) n = 4
and then find out the relation between input and output
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
for(int i = n - 1;i >= 2; i--)
n *= i;
cout << n << endl;
return 0;
}
Practice 2 (this code in 2014 exam)
suppose a and b are defined as integer numbers.
Trace this code carefully and write the output for
1. a=1, b=3 2. a = 3, b = 6 3. a=6, b = 3 4. a = 4, b = 6
then find out the relation between inputs and output
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
while(a != b)
if(a > b)
a = a - b;
else
b = b – a;
cout << a << endl;
return 0;
}
Practice 3
Trace this code carefully and write the output
#include<iostream>
using namespace std;
int main()
{
• for(int i=1,x=1;i<=5;x++)
• {
• cout<<"*";
• if(i==x)
• {
• cout<<endl;
• x=0,i++;
• }
• }
return 0;
}
Practice 1 solution
After tracing the code
When n = 2 the output is “2”.
When n = 3 the output is “6”.
and when n = 4 the output is “24”.
wow!!!!!! the output is the factorial of n or (n!).
Practice 2 solution
After tracing the code
When a = 1 and b = 3 the output is “1”.
When a = 3 and b = 3 the output is “3”.
When a = 6 and b = 3 the output is “3”.
When a = 4 and b = 6 the output is “2”.
Oh my God! I can't find the relation … trace the code again for
more inputs
yeeeeeeeeeeeeeees the relation is the GCD (Greatest common
divisor) of a and b !!!
GCD -> Is the largest positive integer that divides the numbers
without a remainder . For example, the GCD of 8 and 12 is 4.
Practice 3 solution
After tracing the code the output is

*
**
***
****
*****

wow !!!!!! trace the code again please :)


‫‪ ‬بالتوفيق والسداد‬
PREPARED BY
MOHAMMED SALAH
MOHAMMED HELMY

You might also like