loading...

Practice #2

giladri profile image Gilad Ri ・2 min read

Some nice tricks you all should know:

// #1 - the modulo operator (just a reminder):
int x = 125;
int y = 7;
int z = 5;
int divisionRemainder = x % y; // 6
divisionRemainder = x % z; // 0

// #2 - how to get the last digit of a number:
int number = 12345;
int lastDigit = number % 10; // 5

// #3 - how to omit the last digit of a number:
int number2 = 12345;
int shorterNumber = number2 / 10; // 1234

And now, let's write down some code!

Exercise #1

Write a program which gets a number from the user and prints the sum of its digits. For example:

Enter a number:
123
The sum of the digits of the number 123 is 6

(Hint: use the tricks above).

Exercise #2

Write a program which gets an integer number from the user and checks if it's a prime number. If it's a prime number the program prints "Prime", and otherwise it prints "Not prime". (Hint: A number is prime if it is not divisible by any smaller number). For example:

Enter a number:
9
Not prime

Enter a number:
3
Prime

Exercise #3

Write a program which gets from the user an integer and builds a pyramid of asterisks ('*') with a base of this size. For example:

Insert the base size of the pyramid:
5
  *   
 *** 
*****

Insert the base size of the pyramid:
6
  **  
 **** 
******

Insert the base size of the pyramid
25
            *
           ***
          *****
         *******
        *********
       ***********
      *************
     ***************
    *****************
   *******************
  *********************
 ***********************
*************************

Pay attention that if the base size is an even number, the head of the pyramid should be "**" and not '*'.

Good luck!

Always remember, it's much C-mpler than you thought!

Regards,
Gilad

Posted on by:

Discussion

pic
Editor guide