Wednesday, February 11, 2015
C Program to Print Numbers From 1 to n Without Using Loops Recursion or Goto Statement
You may have made program to print numbers from 1 to n using loops, recursion or goto statement. But have you ever thought about doing this without help of loops, recursion or goto? It can be done without using such things as explained in below program.
Also Read: C program to find factorial of any number using recursion
Also Read: C++ Templates: Program to Swap Two Numbers Using Function Template

Also Read: C program to find factorial of any number using recursion
Also Read: C++ Templates: Program to Swap Two Numbers Using Function Template
#include<iostream>
using namespace std;
class Num
{
public:
static int i;
Num()
{
cout<<i++<<" ";
}
};
int Num::i=1;
int main()
{
int n;
cout<<"Enter value on n:";
cin>>n;
Num obj[n];
return 0;
}
In this program we are using the concept of static data member and array of objects. Class Numcontains a static variable i whose value will remain till the program terminates. We are creating an array of objects of class Num. In this program we are creating n objects, value of n depends on input we give. The default constructor is called for all objects one by one. In the constructor the value of i is printed and is incremented by one in each call. In this way numbers from 1 to n are printed.
If you have any doubts or any suggestion regarding above program then you can ask it by commenting below.
Source: http://www.geeksforgeeks.org/output-of-c-program-set-18-3/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.