C++ Program to Separate Digits of a Positive Integer

Seperate digits of a positive integers Suppose you want to write a program in C++ which will take a positive integer from the user and output its individual digits. For example, if the input provided is 12345 then it will print 1,2,3,4 and 5 separately as integers. In this article we shall look at a few different ways of accomplishing exactly this.

First of all, look at the following program. It is probably the simplest way of separating digits of an integer. It makes use of the fact that when the division operator (/) is used with two integer operands then it gives us only the whole part of the quotient and the remainder operator (%) gives us the remainder when dividend is divided by the divisor. In this particular case, we use 10 with both these operators as divisor. When we use it with the remainder operator we get the last digit of the number entered by the user and when we use it with the division operator then we get the original number without that last digit. In this way, repeating these two steps until the original number becomes zero, we get each individual digit of the original number form right to left i.e. from least significant to most significant digit. Continue reading C++ Program to Separate Digits of a Positive Integer

Very Simple C++ programs – Nested loops Demonstration/Examples

Here are some extremely simple programs in C++ for absolute beginner students. I hope these would help them understand how nested loops work in programming. The required pattern of numbers to be printed on screen by a specific program is given before the source code to serve a problem statement.

1)
Required Pattern
1
12
123
1234
12345

Continue reading Very Simple C++ programs – Nested loops Demonstration/Examples