Use of Operators

Here are sample programs which will further explain the use of operators in programming.

 

Problem Statement:

 

Write a program that takes a four digits integer from user and shows the digits on the screen separately i.e. if user enters 7531, it displays 1,3,5,7 separately.

 

Solution:

 

Let’s first analyze the problem and find out the way how to program it.

 

Analysis:

First of all, we will sort the problem and find out how we can find digits of an integer. We know that when we divide a number by 10, we get the last digit of the number as remainder. For example when we divide 2415 by 10 we get 5 as remainder. Similarly 3476 divided by 10 gives the remainder 6. We will use this logic in our problem to get the digits of the number. First of all, we declare two variables for storing number and the digit. Let’s say that we have a number 1234 to show its digits separately. In our program we will use modulus operator ( % ) to get the remainder. So we get the first digit of the number 1234 by taking its modulus with 10 (i.e. 1234 % 10). This will give us the digit 4. We will show this digit on the screen by using cout statement. After this we have to find the next digit. For this we will divide the number by 10 to remove its last digit. Here for example the answer of 1234 divided by 10 is 123.4, we need only three digits and not the decimal part. In C we know that the integer division truncates the decimal part to give the result in whole number only. We will use integer division in our program and declare our variable for storing the number as int data type. We will divide the number 1234 by 10 (i.e. 1234 / 10). Thus we will get the number with remaining three digits i.e. 123. Here is a point to be noted that how can we deal with this new number (123)? There are two ways, one is that we declare a new variable of type int and assign the value of this new number to it. In this way we have to declare more variables that means more memory will be used. The second way is to reuse the same variable (where number was already stored). As we have seen earlier that we can reassign values to variables like in the statement x = x + 1, which means, add 1 to the value of x and assign this resultant value again to x. In this way we are reusing the variable x. We will do the same but use the division operator instead of addition operator according to our need. For this purpose we will write number = number / 10. After this statement we have value 123 in the variable number.

 

 

 

Previous

 

 

TOC

 

 

Next