my question refers to dynamic arrays in C++. I'm new at the language so please spell things out for me where possible.
I was wondering how I could change the following code to accept floats?
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length;
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
int *dArray;
dArray = new int[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
for ( int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
delete[] dArray;
return 0;
Here's a more safe and easy way to write that code:
#include <iostream>
#include <vector> // std::vector
using namespace std;
int main()
{
int length;
cout << "Please enter the length of the array: ";
cin >> length;
vector<int> dArray( length );
for( int i = 0; i < length; ++i )
{
dArray[i] = i;
}
for( int i = 0; i < length; ++i )
{
cout << dArray[i] << " ";
}
}
The basic floating point type in C++ is called double. E.g. the literal 3.14 is of type double. So you can use that instead of int for the array item type.
Related
I am trying to input data to an array and then print them by using a function but I am not sure how to organize the code.
#include <iostream>
using namespace std;
void showGrade(double grade[], int size);
int main()
{
double grade[];
int size;
for (int i = 0; i < size; i++)
{
cout << "Please enter the number of grade" << endl;
cin >> size;
}
showGrade(grade, size);
return 0;
}
void showGrade(double grade[], int size) //How many grade we have
{
for (int counter = 0; counter < size; counter++)
{
cout << "Please enter your grades: " << endl;
cin >> grade[counter];
cout << "Here are your grades: " << endl;
}
}
I Expect to see how many grades I input and then show them.
UPDATE 8/28/19
I figured out how to do it in main function successfully. But what I really want is to put them in a seperate function. My new codes have error at the function call which is type name is not allowed and expected a ')'. How do I make it work?
#include <iostream>
using namespace std;
void showGrades(double ar[], int size);
int main()
{
double ar[20];
int size;
showGrades(double ar[size], int size);
system("pause");
return 0;
}
void showGrades(double ar[], int size) {
cout << "Please enter the number of grade "; // array size
cin >> size;
cout << "Please enter your grades " << endl;
for (int i = 0; i < size; i++) {
cin >> ar[i];
}
cout << "The grades you entered are: " << endl;
for (int i = 0; i < size; i++) {
cout << ar[i] << endl;
}
}
First of all, you need to use the standard container
std::vector
instead of the double grade[];, since you want a variable-length
array as per user input.
Secondly, you are using un-initialized size variable in
for (int i = 0; i < size; i++)
hence it will be initialized with a garbage value. There you need no for-loop
A good starting would be:
#include <iostream>
#include <vector> // std::vector
void showGrade(std::vector<double>& grade)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> pass the vector by ref, as the grades should be inseted to the it
{
// the logic
}
int main()
{
int size;
std::cout << "Please enter the number of grade" << endl;
std::cin >> size;
std::vector<double> grade;
grade.reserve(size); // reserve memory for unwanted re-allocations
showGrade(grade);
return 0;
}
I leave it to you to complete, after reading about the std::vector more.
Also, do not practice with using namespace std;. Read more:
Why is "using namespace std;" considered bad practice?
this is not a valid C++ code:
double grade[];
You can use std::vector:
std::vector<double> grade;
To insert a grade to the vector you can use grade.push_back(someGrade);
I wanted to solve a challenge named "Variable sized Arrays" on Hackerrank and I wanted to do that using vectors. The Code I wrote, doesn't work properly and I tried debugging it, but I'm getting nowhere. I'll be grateful for
Here's the challenge:
Consider an n-element array,a, where each index i in the array contains a reference Kito an array of integers (where the value of Ki varies from array to array). See the Explanation section below for a diagram.
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array and j denotes an index in the array located at a[i] . For each query, find and print the value of element j in the array at location on a[i]a new line.
Input Format
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query.
Sample Input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample Output
5
9
So here's my code for this (I'll leave it with the couts for debugging):
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::endl;
int main() {
int numberOfQueries = 0;
int numberOfArrays = 0;
cout << "Enter Nr.Of Arrays followed by Nr.Of Queries:";
cin >> numberOfArrays >> numberOfQueries;
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
cout << "Nr.Of Queries: " << numberOfQueries << endl;
vector<vector<int>>multiArray;
cout << "MultiArray size: " << multiArray.size();
while (numberOfArrays != 0) {
int vsize = 0;
cout << "\nenter array starting by its size: ";
cin >> vsize;
cout << " Size entered is: " << vsize << endl;
vector<int> vec1(vsize);
cout << "Array Size is: " << vec1.size() << endl;
//int element = 0;
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
multiArray.push_back(vec1);
numberOfArrays--;
cout << "MultiArray size: " << multiArray.size();
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
};
while (numberOfQueries > 0) {
int i = 0, j = 0;
cout << "\nQuery indexes:";
cin >> i >> j;
cout << multiArray[i][j];
numberOfQueries--;
}
}
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
should be something like
for (int i = 0; i < vsize; ++i) {
int elem;
cin >> elem;
cout << "Element is: " << elem << "\n";
vec1.push_back(elem);
}
while (cin >> vsize) isn't going to stop asking for input until you get end of file or an error. But you know how many inputs to expect so code that in a for loop.
My answer.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q;
cin >> n >> q ;
vector<int> a[n];
int k;
for(int i = 0; i < n; i++)
{
cin >> k;
for (int j = 0; j < k; j++)
{
int val_a_i_j;
cin >> val_a_i_j;
a[i].push_back(val_a_i_j);
}
};
for (int i = 0; i < q; i++)
{
int a_i, j;
cin >> a_i >> j;
cout << a[a_i][j] << '\n';
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a , b;
cin >> a >> b;
vector<int> arr[a];
for(int i= 0 ; i < a ; i++)
{
int m;
cin >> m;
int o;
for(int j=0;j<m;j++)
{
cin >> o;
arr[i].push_back(o);
}
}
int r,s;
for(int k=1;k<b;k++)
{
cin>>r>>s;
cout <<a[r][s]<< endl;
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int>* a;
a= new vector<int>[n];
int p;
int k;
for (p = 0;p < n;p++) {
cin >> k;
for (int i = 0; i < k; i++) {
int o;
cin >>o;
a[p].push_back(o);
}
}
int r, s;
for (p = 0;p < q;p++)
{
cin >> r >> s;
cout << a[r][s]<<endl;
}
return 0;
}
This problem is about handling vectors of the vector.
int main() {
int n,q;
cin>>n>>q;
vector<vector<int> > a;//creating vectors of vector
int k;
for (int i = 0; i < n; i++)
{
cin >>k;
vector <int> row; // creating vector
for (int j = 0; j < k; j++)
{
int val;
cin>> val;
row.push_back(val);
}
a.push_back(row);
}
for (int l=0; l < q; l++)
{
int i,j;
cin>>i>>j;
// checking boundary conditions
if ((i >= 0 && i < a.size() ) && (j >=0 && j < a[i].size()))
{
cout<<a[i][j]<<endl;
}
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int>> MultiArry;
vector<int> output;
int n1,n2, q;
int i,j;
cin >> n1 >> q;
MultiArry.resize(n1);
output.resize(q);
for(int i=0;i<n1;i++)
{
cin >> n2;
MultiArry[i].resize(n2);
for(int j=0;j<n2;j++)
{
cin >> MultiArry[i][j];
}
}
for(int ii=0;ii<q;ii++)
{
cin >> i >> j;
output[ii] = MultiArry[i][j];
}
for(int i=0;i<q;i++)
cout << output[i] << endl;
return 0;
}
in the function Read() when i output arrays klas[] and nauj[] everything seems to be read fine, but back in the main function they get destroyed and seem to be filled with other text file. Do you have any idea whats the problem here?
#include <iostream>
#include <fstream>
using namespace std;
const char klase[] = "klase.txt";
const char naujokai[] = "lele.txt";
void Read(int klas[], int nauj[], int &nk, int &nj);
int main()
{
int klas[] = {};
int nauj[] = {};
int nk;
int nj;
Read(klas, nauj, nk, nj);
for(int i = 0; i < nk; i++){
cout << klas[i] << endl;
}for(int i = 0; i < nj; i++){
cout << nauj[i] << endl;
}
return 0;
}
void Read(int klas[], int nauj[], int &nk, int &nj)
{
ifstream fklase(klase);
fklase >> nk;
for(int i = 0;i < nk;i++){
fklase >> klas[i];
cout << klas[i] << endl << endl;
}
fklase.close();
ifstream fnaujokai(naujokai);
fnaujokai >> nj;
for(int i = 0; i < nj; i++){
fnaujokai >> nauj[i];
cout << nauj[i] << endl << endl;
}
fnaujokai.close();
}
Zero-size arrays such as int klas[] = {}; are not standard and writing into them as you do in fklase >> klas[i]; is Undefined Behavior since they have no room to store anything. Also note that when you use int klas[] as a function argument it is actually equivalent to int * klas.
I'm picking up on C++ recently and is trying to code a program which prompts for names for a defined no. of times and inserts each of the input into an array of size-5. The problem happened when I tried to run the following code, my counter, i increases according to the no of len the user input. Why is that so?
#include <iostream>
using namespace std;
int main(){
const int SIZE = 5;
char name[SIZE];
int i;
for (i = 0; i < SIZE; i++){
if (strlen(name) <= 50) {
cout << "Enter a name: \n";
cin >> name[i];
}
}
for (i = 0; i < SIZE; i++){
cout << name[i] << endl;
}
return 0;
}
Output:
if (strlen(name) <= 50) {
You should not call strlen on array which is not initialized.
Use array of strings otherwise
cout << name[i] << endl;
refers to i-th character, not entire string. Or if you want to go with char arrays, you'd need a two dimensional array.
I thing what you indended to do was :
#include <iostream>
using namespace std;
int main(){
const int SIZE = 5;
string names[SIZE];
int i;
for (i = 0; i < SIZE; i++){
cout << "Enter a name: \n";
string name;
cin>>name;
if (strlen(name) <= 50) {
cin >> names[i];
}
}
for (i = 0; i < SIZE; i++){
cout << name[i] << endl;
}
return 0;
}
UNTESTED
The second for loop, which does the output, does this in single characters, incrementing i each time.
To output the string all at once assign a string pointer to name[0] and send that to cout.
I am new to C++. I am trying to solve a problem in the textbook: swap the first and last element in an array. But when I run the code I wrote, nothing happened and even the sentence "Please enter the numbers in the array: " does not show up. Anyone could give some help? Thanks.
#include <iostream>
using namespace std;
int swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
int input;
cin >> input;
for(int i=0; i<SIZE; i++)
{
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE] << endl;
return 0;
}
There were a few mistakes:
You should get the input inside the loop and then assign it to the test array.
When printing the swapped value, access the test array with SIZE-1 instead of SIZE, because array indexes run from 0 to SIZE-1, inclusive.
You declared swap() as returning int, but provided no return statement (this suggests that you haven't enabled enough warnings from your compiler).
#include <iostream>
using namespace std;
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
int input;
cout << "Please enter the numbers in the array: " << endl;
for(int i=0; i<SIZE; i++)
{
cin >> input;
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE-1] << endl;
return 0;
}
#include <iostream>
using namespace std;
//Here return type should be void as you are not returning value.
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
//USE LOOP TO TAKE INPUT ONE BY ONE IN AN ARRAY
for(int i = 0; i < SIZE; i++)
cin >> test[i];
swap(test, SIZE);
//USE LOOP TO DISPLAY ELEMENT ONE BY ONE
for(int i = 0; i < SIZE; i++)
cout << test[i] << endl;
return 0;
}