Below is the code I've written to find the largest and smallest number in an array of 100 integers(which are random).
My question is for the user to enter a number and find the location of the number the user entered. For example: "The number 230 was found at array location 34" or something like that.
How do I go about this question? My attempt looks something like
cout << "Enter #: ";
cin >> Input;
if(1){
for (int i = 0; i < 100 : i++){
if (Input == arr[i]
cout << "Location: " << i << endl;
} else
cout << "Input was not found ";
#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
int small, big;
int arr[100];
srand(time(0));
for(int i=0; i < 100; i++) {
arr[i] = rand() % 1000;
}
for(int i=0; i < 100; i++) {
cout << arr[i] << " ";
}
cout << endl;
big = small = arr[0];
for (int i = 0; i < 100; i++) {
if (arr[i] > big) {
big = arr[i];
}
if(arr[i] < small) { // compares smallest value with current element
small = arr[i];
}
}
}
A simple (and not ideal) solution is to loop over the array until the desired number is found. Something along the lines of:
const int N = 100;
int arr[N];
for (int i = 0; i < N; i++) {
arr[i] = rand() % 1000;
}
// Number to search for
int target = 11;
// Single loop searching for target
int index = -1;
for (int i = 0; i < N; i++) {
if (arr[i] == target) {
index = i;
break; // break when target found
}
}
if (index != -1) {
cout << "Found at " << index << "\n";
}
else {
cout << "Not Found\n";
}
However, you should use a vector whenever possible instead of an array. One benefit of using a vector is the ability to use the standard library find function.
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
vector<int> vec;
// fill vec with random numbers
for (int i = 0; i < 100; i++) {
int random_number = rand() % 1000;
vec.push_back(random_number); // adds random_number to end of vec
}
// Number we are searching for
int target = 7;
// find an iterator pointing to target if it exists
// else it will be vec.end()
auto it = find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
// find distance of it from beggining of vector
// i.e. vec[index] == target
int index = distance(vec.begin(), it);
cout << "Found " << target << " at " << index << "\n";
}
else {
cout << "Not Found\n";
}
}
Related
I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo
I am trying to make a program that calculates the average score of class and counting the number of A, B, C, D students. Now I am trying another idea: If the test scores are randomly given to students(between 60 to 100), how can I input those random scores into an array? Mine requires users to input all scores one by one. I would like to know how to fill in the array automatically.
#include <iostream>
#include <cstdlib>
using namespace std;
double Average(double *scores, int N)
{
int i;
double total = 0;
for(i = 0; i < N; i++)
{
total = total+scores[i];
}
return total / N;
}
int Agrade(double *scores, int N)
{
int i;
int count = 0;
for(i = 0; i < N; i++)
{
if(scores[i] >= 90 && scores[i] <= 100) count++;
}
return count;
}
int Bgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] >=80 && scores[i] < 90) count ++;
}
return count;
}
int Cgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] >=70 && scores[i] < 80) count ++;
}
return count;
}
int Dgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] >=60 && scores[i] < 70) count ++;
}
return count;
}
int Fgrade(double *scores, int N)
{
int i;
int count = 0;
for(i=0; i < N; i++)
{
if(scores[i] < 60) count ++;
}
return count;
}
int main(){
int i;
int N;
double *scores;
std::cout<<"How many test scores? "<<endl;
cin>>N;
if(N<1){
std::cout<<"Invalid input. try again"<<endl;
}
else if(N>25)
{
std::cout<<"1-25 only."<<endl;
}
else if(N>0 && N<25){
std::cout<<"Total number of test is: "<< N << endl;
}
scores = new double[N];
for(i = 0; i < N; i++)
{
cout << "Randomly generating score of students" << i + 1 << ": ";
cout << (rand() % 40 + 60) << endl; //Trying to give random scores between 60-100
if(!(cin >> scores[i]) || scores[i] < 0 || scores[i] > 100)
{
if(!cin)
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Score must be between 0 to 100.\n\n"; i--; continue;
}
}
double averagescore = Average(scores, N);
int scoreAcount = Agrade(scores, N);
int scoreBcount = Bgrade(scores, N);
int scoreCcount = Cgrade(scores, N);
int scoreDcount = Dgrade(scores, N);
int scoreFcount = Fgrade(scores, N);
cout << "The average test score : " << averagescore << endl;
cout << "The number of A grades : " << scoreAcount << endl;
cout << "The number of B grades : " << scoreBcount << endl;
cout << "The number of C grades : " << scoreCcount << endl;
cout << "The number of D grades : " << scoreDcount << endl;
cout << "The number of F grades : " << scoreFcount <<endl;
cout << endl;
return 0;
}
Can I just modify this part to make it work?
for(i = 0; i < N; i++)
{
cout << "Randomly generating score of students" << i + 1 << ": ";
cout << (rand() % 40 + 60) << endl; //Trying to give random scores between 60-100
if(!(cin >> scores[i]) || scores[i] < 0 || scores[i] > 100)
{
if(!cin)
{
cin.clear();
cin.ignore(1000, '\n');
}
cout << "Score must be between 0 to 100.\n\n"; i--; continue;
}
}
or do I need to modify all functions?
If what you want is to assign result of std::rand() function to all elements in array, you should take a look at std::generate function from <algorithm> header, which does exactly what you want. Take a look at this simple example:
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
int main() {
std::srand(0);
const int N = 5;
std::vector<int> scores(N);
std::generate(scores.begin(), scores.end(), [](){return std::rand() % 40 + 60; });
for(auto s : scores) {
std::cout << s << ' ';
}
}
This will fill vector scores with randomly generated numbers from specified interval using std::generate function and lambda function given as its third argument that returns random number.
In your case, if you're not allowed to use std::vector, you can still do it with plain C-arrays, like this:
int scores[5];
std::generate(std::begin(scores), std::end(scores), [](){return std::rand() % 40 + 60; });
Unfortunately, std::begin and std::end functions cannot be applied straight-forward to dynamically allocated arrays, but this still should work in your case:
const int N = 5;
double* scores = new double[N];
std::generate(scores, scores+N, [](){return std::rand() % 40 + 60; });
for(int i=0; i<N; ++i) {
std::cout << scores[i] << ' ';
}
// remember to release memory allocated using new
You need to seed the random number generator to make sure the random numbers have a reasonably random seed. So before the for loop you mentioned, you need to call something like srand(time(NULL)) and include time.h in your code. That should be enough.
And just as an aside, in your code, I only see allocation of the scores array. Remember to delete! Even better, use vectors throughout.
am new in coding and am using c++ to create a program to find sum median maximum and minimum but i get the error expected primary-expression before ';' token in every place that has cout
#include <iostream>
using namespace std;
int main()
{
int array[10],maximum,minimum,sum=0,median;
cout<<"input ten integers,"<<;
for(int i=0; i<10; i++){
cin>> array[i];
sum=sum+array[i];
}
for(int i=0; i<10; i++){
if(maximum>array[i])
{
maximum=array[i];
}
else if( minimum<array[i])
{
maximum= array[i];
}
}
median=(array[4]+array[5])/2;
cout<<"maximum value is"<<maximum<<;
cout<<"minimum value is"<<minimum<<;
cout<<"sum is"<<sum<<;
cout<<"median is"<median<<;
Remove the << before the ; on every line that has it or replace <<; with <<'\n'; for a new line.
#include <iostream>
using namespace std;
int main()
{
int array[10], maximum = 0, minimum = 0, sum = 0, median = 0;
cout << "input ten integers: ";
for (int i = 0; i < 10; i++) {
cin >> array[i];
sum = sum + array[i];
}
for (int i = 0; i < 10; i++) {
if (maximum > array[i])
{
maximum = array[i];
}
else if (minimum < array[i])
{
maximum = array[i];
}
}
median = (array[4] + array[5]) / 2;
cout << "maximum value is " << maximum << '\n';
cout << "minimum value is " << minimum << '\n';
cout << "sum is " << sum << '\n';
cout << "median is " << median << '\n';
return 0;
}
Use the below dummy code to fix this issue for the new line:
dummy code
#include <iostream>
int main() {
int a = 5;
int b = 10;
std::cout << (a < b) << std::endl; // 1
std::cout << (a > b) << std::endl; // 0
return 0;
}
output
1
0
This is a console application on CodeBlocks 13.12.
I am getting a variety of errors when I run this Insertion Sort.
Sometimes it prints outrageously large values that weren't in the original array. Or sometimes it runs and sorts the array perfectly fine.
Can anybody please point out what could possibly be wrong? Sorry I'm a noob.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void insertionSort(int arr[], int size);
int main()
{
int size;
srand(time(NULL));
cout << "Specify the size of your array: ";
cin >> size;
int theArray[size]; // creates an array of a size the user chooses
cout << endl << "Your current array: {";
for (int i = 0; i < size; i++) //prints out the original array
{
theArray[i] = rand() % 10000;
cout << theArray[i];
if (i != size - 1) // to beautify output
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl;
insertionSort(theArray, size);
}
void insertionSort(int arr[], int size)
{
int begin = clock(); // are for timing the sort
for (int i = 0; i < size; i++) //does the sorting
{
int j = i + 1;
int temp = arr[j];
while (arr[i] > arr[j])
{
arr[j] = arr[i];
arr[i] = temp;
j--;
i--;
}
}
int end = clock(); // are for timing the sort
cout << endl << "Your sorted array is: {";
for (int i = 0; i < size; i++) // prints out sorted array
{
cout << arr[i];
if (i != size - 1)
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl << "Your sort took: " << end - begin << " milliseconds" << endl << endl;
}
Additionally to #marom's answer, in your while loop, you don't put limitations neither on i or j, hence you try to access arr[-1], arr[-2] and so on. Also, you go back to the beginning of the sorted array, since you decrement i. Have a look at this code, compiled with g++ 4.8.1 gives no errors. Also, try to use std::swap defined in header <utility> since c++11 or in header <algorithm> until c++11.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <utility>
using namespace std;
void insertionSort(int arr[], int size);
int main()
{
int size;
srand(time(NULL));
cout << "Specify the size of your array: ";
cin >> size;
int theArray[size]; // creates an array of a size the user chooses
cout << endl << "Your current array: {";
for (int i = 0; i < size; i++) //prints out the original array
{
theArray[i] = rand() % 10000;
cout << theArray[i];
if (i != size - 1) // to beautify output
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl;
insertionSort(theArray, size);
}
void insertionSort(int arr[], int size)
{
int begin = clock(); // are for timing the sort
for (int i = 0; i < size - 1; i++) //does the sorting
{
int j = i + 1;
int temp = arr[j];
while (j > 0 && arr[j] < arr[j - 1])
{
// ^^ this ensures that we don't try to access arr[-1]
swap(arr[j], arr[j-1]); //prefer std functions if they do the job you want
j--;//we don't go back
}
}
int end = clock(); // are for timing the sort
cout << endl << "Your sorted array is: {";
for (int i = 0; i < size; i++) // prints out sorted array
{
cout << arr[i];
if (i != size - 1)
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl << "Your sort took: " << end - begin << " milliseconds" << endl << endl;
}
At least this is wrong:
void insertionSort(int arr[], int size)
{
int begin = clock(); // are for timing the sort
for (int i = 0; i < size; i++) //does the sorting
{
int j = i + 1;
When i is size-1 then j equals size and you get over the bounds of the array (valid values are from 0 to size-1 included). You need to limit your for loop to i < size-1
First advice : don't do all your printing or clock measure in your sort function. Keep that for your main program. Your sort function must remain clear and concise with no side effect.
Now, i find it better to split the code into 2 simple functions :
First, if arr is assumed already sorted up the index n-1
you want to insert the adequate element of the table at pos offset so that
arr will be sorted up to index n:
void insert(int arr[], int n){
int i=n, temp=arr[n];
while ( (arr[i-1]>temp) && (i>0) )
{
arr[i]=arr[i-1];
i--;
}
arr[i]=temp;
}
Now we just have to call our insertion for all offsets in arr except first one:
void insertionSort(int arr[], int size)
{
for(int n=1; n<size; n++) insert(arr,n);
}
As already mentioned by marom in his answer, when i = size - 1 you set j = size and access memory out of bounds, similarly, consider the case where j is set to the smallest element in the array, in that case you reach the left most position of the array by swapping the elements and decrementing, and eventually, i will become negative (since you do not put a bound to check if i becomes less than 0) and so will j and you will be accessing memory out of your bounds again.
Moreover, you are decrementing the value of i as well, which does not make sense, since by decrementing the value of i you are making extra runs for the external for loop.
So, your function shall look something like this ::
for (int i = 0; i < size - 1; i++) //changed the limit of for loop
{
int j = i + 1;
int temp = arr[j];
while ((j > 0) && (arr[j - 1] > arr[j])) //instead of working with the values of i, now we are doing everything with j
{
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
Hope this helps!
I'm trying to show a ranking list of my array qt, which contains 5 numbers.
int i, j;
int qt[5] = {10,20,10,50,20};
int tempqt;
for (i=0; i<5; i++)
{
for(j=(i+1); j<5; j++)
{
if (qt[i] >= qt[j])
{
tempqt = qt[i];
qt[i] = qt[j];
qt[j] = tempqt;
}
}
}
for(i=0; i<5; i++)
{
cout << i+1 << ".number: " << qt[i] << endl;
}
normally, the 2 for-loops sort my array and the last for-loop displays my array ordered, so it looks like this:
1.number: 10
2.number: 10
3.number: 20
4.number: 20
5.number: 50
But I want to display the numbers with the same value as the same ranking position, so like this:
1.number: 10
1.number: 10
2.number: 20
2.number: 20
3.number: 50
The idea is to increase rank counter when meet different value in qt array.
i = 0;
int rank = 1, val = qt[i];
cout << rank << ".number: " << qt[i] << endl;
for(i=1; i<5; i++)
{
if (qt[i] != val) {
++rank;
val = qt[i];
}
cout << rank << ".number: " << qt[i] << endl;
}
Use std::sort to sort the array -- you won't get anywhere until the array is sorted.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int qt[5] = { 10, 20, 10, 50, 20 };
sort(qt, qt + 5);
int count = 1;
for (int i = 0; i < 5; ++i)
{
if (i > 0)
{
if (qt[i] != qt[i - 1])
++count;
}
cout << count << ".number: " << qt[i] << endl;
}
}
Here is another solution using a map. This is more "lazy" in that there is no real "check if number already seen" logic involved. Just add numbers to a map, and print out the results in a loop.
If there are no memory constraints (you will need to create a map of the numbers, of course), and/or you need the array to remain stable (not sorted), then this could be an alternative.
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int qt[5] = { 10, 20, 10, 50, 20 };
std::map<int, int> IntMap;
// add entries to map, adding to a counter each time
for (int i = 0; i < 5; ++i)
IntMap[qt[i]]++;
// output the results.
int count = 1;
for (auto it = IntMap.begin(); it != IntMap.end(); ++it, ++count)
{
for (int i = 0; i < it->second; ++i)
cout << count << ".number: " << it->first << endl;
}
}
The map already sorts, so that's taken care of. Then the map is set up to count the number of times each number shows up, so that's taken care of. The only thing left is to write a loop that just goes through the map and prints the information.
See it here: http://ideone.com/q08SeX
I'd rather use a do while loop:
int p = 1, x = 0;
do
{
cout << p << ".number: " << qt[x++] << endl;
if (x < 5 && qt[x] != qt[x-1])
p++;
} while (x < 5);