get length of an array in C++ - c++

int grades[100];
int j = 0;
int len = sizeof(grades)/sizeof(grades[0]);
while (j < len)
{
cout << grades[j] << endl;
j++;
}
I have entered only 5 grades and I want to print only that entered grades then ho can I print that?
I have tried to use length of array but since I have created array of size 100, it is printing all unwanted characters at the end.
I have also used '\0' to get end of array but it is not working.

#include <vector>
std::vector<int> grades;
// add 3 grades
grades.push_back(4);
grades.push_back(1);
grades.push_back(9);
// https://www.cplusplus.com/reference/vector/vector/size/
auto size = grades.size();

Just keep track of the size when you read the numbers:
#include <iostream>
int main()
{
int const max_len = 100;
int arr[max_len];
std::cout << "Enter numbers: ";
int len = 0;
while (len < max_len && std::cin >> arr[len]) {
++len;
}
// you've read `len` numbers.
std::cout << "You've entered " << len << " numbers\n";
for (int i = 0; i != len; ++i) {
std::cout << arr[i] << '\n';
}
}

Your code returns the total number of elements the array can store.
Try this instead:-
#include <iostream>
int main()
{
int sample[10];
int length = 0;
for (int integer : sample)
{
if (integer != NULL)
{
length++;
// If you want to print the element as well -
std::cout << integer << std::endl;
}
}
}
Essentially what it does goes through all of the elements of the array and adds 1 to length if that element is not NULL (NULL means a null pointer, or if you're a beginner, just know it means basically nothing).
You can easily change int to any other type.
Hope it helps :)

Related

Expression must have a constant value error when creating an array C++

Good day. Faced an error "Expression must have a constant value" when creating an array. Find this question c++ array - expression must have a constant value, but these tips didn’t solve the problem. Please help and I'm sorry for such requests, I just started to learn C ++
Code:
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <string>
#include <sstream>
#include <conio.h>
#include <random>
int main()
{
int userInput = 0, sumEvenIndexElements = 0, sumElementsBeetwenZero = 0;
bool checkZeroElements = false;
std::cout << "Write array length:" << std::endl;
std::cin >> userInput;
const int lengthOfArray = userInput;
int numbers [lengthOfArray];
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(-10, 10);
for (int index = 0; index < lengthOfArray; index++)
{
numbers[index] = new int[distribution(generator)];
std::cout << numbers << std::endl;
if (index % 2 == 0)
{
sumEvenIndexElements += *numbers[index];
}
}
std::cout << "Sum even index elements: " << sumEvenIndexElements << std::endl;
for (int index = 0; index < lengthOfArray; index++)
{
numbers[index] = new int[distribution(generator)];
if (numbers[index] == 0)
{
checkZeroElements = !checkZeroElements;
}
if (checkZeroElements)
{
sumElementsBeetwenZero += *numbers[index];
}
}
if (checkZeroElements)
{
std::cout << "Sorry, array have less than two zero elements.";
}
else
{
std::cout << "Sum even index elements: " << sumEvenIndexElements << std::endl;
}
}
lengthOfArray is a constant variable, it's value would not be chagned during runtime after initialization.
But it's value - userInput is not a constant, it dependes on runtime user input. As pointed here
A constant value is an explicit number or character such as 1 or 0.5
or ‘c’.
You should use std::vector instead of an array, as suggested in Paul Evans's answer, or assign a proper constant value to the lengthOfArray, which will be known at the time of compilation, e.g.:
const int lengthOfArray = 10;
Your code:
std::cout << "Write array length:" << std::endl;
std::cin >> userInput;
const int lengthOfArray = userInput;
int numbers [lengthOfArray];
won't work as per the compiler error you're getting.
std::vector plays a lot nicer:
std::cout << "Write array length:" << std::endl;
std::cin >> userInput;
const int lengthOfArray = userInput;
std::vector<int> numbers(lengthOfArray, 0);
will create a std::vector of int of length lengthOfArray all initialised to 0.

sort and show the number of digits

I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}

C++ Binary Search Not Working Correctly - Finds Element Not in Array

