For a project I need to write a program that reads in a series of positive integers, stored in an array, terminated by a -1. Then it should reverse the order of the array and print that along with the average of all the numbers.
ex: Input: 21 34 63
Output: 63 34 21 Ave: 39.3
I am not sure where to begin. I thought maybe getting a user input in a while loop. So,
int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
arr[i] = num;
i++;
}
cout << arr;
Okay so, first how do I create an array that takes user inputs and stores it as separate variables in the array? (Above is my unsuccessful attempt at that.)
Thats a simple problem. You first need to take the input and then reverse it.
int num=0, i,j,k;
const int SIZE = 99; //any upperbound value, just to ensure user doesnt enter more values then size of array
int arr [SIZE] = {0}; //better to initialize with 0
i = 0; //considering 0 indexed
int sum=0; // for average
while(num !=-1){
cout << "Enter a number: ";
cin >> num;
if(num!=-1)
{
arr[i] = num;
sum+=num;
}
i++;
}
int temp;
//now reversing
// size of the input array is now i
for(j=0,k=i-1;j<k;j++,k--)
{
temp=arr[j];
arr[j]=arr[k];
arr[k]=temp;
}
//what i am doing here is- keeping the index j on the beginning of the
//array and k to the end of the array. Then swap the values at j and k, then
//increase j and decrease k to move to next pair of points. We do this until j is
//less then k, means until we doesnt reach mid of the array
//printing the reversed array and average
cout<<"reversed array"<<endl;
for(j=0;j<i;j++)
cout<<arr[j]<<" ";
cout<<"average"<<float(sum)/i;
see the comments for suggestions
Since you are writing your program in c++, you should take a look at std::vector and the reverse function that the STL provides you.
Using the above tools the solution to your problem is the following:
#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse
int main()
{
std::vector<int> v;
int i;
float sum = 0.0f;
while(std::cin>>i && i != -1)
{
v.push_back(i);
sum+=i;
}
reverse(v.begin(),v.end());
for(int num : v)
std::cout<<num<<" ";
std::cout<<"average:"<<sum/v.size()<<std::endl;
}
Related
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.
I know how to do that without using a function ,for example for any n numbers I have the following program:
#include<stdio.h>
int main()
{
int n, i;
float sum = 0, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
return 0;
}
Or this one which do that using arrays:
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
But is it possible to use functions?if yes then how? thank you so much for helping.
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
In fact a complete example can require only a dozen or so additional lines, e.g.
#include <iostream>
#include <vector>
#include <numeric>
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
int main (void) {
int n; /* temporary integer */
std::vector<int> v {}; /* vector of int */
while (std::cin >> n) /* while good integer read */
v.push_back(n); /* add to vector */
std::cout << "\naverage: " << avg(v) << '\n'; /* output result */
}
Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).
Example Use/Output
$ ./bin/accumulate_vect
10
20
34
done
average: 21.3333
(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)
It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array
#include <iostream>
#include <vector>
float average(std::vector<int> vec)
{
float sum = 0;
for (int i = 0; i < vec.size(); ++i)
{
sum += vec[i];
}
sum /= vec.size();
return sum;
}
float average(int arr[],const int n)
{
float sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
}
sum /= n;
return sum;
}
int main() {
std::vector<int> vec = { 1,2,3,4,5,6,99};
int arr[7] = { 1,2,3,4,5,6,99 };
std::cout << average(vec) << " " << average(arr, 7);
}
This is an example meant to give you an idea about what needs to be done. You can do this the following way:
// we pass an array "a" that has N elements
double average(int a[], const int N)
{
int sum = 0;
// we go through each element and we sum them up
for(int i = 0; i < N; ++i)
{
sum+=a[i];
}
// we divide the sum by the number of elements
// but we first have to multiply the number of elements by 1.0
// in order to prevent integer division from happening
return sum/(N*1.0);
}
int main()
{
const int N = 3;
int a[N];
cin >> a[0] >> a[1] >> a[2];
cout << average(a, N) << endl;
return 0;
}
how to do that without using a function
Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?
The list of numbers (array of numbers)
Total numbers (n)
So let's first get the input from the user and put it into the array, you have already done it:
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
}
Now, lets make a small function i.e., calculateAverage():
int calculateAverage(int numbers[], int total)
{
int sum = 0; // always initialize your variables
for(int i = 0; i < total; ++i)
{
sum += numbers[i];
}
const int average = sum / total; // it is constant and should never change
// so we qualify it as 'const'
//return this value
return average
}
There are a few important points to note here.
When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,
pass the size information in the function, like we passed total
Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array
A few problems with your code:
using namespace std;
Don't do this. Instead if you want something out of std, for e.g., cout you can do:
using std::cout
using std::cin
...
or you can just write std::cout everytime.
int n, i;
float num[100], sum=0.0, average;
Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};
int n{}, i{};
float num[100]{}, sum=0.0, average{};
It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.
Ok, I'm very confused as to why this happens. All I'm trying to do is put 10 integers from input into an array. Why is this happening.
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
If you could please tell me where I'm going wrong, that would be very much appreciated. Thank you!
From how your code is written, you're only adding the user's input to the [10] element of intArray[] within that for loop you created. Additionally, any information added to the array at intArray[10] or beyond is placed out of bounds.
The only way I can really demonstrate what I mean is...
for (int i = 0; i < 10; i++)
{
std::cout<<"Enter a number:";
std::cin >> intArray[i];
}
Another thing I noticed is you're creating another array with the same name in your printData method. You should instead pass the intArray you're filling up with information to this method and use it to display your information.
The problem lies in this block of code-
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
As mentioned in other answers and comments you are storing all the values in the 10th memory slot of the array.
As per your comment
I forgot to mention, the output is just random integers and characters. EX: 00B3F724
00B3F724=> These are the memory address allocated to the array and which will hold the elements which will be inserted.
How array actually works-
float myArray[10];
The above snip creates 10 units of memory space. The units differ on the type which the array will hold. In this case it is holding float values, so each memory space will be of 4 bytes. All of these spaces have an address for lookup and other operations. All these spaces are expecting a float value to be inserted.
As you are using the loop you have to loop through the array(all the memory slots allocated to the array) and allocate a float element to each one of them and not only the last element(10th).
Effectively your for loop will become
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
Instead of intArray[10] insert values like this intArray[i]. As i will traverse through all the slots on every iteration of the loop insert a values to a slot.
Your code will look like
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
As you know if an array is declared as myArray[10], its index ranges from 0-9. Putting a value in myArray[10] will go out of bound and will produce garbage value.
In getData(float intArray[]) you are always overwriting the content of intArray[10] while it is out of bound so it is not being stored in an actual array. You should write your getData(float intArray[]) as following :
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cin >> intArray[i];
}
return 1;
}
Also in printData(float intArray[10]) you are only printing the base address of the array (i.e the name of the array gives the address of the 0th index).So the correct code would be:
void printData(float intArray[])
{
for(int i=0;i<10;i++)
{
cout << intArray[i]<<" ";
}
}
Simply change,
std::cin >> intArray[10];
to,
std::cin >> intArray[i];
What you are doing wrong:
you are storing the value at the 10th position (actually it is 11th position) again and again and the value at 10th position replaces with the new value again and also the 10th position doesn't exist in the array because the index of the array starts from 0, so your array has the index values from 0 to 9.
I'm creating this very simple C++ program.
the program asks the user to enter a few integers and stores them in an array.but when a specific integer(for example 50)is entered,the input is ended and then,all of the integers are displayed on the screen except for 50.
for example:
input:
1
2
88
50
output:
1
2
88
the error i'm getting is when i use cout to print the array,all of numbers are shown,including 50 and numbers i did'nt even entered.
this is my code so far:
#include<iostream>
int main() {
int num[100];
for(int i=0;i<=100;i++) {
cin >> num[i];
if (num[i]!=50) break;
}
for(int j=0;j<=100;j++) {
cout << num[j] << endl;
}
return 0;
}
Change the program the following way
#include<iostream>
int main()
{
const size_t N = 100;
int num[N];
size_t n = 0;
int value;
while ( n < N && std::cin >> value && value != 50 ) num[n++] = value;
for ( size_t i = 0; i < n; i++ ) std::cout << num[i] << std::endl;
return 0;
}
Here in the first loop variable n is used to count the actual number of entered values. And then this variable is used as the upper bound for the second loop.
As for your program then the valid range of indices for the first loop is 0-99 and you have to output only whose elements of the array that were inputed.
A do while loop is more suitable for your problem. The stop condition will check if the number fit inside the array (if k is not bigger than 100) and if number entered is 50.
#include<iostream>
using namespace std;
int main() {
int num[100];
int k = 0;
// A do while loop will be more suitable
do{
cin >> num[k++];
}while(k<100&&num[k-1]!=50);
for (int j = 0; j < k-1; j++) {
cout << num[j] << endl;
}
return 0;
}
Also, a better solution to get rid of 100 limitation is to use std::vector data structure that automatically adjust it's size, like this:
vector<int> num;
int temp;
do {
cin >> temp;
num.push_back(temp);
} while (temp != 50);
Note, you can use temp.size() to get the number of items stored.
You read up to 101 numbers, but if you enter 50 you break the loop and go for printing it. In the printing loop you go through all 101 numbers, but you actually may have not set all of them.
In the first loop count in a count variable the numbers you read until you meet 50 and in the printing loop just iterate count-1 times.
You have allocated an array of 100 integers on the stack. The values are not initialized to zero by default, so you end up having whatever was on the stack previously appear in your array.
You have also off-by-one in both of your loops, you allocated array of 100 integers so that means index range of 0-99.
As the question is tagged as C++, I would suggest that you leave the C-style array and instead use a std::vector to store the values. This makes it more flexible as you don't have to specify a fixed size (or manage memory) and you don't end up with uninitialized values.
Little example code (requires C++11 compiler):
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers; // Store the numbers here
for(int i = 0; i < 100; ++i) // Ask a number 100 times
{
int n;
std::cin >> n;
if( n == 50 ) // Stop if user enters 50
break;
numbers.push_back(n); // Add the number to the numbers vector
}
for (auto n : numbers) // Print all the values in the numbers vector
std::cout << n << std::endl;
return 0;
}
There are just 2 changes in your code check it out :
int main()
{
int num[100],i; //initialize i outside scope to count number of inputs
for(i=0;i<100;i++) {
cin >> num[i];
if (num[i]==50) break; //break if the entered number is 50
}
for(int j=0;j<=i-1;j++)
{
cout << num[j] << endl;
}
return 0;
}
Okay, others already pointed out the two mistakes. You should use i < 100 in the loop conditions instead of i <= 100 and you have to keep track of how many elements you entered.
Now let me add an answer how I think it would be better.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; // a temp variable in the for loop.
numbers.size() < 100 && // check that we have less than 100 elements.
std::cin >> temp && // read in the temp variable,
// and check if the read was a success.
temp != 50) // lastly check that the value we read isn't 50.
{
numbers.push_back(temp); // Now we just add it to the vector.
}
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i]; // Now we just print all the elements of
// the vector. We only added correct items.
}
The above code doesn't even read anymore numbers after it found 50. And if you want to be able to enter any number of elements you just have to remove the check that we have less than 100 elements.
Now I commented the above code a bit much, if you compress it it'll reduce to just:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i];
}
If you can use the C++11 standard it reduces to:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int element : numbers)
std::cout << element;
}
for (auto element : numbers) is new, it basically means for every int 'element' in 'numbers'.
I am very very new to C++ and I am trying to call the function "jacobi" which performs a user specified number of iterations for the jacobi method (or at least I hope so). On the line where I call 'jacobi' I get the error "No matching function to call to "jacobi". I have read other posts similar to this one and have tried to apply it to my own code but I have been unsuccessful. Maybe there are other issues in my code causing this problem. As mentioned I am very new C++ so any help would be appreciated and please break it down for me.
#include <iostream>
using namespace std;
void jacobi (int size, int max, int B[size], int A[size][size], int init[size], int x[size]){
////
//// JACOBI
////
int i,j,k,sum[size];
k = 1;
while (k <= max) // Only continue to max number of iterations
{
for (i = 0; i < size; i++)
{
sum[i] = B[i];
for (j = 0; j < size; j++)
{
if (i != j)
{
sum[i] = sum[i] - A[i][j] * init[j]; // summation
}
}
}
for (i = 0; i < size; i++) ////HERE LIES THE DIFFERENCE BETWEEN Guass-Seidel and Jacobi
{
x[i] = sum[i]/A[i][i]; // divide summation by a[i][i]
init[i] = x[i]; //use new_x(k+1) as init_x(k) for next iteration
}
k++;
}
cout << "Jacobi Approximation to "<<k-1<<" iterations is: \n";
for(i=0;i<size;i++)
{
cout <<x[i]<< "\n"; // print found approximation.
}
cout << "\n";
return;
}
int main (){
// User INPUT
// n: number of equations and unknowns
int n;
cout << "Enter the number of equations: \n";
cin >> n;
// Nmax: max number of iterations
int Nmax;
cout << "Enter max number of interations: \n";
cin >> Nmax;
// int tol;
// cout << "Enter the tolerance level: " ;
// cin >> tol;
// b[n] and a[n][n]: array of coefficients of 'A' and array of int 'b'
int b[n];
int i,j;
cout << "Enter 'b' of Ax = b, separated by a space: \n";
for (i = 0; i < n; i++)
{
cin >> b[i];
}
// user enters coefficients and builds matrix
int a[n][n];
int init_x[n],new_x[n];
cout << "Enter matrix coefficients or 'A' of Ax = b, by row and separate by a space: \n";
for (i = 0; i < n; i++)
{
init_x[i] = 0;
new_x[i] = 0;
for (j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
jacobi (n, Nmax, b, a, init_x, new_x);
}
The problem:
There are several problems, related to the use of arrays:
You can't pass arrays as parameter by value.
You can't pass multidimensional arrays as parameter if the dimensions are variable
You can't define arrays of variable length in C++
Of course there are ways to do all these kind of things, but it uses different principles (dynamic allocation, use of pointers) and requires additional work (especially for the access of multidimensional array elements).
Fortunately, there is a much easier solution also !
The solution:
For this kind of code you should go for vector : these manage variable length and can be passed by value.
For the jacobi() function, all you have to do is to change its definition:
void jacobi(int size, int max, vector<int> B, vector<vector<int>> A, vector<int> init, vector<int> x) {
int i, j, k;
vector<int> sum(size); // vector of 'size' empty elements
// The rest of the function will work unchanged
...
}
Attention however: the vectors can be of variable size and this jacobio implementation assumes that all the vectors are of the expected size. In professional level code you should check that it's the case.
For the implementation of main(), the code is almost unchanged. All you have to do is to replace array definitions by vector definitions:
...
vector<int> b(n); // creates a vector that is initialized with n elements.
...
vector<vector<int>> a(n,vector<int>(n)); // same idea for 2 dimensional vector (i.e. a vector of vectors)
vector<int> init_x(n), new_x(n); // same principle as for b
...
I have this homework question:
Write and test a program that read in n integers (max value for n is 20), each integer has
a value between 0 and 100 inclusive. You program should then print out the unique values
among the input numbers and the count of these values.
Sample input:
Enter a the number of integers = 8
Enter 8 integers: 5 6 7 6 6 17 17 35
Sample output:
Number 5: 1
Number 6: 3
Number 7: 1
Number 17: 2
Number 35: 1
This is what I did:
#include<iostream>
using namespace std;
int main(){
int a[20], n;
cout<< "Please enter the number of integers= ";
cin>> n;
cout<<"Please enter"<< n<<" integers: ";
for (int i=0; i<n; i++)
cin >> a[i];
for (int k=0; k< n; k++){
int sum=0;
for (int i=0; i< n; i++){
if (a[i]==a[k])
sum= sum+1;
}
cout<< "Number "<< a[k]<<" : "<< sum<< endl;
}
}
Consider that when you iterate through your list, you're checking all values with both i and k. So essentially, if you had a list of 1 1 2 2, then the first one will count itself, and the 1 at a[1]. The second 1 will count the first 1 and itself, giving you your repeated output.
A way to simplify this would be to make use of a hash_map, or some similar structure (I'm not as familiar with C++) that maps a key to a value and doesn't allow repeats. This would allow you to record the unique numbers as keys, and increment them with only one pass through the list. The advantage to using the hashMap is that you make your program linear (although I don't think that's really a concern at this stage).
The simplest way to solve your problem, however would be to use a Bin sort technique. The underlying idea here is that your number range is simply 0 to 100, meaning you could create bins for 0 to 100 and increment each one. Again, this is Java code, and doesn't have any actual input for a.
// Count is the key, it uses indexes from 0 to 100, with null values of
// 0 after initialized. Simply iterate the loop, and use the value of
// a[k] to increment the corresponding count in the count array.
// Finally, print the results
int[] a = new int[20];
int[] count = new int [101];
for (int k = 0; k < a.length; k++){
count[a[k]]++;
for (int i = 0; i < count.length; i++){
if (count[i] > 0)
System.out.println(i + ": " + count[i]);
}
Add another bool b[20] ,initialize it with true. Then every time you detect a[k] is a dupe, you set b[k] = false. Only print a[k] if b[k] == true
for (int k = 0; k < n; k++) {
if (!b[k]) {
continue;
}
int sum = 0;
for (int i = 0; i < n; i++) {
if (a[i] == a[k]) {
sum = sum + 1;
b[i] = false;
}
}
cout << "Number " << a[k] << " : " << sum << endl;
}
You have to keep a running count of the items you processed in a separate array, and before running your inner loop to count the items, check if he item you're trying to count isn't in your second array already.
Before you print the result, check if you already printed it for this number
Here's my new attempt.
A quick fix (while not the most professional) would be to create another loop checking for repeats right before printing out.
I took your current big loop and turned it into an even bigger monster.
I also tested it out and it works for me. =D
for (int k=0; k< n; k++){
int sum=0;
for (int i=0; i< n; i++)
{
if (a[i]==a[k])
sum= sum+1;
}
bool repeat = false;
for(int i = 0; i < k; i++)
{
if(a[k] == a[i])
{
repeat = true;
}
}
if(!repeat)
cout<< "Number "<< a[k]<<" : "<< sum<< endl;
}
An alternate implementation (and more memory-hungry with your current limit of 20 input values) would be to create an array of 100 "count" values. Increment the appropriate item for each input value, then iterate through the count array outputting non-zero values.
Apparently that description wasn't good enough... perhaps some code would help (NOTE:This code is untested, but should be enough for you to understand the concept):
#include<iostream>
using namespace std;
int main(){
int a[101], n, v;
cout<< "Please enter the number of integers= ";
cin>> n;
cout<<"Please enter"<< n<<" integers: ";
for (int i=0; i<n; i++)
{
cin >> v;
a[v] ++;
}
for (int k=0; k< 100; k++){
if (a[k] > 0)
{
cout<< "Number "<< k + 1 <<" : "<< a[k] << endl;
}
}
}
}
getting familiar with Standart Template Library is the key to writing good programs in my humble opinion, since this is a homework, you do the controlling for 0 and 100 ;-))
#include <iostream>
#include <map>
using std::cin;
using std::map;
using std::cout;
using std::endl;
int main()
{
int limit = 20;
int cnt=0;
int n;
map<int, int> counters;
while( cnt++ < limit )
{
cin >> n;
++counters[n];
}
for(map<int, int>::iterator it = counters.begin();
it!=counters.end(); ++ it)
cout << it->first << " " << it->second << endl;
return 0;
}