Create array for which each object can hold integers in the range 0-100. You input a few numbers say 1 3 5 they are displayed as 0 1 0 1 0 1 0 0 0 0 up to 100.I can do a simple loop of zeros up to 100 but i cant display numbers in the 0 , 1 context portrayed above . Any help would be great. Thanks

#include<iostream>

using std::cout;
using std::endl;

#include<iomanip>

using std::setw;

int main()
{
	int i,n[ 100 ];

	for (i=0;i<100; i++)
		n[ i ]=0;			//intialize array

	cout<<"Elements"<<setw(13)<<"Value"<<endl;

	for (i=0; i <100; i++) // print array
		cout<<setw(7)<<i<<setw(13)<<n[i]<<endl;

	return 0;
}

Recommended Answers

All 3 Replies

It looks like the input specifies indices of which values are to be set to 1. Let's say you have an array of 10 rather than 100 (because I don't want to type that much). You initialize the array to 0's:

{0,0,0,0,0,0,0,0,0,0}

Now let's say the user types 1, 4, 5, 7, and 9. You go to those indices and set the value to 1:

{0,1,0,0,1,1,0,1,0,1}

Then just print the array. The logic and the implementation are very simple:

#include <iostream>

int main()
{
  int a[10] = {0};
  int x;

  std::cin>> x;

  if ( -1 < x && x < 10 )
    a[x] = 1;

  for ( int i = 0; i < 10; i++ )
    std::cout<< a[i] <<' ';
  std::cout<<'\n';
}

if you want to display more than one number do you declare more variables , that i mean is where you have line 6 int x; you'd change it to int x,y; then you create a loop for y like you did for x.

The x in Narue's code is an arbritrary name for the index used in referencing each element of the array. She could have used sassafrass or i or y or any other variable name she wanted.

To display the values within an array you can loop through them one by one to display them or pick and choose how you please. If you want to keep track of two of the results outside of the array at any given time you'll need to store them in two separate objects, be they single variables or another array or whatever.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.