I am running the binary search algorithm in C++ but it gives me spurious results. For example, searching for the value 21 gives me a
"Value is Found"
message but my array consists only of numbers from 0 to 20.
Any help is greatly appreciated.
#include <iostream>
#include <iomanip>
using namespace std;
int binarySearch(const int [], int, int, int, int ); // function prototype
int main()
{
const int arraySize = 10;
int arr[ arraySize ];
int key;
for( int i = 0; i <= arraySize; i++) // generate data for array
arr[i] = 2*i;
cout << "The array being searched is: " << endl;
for (int j = 0; j<=arraySize; j++) // print subscript index of the array
{
cout << setw(5) << j << " ";
}
cout << endl;
for (int z = 0; z<=arraySize; z++) // print elements of the array below index
{
cout << setw(5) << arr[z] << " ";
}
cout << "\n" <<"Enter value you want to search in array " << endl;
cin >> key;
int result = binarySearch(arr, key, 0, arraySize, arraySize); // function call
if (result == 1) // print result of search
cout << "Key is found " << endl;
else
cout << "Key not found " << endl;
return 0;
} // end main function
int binarySearch(const int a[], int searchKey, int low, int high, int length)
{
int middle;
while (low <= high){
middle = (low + high) / 2;
if (searchKey == a[middle]) // search value found in the array, we have a match
{
return 1;
break;
}
else
{
if( searchKey < a[middle] ) // if search value less than middle element
high = middle - 1; // set a new high element
else
low = middle + 1; // otherwise search high end of the array
}
}
return -1;
}
You are invoking undefined behavior because your for loop conditions are <=arraySize. Change it to <arraySize. On making this change, the code works perfectly for sample inputs.
By writing int arr[ arraySize ]; you are creating an array of 10 elements (i.e., from 0 to 9), while in the for loops, you start from 0 and move until 10.
Live Demo

Why does C++ give me this error? How to say if an array of ints is either odd or even?

