I am trying to learn C++ and I am having problem writing a simple program. What I want is a function that will take one integer input parameter, create a sequence of numbers stored in an array from 0 to that number, and the numbers are a summation. For example, given 7 outputs 0 1 2 3 4 5 6 7
You said you would like to fill an array where you plug in a value such as "7" and the array will fill up from 0 to 7.
This can easily be done:
#include <stdio.h>
#include <malloc.h>
int main() {
int i = 0, num = 0; //declare variables
scanf("%d", &num);
int *myArray = (int *)malloc(sizeof(int)*(num+1)); //malloc for array
for (i = 0; i <= num; i++){
myArray[i] = i; //fill array as you asked
printf("%d", myArray[i]); //print out tested values: 01234567
}
free(myArray);
return 0;
}
C-style:
#include <stdio.h>
#include <malloc.h>
int main()
{
int num;
scanf("%d", &num);
int *arr = (int *)malloc(sizeof(int)*(num+1));
int i;
for(i = 0; i <= num; i++)
arr[i] = i; //This is the array
return 0;
}
C++ style:
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char ** argv)
{
int num;
cin >> num;
vector<int> arr;
for(int i = 0; i <= num; i++)
arr.push_back(i);
return 0;
}
By way of giving you a helping hand, start here and fill in the blanks:
#include <vector>
std::vector<int> make_sequence(int last)
{
std::vector<int> result;
// <fill this in>
return result;
}
int main()
{
// <probably do something useful here too...>
return 0;
}
You're going to have to do some of this yourself though, that's the way StackOverflow works with regard to homework-like problems :)