so my program should be able to take several numbers from the user until the last number is "999". Then, it should be able to print out an array having all the numbers entered sorted. I have to use sorting by selection (by comparing values in each index).
I tried by best and i don't seem to know what is going wrong
this is my code: (sorry for the lack of tidiness and comments, I'm in a hurry)
#include <iostream>
using namespace std;
int main() {
int n;
int i;
int sentinel =999;
int A[250];
cout <<"Please enter the list of nbs ending with 999"<< endl;
cin>>n;
i=0;
int nblist;
while(n!=sentinel)
{
A[i]=n;
cin>>n;
i++;
}
nblist = i-1;
int minindex;
i =0;
int min;
int k;
k=0;
min=A[k];
for(k=0;k<nblist;k++)
{cout<<k<<endl; int i =0;
while(i<nblist){
cout<<i<<endl;
if (A[i]< min)
{
min= A[i];
if (A[i]==min)
{minindex=j;}
i++;
//cout<< "the array containing min is "<< minindex << endl;
}
cout<<"The nb of array is "<<i<<"its filled with"<< A[i]<<endl;
}int temp;
temp= A[k];
A[k]=A[minindex];
A[minindex]=temp;
//cout<<"The nb of array is "<<k<<"its filled with"<< A[k]<<endl;
//cout<<"The nb of array is "<<minindex<<"its filled with"<< A[minindex]<<endl;
int counter=0;
while(counter<nblist)
{ cout<<"The nb of array is "<<counter<<"its filled with"<< A[counter]<<endl;
counter++;
}
}
return 0;
}
Related
#include <iostream>
using namespace std;
int main()
{
int n;
n=4;
int arr[n]={1,2,3,8};
int sum;
sum=5;
int curr=0;
cin>>sum;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
curr+=arr[j];
if(curr==sum){
cout<<i;
}
cout<<curr<<endl;
}
}
}
For the given question I need to find the starting and ending index of such a subarray. I have tried the above code but am not able to get the right output. Please guide me.
I think your code only needs some minor modifications. You should add
some code to handle the case where your running sum is greater than the target sum, and you should also re-initialize your running sum correctly.
There may be some efficient solution that is faster than O(n^2), which I am not aware of yet. If someone knows of a solution with a better time complexity, please share with us.
Below is a simple algorithm that has the time complexity of O(n^2). (It may not have the most efficient time complexity for this problem).
This function prints out the 2 indices of the array. The sum of all elements between these 2 indices inclusively will equal the target sum.
void Print_Index_of_2_Elements(int array[], int total_element, int target)
{
// Use Brute force . Time complexity = O(n^2)
for (int i = 0; i < total_element; i++)
{
int running_sum = array[i];
// Second for loop
for (int j = (i + 1) ; j < total_element; j++)
{
if (running_sum == target)
{
cout << "Two indices are: " << i << " and " << j;
return; // Found Answer. Exit.
}
else if ( running_sum > target )
break;
else // running_sum < target
running_sum += array[j];
}
}
cout << " Sorry - no answer was found for the target sum.";
}
If you are someone that is a beginner in subarrays or arrays for the case. Then this code is for you:
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int sum;
cin>>sum;
int curr=0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(curr==sum){
cout<<i+1<<" "<<j;
return 0;
}
else if (curr>sum){
curr=0;
}
else if(curr<sum){
curr+=arr[j];
}
}
}
return 0;
}
If you have any doubts regarding this, feel free to comment and let me know.
I am testing the ability to use functions to input values in 2 arrays and also to perform addition of the values. I wish to input the different values in the 2 arrays using a function inputArray(A1, A2, size) using a For loop.
I also used a function sumArray(A1, A2, size) to perform the addition of the 2 values in the arrays.
But the issue is with the input function as when i am running the program to input different values in the 2 arrays, the first array is also been attributed the value of the second array.
void inputArray(int Array1[], int Array2[], int n)
{
for(int i=0; i<n; i++)
{
cout<<"Array 1:"<<endl;
cin>>Array1[i];
cout<<" Array 2: "<<endl;
cin>>Array2[i];
cout<<endl;
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[0]="<<Array2[0]<<endl;
}
}
I tried to use 2 different functions to input the values and this worked.But then again when i used a FOR loop for the Addition function sum = sumArray(A1, A2, size), both arrays A1 and A2 were being attributed the value of the second array.
int sumArray(int Array1[], int Array2[], int n)
{
int sum= 0;
for(int i=0; i<n; i++)
{
sum+= ( Array1[i] + Array2[i] );
cout<<"The total sum so far for values till position "<<i<<" is "<<sum<<endl;
}
//to monitor if the program is performing well with the addition
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[1]="<<Array2[2]<<endl;
return sum;
}
#include<iostream>
using namespace std;
void inputArray(int Array1[], int Array2[], int n)
{
for(int i=0; i<n; i++)
{
cout<<"Array 1:"<<endl;
cin>>Array1[i];
cout<<" Array 2: "<<endl;
cin>>Array2[i];
cout<<endl;
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[0]="<<Array2[0]<<endl;
}
}
//To sum all the values in the 2 arrays//not asked in the question
int sumArray(int Array1[], int Array2[], int n)
{
int sum= 0;
for(int i=0; i<n; i++)
{
sum+= ( Array1[i] + Array2[i] );
cout<<"The total sum so far for values till position "<<i<<" is "<<sum<<endl;
}
//to monitor if the program is performing well with the addition
//test
cout<<"\n\t A1[0]= "<<Array1[0]<<endl;
cout<<"\n\t A2[1]="<<Array2[2]<<endl;
return sum;
}
int main()
{
int size;
int A1[size];
int A2[size];
size= 3;
cout<<"Input "<<size<<" values in the first and second array: "<<endl;
inputArray( A1, A2, size); //do not write square bracket when calling a function
int sum = sumArray(A1, A2, size);
cout<<"The sum of the total values is : "<<sum<<endl;
//test
cout<<"\n\t A1[0]= "<<A1[0]<<endl;
cout<<"\n\t A2[1]="<<A2[2]<<endl;
return 0;
}
Here you use a non-initialised variable for the size of the two arrays.
int size;
int A1[size];
int A2[size];
This is in C++ wrong in more than one way.
You need to define C-like arrays with a constant size.
Safer would be to use C++ containers, e.g. std::vector for anything without predictable size.
Even in C, where VLAs are possible, creating them like you did and LATER reading in a new value for size will not change anything, especially not the size of the arrays.
Also, but that is already inside undefined behaviour and purely speculative,
if the compiler understands that as A1 and A2of size 0, then the start of both arrays is the same and writing to one writes also to the other - AND be totally forbidden because it will access beyond any arrays size.
To demonstrate that, try
int A1[5];
int A2[5];
This is relatively basic but I'm trying to write a function that sorts an array in C++ and I don't want to do it the regular way. I made a loop to find the greatest number in array, store it as "max", save max as the current value in another array and then change the value to zero so that by the time the loop runs the next time, the previous max number will no longer be the maximum, letting the next highest take its place but for some reason, this doesn't work. what did I do wrong?
#include <iostream>
using namespace std;
void mysort(int arr[10]){
int max = 0;
int high[10];
int count;
for (int j=0; j<10; ++j){
for(int i=0; i<10; ++i){
if (arr[i]> max){
max= arr[i];
count=i;
}
}
cout<<"the "<< count+1<<" largest is: "<< max<<"\n";
high[j]= max;
*arr[count]= 0;
}
}
main(){
int pass[10] = {1,2,3,4,5,6,7,8,9,0};
mysort(pass);
}
Your max never gets reset, so on first iteration it gets set to 9 and stays that for the rest of the execution
#include <iostream>
using namespace std;
void mysort(int arr[10]){
// int max = 0; **this was the problem**
int high[10];
int count;
for (int j=0; j<10; ++j){
int max = 0;
for(int i=0; i<10; ++i)
{
if (arr[i]> max)
{
max= arr[i];
count=i;
}
}
cout<<"the "<< count+1<<" largest is: "<< max<<"\n";
high[j]= max;
arr[count]= 0;
}
}
int main(){**you should also add return type to int main**
int pass[10] = {1,2,3,4,5,6,7,8,9,0};
mysort(pass);
}
Your inner loop always set max to 9 on its final iteration, and your outer loop only ever reads max once the inner loop is completed, so high[j] will always be 9.
So I'm totally new to pointers, I apologize for this, I'm supposed to pass an array of pointers and get the mode of that array. After the array passes as a set of pointers, I can't manipulate the array to find the mode, everything I try results in a syntax error.
EDIT: I changed list to an array of pointers and I get a runtime error.
int main()
{
int size=0;
int *list[size];
cout<<"Please enter the size of your array: ";
cin>>size;
cout<<"\nPlease enter the numbers in your list seperated by spaces: ";
for(int i=0;i<size;i++)
{
cin>>*list[i];
}
cout<<endl;
int mode=getMode(list,size);
cout<<"\n"<<mode<<endl;
return 0;
}
int getMode (int* list[], int arraySize)
{
cout<<"The array you entered is listed below\n "<<list[0];
for(int i=0;i<arraySize;i++)
{cout<<setw(3)<<list[i];}
int *number=list[0];
int count1=0;
int count2=0;
int mode=0;
for(int j=1;j<arraySize;j++)
{
for(int i=1;i<arraySize;i++)
{
if(list[i]==number)
{
count1++; //counts the number of instances that the number occurs
}
}
if(count1>count2)
{
mode= *list[j];
count2=count1;
}
count1=0;
}
return mode;
}
When you pass an array to a function, it automatically decays to a pointer, so you don't need to use &list. And in the function, you shouldn't declare it int *list[], it should just be int list[] or int *list.
Also, in the getMode() function, you need to count the matches of list[j]. You're just counting the repetitions of number, which is list[0].
#include <iostream>
#include <iomanip>
using namespace std;
int getMode (int list[], int arraySize)
{
cout<<"The array you entered is listed below\n "<<list[0];
for(int i=0;i<arraySize;i++)
{cout<<setw(3)<<list[i];}
int count1=0;
int count2=0;
int mode=0;
for(int j=0;j<arraySize;j++)
{
for(int i=0;i<arraySize;i++)
{
if(list[i]==list[j])
{
count1++; //counts the number of instances that the number occurs
}
}
if(count1>count2)
{
mode= list[j];
count2=count1;
}
count1=0;
}
return mode;
}
int main()
{
int size;
int *list;
cout<<"Please enter the size of your array: ";
cin>>size;
list=new int[size];
cout<<"\nPlease enter the numbers in your list seperated by spaces: ";
for(int i=0;i<size;i++)
{
cin>>list[i];
}
cout<<endl;
int mode=getMode(list,size);
cout<<"\n"<<mode<<endl;
return 0;
}
DEMO
I am trying to finish a problem where I read a file into the program and output a file with the average, min, max, and the count of how many times that number occurred in the program. However, I cannot figure out how to create an array for duplicated number of the "counts".
If the file that I was trying to read in had the values 19 5 26 5 5 19 16 8 1,
I need the outputted file to read 5---3 times; 8---1 time; 16---1 time; 19--2 times; 26--1 times.
I first sorted my array to read 5 5 5 8 16 19 19 26.
Below is my code with explanations of what I was trying to do:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
double averageArray(int a[], int length); // user defined function to get average
int maxval(int a[], int length); //user defined function to get max val
int minval(int a[], int length); //user defined function to get min val
void bsort(int arr[], int length);// udf to sort array from min to max
int countArray(int a[], int length); //attempt to create a function to get the number of occurrences of a number that is duplicated
int main()
{
char infilename[16];
int nums[50];//newly created array to read in the numbers from the file
int length(0);//array has a length defined by "length"
ifstream fin;
ofstream fout;
cout << "Please enter an input file name: ";
cin >> infilename;
cout << endl;
fin.open(infilename);
if (fin.fail())
{
cerr << "The file " << infilename << " can't be open!"<<endl;
return 1;
}
cout<<"The output to the file statistics.txt should be as follows: "<<endl;
fout.open("statistics.txt");
fout<<"N"<<"\t"<<"Count"<<endl;
cout<<"N"<<"\t"<<"Count"<<endl;
while (fin >> nums[length])
length++;
bsort(nums, length);
for (int i=0; i<length; i++) {
if (nums[i]==nums[i-1]) {
continue;
}
cout<<nums[i]<<"\t"<<countArray(nums,length)<<endl;
fout<<nums[i]<<"\t"<<endl;
}
cout << "\nAverage: " << averageArray(nums,length) << endl;
cout << "Max: "<< maxval(nums,length)<<endl;
cout << "Min: "<< minval(nums,length)<<endl;
fin.close();
return 0;
}
double averageArray (int a[], int length)
{
double result(0);
for (int i = 0; i < length ; i++)
result += a[i];
return result/length;
}
int maxval(int a[], int length)
{
int max(0);
for (int i=1; i<length; i++)
{
if (a[i]>max)
max=a[i];
}
return max;
}
int minval(int a[], int length)
{
int min(100);
for (int i=1; i<length; i++)
{
if (a[i]<min)
min=a[i];
}
return min;
}
void bsort(int a[], int length)
{
for (int i=length-1; i>0; i--)
for (int j=0; j<i; j++)
if (a[j]>a[j+1])
{
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int countArray(int a[], int length)
{
int counter(0);
for (int i=0; i<length; i++){
if (a[i]==a[i+1]) //loop through array and if the number after is the same as the previous number, then count one
counter++;
}
return counter;
}
Though it compiles, the count only shows "3"s as shown in the picture below:
.
Before I give you the solution, please take a moment to remember, you are programming in C++, not C. As such, you ought to use vectors, istream iterators and std::sort. You also ought to use std::map, which easily accomplishes this purpose:
template <typename It>
std::map<int, int> count_occurrences(It it, It end)
{
std::map<int, int> output;
while (it != end) output[*it++]++;
return output;
}
How to combine this with your existing code is left as an exercise for the reader. I suggest you ought to read about iterators.
Your function int countArray(int a[], int length) has no input for the actual number. It always counts how often there are the same numbers behind each other in your array. That happens two times for fives and once for 19 => 3 times.
Solution:
int countArray(int a[], int length, int num)
{
int counter(0);
for (int i=0; i<length; i++){
if (a[i]==num) //loop through array and if the number is the one you are looking for
counter++;
}
return counter;
}
and call you function: countArray(nums, length, nums[i]);
void countArray(int a[], int length)
{
int counter(1);
bool flag(false);
//you take (i+1) index, it can go out of range
for (int i = 0; i < length - 1; i++){
if (a[i]==a[i+1]){ //loop through array and if the number after is the same as the previous number, then count one
flag = true;
counter++;
}
else {
if (flag){
cout<<a[i] << counter << endl;
}
flag = false;
counter = 1;
}
}
}
I didn't code on C for a long time, but I hope it'll help.
This procedure will print you the answer, and you have to call it just once.
I suggest to use std::map which is the best solution to solve your problem. I will try to explain easily the differents steps to do this:
I consider your variables initialized, for instance:
int length = 9;
int nums[length] = {19, 5, 26, 5, 5, 19, 16, 8, 1};
Create the std::map<int,int>, where the key (first int) will be your number and the value (second int) the number of occurence of this number store in the key.
std::map<int,int> listNumber;
Fill your map
// For all numbers read in your file
for(int i=0; i<length; ++i)
{
// Get number value
int n = nums[i];
// Find number in map
std::map<int, int>::iterator it = listNumber.find(n);
// Doesn't exists in map, add it with number of occurence set to 1...
if(it == listNumber.end())
{
listNumber.insert(std::pair<int,int>(n,1));
}
// ... otherwise add one to the number of occurence of this number
else
{
it->second = it->second+1;
}
}
Read the map
// Read all numbers and display the number of occurence
std::cout << "N" << "\t" << "Count" << std::endl;
for(std::map<int, int>::iterator it = listNumber.begin(); it!=listNumber.end(); ++it)
{
std::cout << it->first << "\t" << it->second << std::endl;
}