This is supposed to be a code for user entering integers in an array and then calling a function that shows if they are even or odd. It then counts how many are even or odd (which I didn't get to yet because I am stuck here and I keep getting this error).
invalid operands of types 'int [20]' and 'int' to binary 'operator%'
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void getValue(int[], int);//function prototype
int main()
{
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
cout<<fixed<<showpoint<<setprecision(1);
//get ints from user
getValue(numbers, ARRAY_SIZE);
if ( numbers % 2== 0 )
// if the integer when divided by 2 has no remainder then it's even.
cout << numbers << " is even "<<endl;
else
// the integer is odd
cout << numbers << " is odd "<<endl;
return 0;
}
void getValue(int numbers[], int ARRAY_SIZE)
{
//loop counter
int index;
//get each value
for(index = 0; index <= ARRAY_SIZE - 1; index++)
{
cout<< "Enter an integer " << (index + 1)<< " : ";
cin>> numbers[index];
}
}
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
void getValue(int [], int);//function prototype
int main()
{
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
cout << fixed << showpoint << setprecision(1);
//get ints from user
getValue(numbers, ARRAY_SIZE);
//I added this FOR loop.
for (int i = 0; i < ARRAY_SIZE - 1; i++)
{
//I also added the [i] so that the number is outputted as well
if (numbers[i] % 2 == 0)
// if the integer when divided by 2 has no remainder then it's even.
// and here as well
cout << numbers[i] << " is even "
<< endl;
else
// the integer is odd
cout << numbers[i] << " is odd "
<< endl;
}
return 0;
}
void getValue(int numbers[], int ARRAY_SIZE)
{
//loop counter
int index;
//get each value
for (index = 0; index <= ARRAY_SIZE - 1; index++)
{
cout << "Enter an integer " << (index + 1) << " : ";
cin >> numbers[index];
}
}
I added a for loop and the array brackets on the output.
You need to loop through your array, just add a loop and check if (numbers[index] % 2 == 0)
Above answers should give you right results.
You can use a range for loop for fixed-size arrays:
for (int value : numbers)
{
if (value % 2 == 0)
{
cout << value << " is even.\n";
}
else
{
cout << value << " is odd.\n";
}
}
First, this is illegal in C++:
const int ARRAY_SIZE = 20;
int numbers[ARRAY_SIZE];
You need to declare
int numbers[20];
instead.
Second,
if ( numbers % 2== 0 )
numbers is an array of 20 values. What exactly is it meant to be using the % operator on? You probably want a loop that will check each int in the array.
for (int i = 0; i < 20; ++i)
{
if ( numbers[i] % 2== 0 )
...
else
...
}

C++ Permutation with a output length limit and special arguments

I am new to C++ and I am working on a program that will generate a list of all permutations of a string of characters, however I need the ability to limit the length of the output to lets say 5 characters (this will most likely become a variable number set by the user). I have been searching for about a week for something like this and the closest I have gotten is the following code.
Source.cpp:
#include <iostream>;
using namespace std;
void swap(char *fir, char *sec)
{
char temp = *fir;
*fir = *sec;
*sec = temp;
}
/* arr is the string, curr is the current index to start permutation from and size is sizeof the arr */
void permutation(char * arr, int curr, int size)
{
if(curr == size-1)
{
for(int a=0; a<size; a++)
cout << arr[a] << "";
cout << endl;
}
else
{
for(int i=curr; i<size; i++)
{
swap(&arr[curr], &arr[i]);
permutation(arr, curr+1, size);
swap(&arr[curr], &arr[i]);
}
}
}
int main()
{
string next;
char str[] = "abcdefghijklmnopqrstuvwxyz1234567890-";
permutation(str, 0, sizeof(str)-1);
cin.get();
cin.get();
}
This code works however it does not limit the length of the output. It sets the output length to the length of the given string. It also appears it might not account for multiple of the same letter/number in the output (this I am not 100% sure of).
Additionally, I will need to set special rules such as the hypen cannot be the first or last character in the output.
I have attempted to modify the above code by replacing sizeof(str)-1 with 5 however it will only "loop" through the first 5 characters in the string, so anything beyond "e" is not processed.
If anyone can assist on this it would be much appreciated.
EDIT:
Thank you to everyone for their excellent help I am now going to post my final product in case anyone else was trying to do the same thing.
Final Source:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
void swap(char *fir, char *sec)
{
char temp = *fir;
*fir = *sec;
*sec = temp;
}
void permutation(char * arr, int size, char* result, int depth, int limit)
{
ofstream myfile ("permutation.txt", fstream::app);
if(depth == limit)
{
for(int a=0; a<limit; a++){
myfile << result[a] << "";
cout << result[a] << "";
}
myfile << "\n";
cout << endl;
}
else
{
for(int i=0; i<size; i++)
{
result[depth] = arr[i];
permutation(arr, size, result, depth + 1, limit);
}
}
myfile.close();
}
int main()
{
ofstream myfile ("permutation.txt");
myfile << "";
myfile.close();
string answer;
char *rArray;
string startProcess = "N";
std::cout << "Welcome to permutation v1" << endl;
std::cout << "-------------------------" << endl;
std::cout << "Please enter how long the string should be: ";
std::getline (std::cin,answer);
int result = atoi(answer.c_str());
rArray = new char[result];
std::cout << "\n\nThank You!\n" << endl;
std::cout << "Please wait, generating possible character array for length of " << result << "." << endl;
std::cout << "Would you like to proceed? Y = yes & N = no: ";
std::getline (std::cin,startProcess);
char str[] = "abcdefghijklmnopqrstuvwxyz1234567890";
if(startProcess == "Y")
{
permutation(str, sizeof(str)-1, rArray, 0, result);
}
else
{
std::cout << "\n\nOperation Terminated. No permutations being generated..." << endl;
}
cin.get();
return EXIT_SUCCESS;
}
You need to limit the depth of the recursion
To give permutations of characters in the string, using each only once:
void permutation(char * arr, int currsize, intchar* sizeresult, int depth, int limit)
{
if(depth == limit)
{
for(int a=0; a<limit; a++)
cout << arr[a]result[a] << "";
cout << endl;
}
else
{
for(int i=curr;i=0; i<size; i++)
{
swap(&arr[curr],result[depth] &arr[i]);= arr[i];
permutation(arr, curr+1size, sizeresult, depth + 1, limit);
swap(&arr[curr], &arr[i]);
}
}
}
Call like this
permutation(str, 0, sizeof(str)-1, result, 0, 5);
To give permutations of characters in the string, using each character an unlimited number of times:
void permutation(char * arr, int size, char* result, int depth, int limit)
{
if(depth == limit)
{
for(int a=0; a<limit; a++)
cout << result[a] << "";
cout << endl;
}
else
{
for(int i=0; i<size; i++)
{
result[depth] = arr[i];
permutation(arr, size, result, depth + 1, limit);
}
}
}
Call like this
char result[5];
permutation(str, sizeof(str)-1, result, 0, sizeof(result));
This is not a tough job actually. If you can use recursion and a loop within that function you can solve it. I suggest use next_permutation function from the standard library.
The fact is time. Within 3 second you can process permutation for only 8 character. And the condition will be depended to requirement. Suppose in your example you can prune back if you need to omit hyphen in starting or ending.
Pseudo code of my implementation:
char array[] = "abcdee";
char eachPerm[6];
bool usedmatrix[6][6];
Recur(int depth, int n)
{
// you can return from here if this is not the right path, suppose '-'
// in first or last place.
if(depth == n)
{
print;
}
else
{
int i;
for(i= 0 to array.length)
{
if(array[i] is not used before)
eachPerm[depth] = array[i];
recur(depth+1, n);
}
}
}
Call this function initially recur(0, 5)