I need to calculate numbers from the array.
I have a code written but I don't know how exactly I would need to write that I could get a summation of the numbers in the array.
If You would recommend some good material to learn something like so of, I would be thankful.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int n;
int array_1[20];
const char D[]= "Data.txt";
const char R[]="Rezults.txt";
void to_read ( int &n, int array_1[])
{
ifstream fd(D);
fd>>n;
for (int i=0; i<n; i++)
fd>>array_1[i];
fd.close();
}
int to_sum()
{
int m=0;
for (int i=0; i<n; i++)
m=m+array_1[i];
return m;
}
void to_print(int n, int mas_1[])
{
int sum=0;
ofstream fr(R);
fr<<n<<endl;
for (int i=0; i<n; i++)
fr<<array_1[i]<<" ";
fr<<endl;
sum=to_sum();
fr<<sum<<endl;
fr.close();
}
int main()
{
to_read(n, array_1);
to_sum();
to_print(n, array_1);
return 0;
}
I rewritten your code, removed global variables, changed formatting for easier reading, rename some variables to more explain for what they are and add function prototypes. Hope this will help you a little.
There are still lot of places which should be changed, but i want to keep as close to your original code as possible.
If you have any questions feel free to ask.
#include <iostream>
#include <fstream>
using namespace std;
//functions prototypes (these will be moved to header file if you wanna use this code from another file)
void to_read(int &len, int * array, const char * name); //added name parameter to avoid glogal variables
void to_print(int len, int * array, const char * name);
int to_sum(int len, int * array); //added parameters to avoid global variables
int main()
{
int lenght = 20; //moved to here, try to avoid global variables
int array_1[lenght]; //preconfigured size depend on variable
const char D[] = "Data.txt";
const char R[] = "Rezults.txt";
to_read(lenght, array_1, D);
//to_sum(lenght, array_1); //not needed here, not storing/processing result
to_print(lenght, array_1, R);
return 0;
}
void to_read(int &len, int * array, const char *name)
{
int lenght;
ifstream fd(name); //you should check if opening was successful
fd >> lenght; //you should check if reading was successful
if (lenght < len) len = lenght; //to prevent overflow of array, read max 20
for (int i=0; i<len; i++){
fd >> array[i];
}
fd.close();
}
int to_sum(int len, int * array)
{
int sum=0;
for (int i=0; i<len; i++){
sum += array[i]; //changed sum = sum + value; to sum += value; its same but this is more often used
}
return sum;
}
void to_print(int len, int * array, const char *name)
{
int sum = to_sum(len, array);
ofstream fr(name);
fr << len << endl;
for (int i=0; i<len; i++){
fr << array[i] << " ";
}
fr << endl;
fr << sum << endl;
fr.close();
}
Related
I don't understand how the following code can work.
void read(int *);
int numbers[10];
fstream myfile;
int main() {
myfile.open("input.txt", ios::in);
read(numbers);
for (int i = 0; i < 10; i++) {
cout << numbers[i] << endl;
}
}
void read(int *z) {
// is my understanding correct that *z is an pointer to the first element of the array?
for (int i = 10; i > 0; i--) {
myfile >> *z++; // why can write characters into an int array?
}
}
my_file has
basic_fstream<char>
as datatype.
however in the read function, it's values are written into an int array.
I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine.
this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
int sumOfElements(int[],int);
int number;
int sum=0;
int main()
{
int a[10];
getElements(a,5);
sumOfElements(a,5);
cout<<"The sum is "<<sumOfElements(a,5)<<endl;
return 0;
}
//Getting array's elements
void getElements(int numbers[],int size_)
{
for (int i=0; i<size_; i++)
{
cout<<"numbers["<<i<<"]: ";
cin>>number;
numbers[i]=number;
}
cout<<'\n';
}
//Calculation the sum of array's elements
int sumOfElements(int numbers[],int size_)
{
for(int i=0;i<size_;i++)
{
sum+=numbers[i];
}
cout<<sum<<endl;
return sum;
}
any idea? thank you in advance!
You defined int sum globally and were calling sumOfElementstwice, so sum contained twice what you expected.
Here is a modified version of your code that does what you want:
#include <iostream>
using namespace std;
void getElements(int[], int);
int sumOfElements(int[], int);
int main() {
int numbers[5];
getElements(numbers, 5);
cout << sumOfElements(numbers, 5);
return 0;
}
void getElements(int numbers[], int size) {
for (int i = 0; i < size; i++) {
cin >> numbers[i];
}
}
int sumOfElements(int numbers[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
return sum;
}
Here is a modified and simpler version of your program:
#include <array>
#include <iostream>
#include <numeric>
using namespace std;
int main(){
const int num_elements_to_sum = 5;
array<int, num_elements_to_sum> elements;
for(int i=0; i<num_elements_to_sum; ++i){
cin>>elements[i];
}
int sum = accumulate(elements.begin(), elements.end(), 0);
cout<<"Sum: "<<sum<<endl;
return 0;
}
C++ has a dedicated fixed size array container, use this instead of C-style arrays. This then allows to use standard library algorithms instead of your own implementation (e.g. accumulate).
Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max
We are converting base 10 to a number in a different base(B). I am having trouble with the void reverse function it will not reverse the order of the numbers.
string convertToBaseB(int num, int b){
int digit;
stringstream answer;
string x="";
while(num>0){
digit=num%b;
num/=b;
answer<<digit;
}
return answer.str();}
void reverse(int x[],int size){//reversing the
for(int k=0; k<size/2; k++){
int temp=x[k];
x[k]=x[size-k-1];
x[size-k-1]=temp;}
}
Your reverse function works fine. However it doesn't looks like C++ to me... In C++ I would have a vector and do:
std::vector<int> arr;
//... fill arr
std::swap_ranges(&arr[0], &arr[arr.size()/2], arr.rbegin());
If you want to stick with your for loop, at least use std::swap like this
void reverse(int x[],int size) {
for(int k=0; k<size/2; k++)
std::swap(x[k], x[size-k-1]);
}
Works for me:
#include <iostream>
using namespace std;
void reverse(int x[],int size)
{
for(int k=0; k<size/2; k++)
{
int temp=x[k];
x[k]=x[size-k-1];
x[size-k-1]=temp;
}
}
int main()
{
const int sz = 9;
int* digits;
digits = new int[sz];
for (int i=0; i < sz; ++i)
{
digits[i] = i;
}
reverse(digits, sz);
for (int i=0; i < sz; ++i)
{
cout<<digits[i]<<" ";
}
cout<<endl;
}
I have modified the code from my previous question, and now it looks like this:
//#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <cassert>
using namespace std;
const int MAX_SIZE=10000;
const int MAX_STRINGS = 10;
char** strings=new char*[10];
int len;
char* GetLongestCommonSubstring( char* str1, char* str2 );
inline void readNumberSubstrings();
inline const char* getMaxSubstring();
void readNumberSubstrings()
{
cin >> len;
assert(len >= 1 && len <=MAX_STRINGS);
for(int i=0; i<len;i++)
strings[i]=new char[MAX_SIZE];
for(int i=0; i<len; i++)
cin >> strings[i];
}
const char* getMaxSubstring()
{
char *maxSubstring=strings[0];
auto begin = chrono::high_resolution_clock::now();
for(int i=1; i < len; i++)
maxSubstring=GetLongestCommonSubstring(maxSubstring, strings[i]);
cout << chrono::duration_cast <chrono::milliseconds> (chrono::high_resolution_clock::now()-begin).count() << endl;
return maxSubstring;
}
char* GetLongestCommonSubstring( char* string1, char* string2 )
{
if (strlen(string1)==0 || strlen(string2)==0) cerr << "error!";
int *x=new int[strlen(string2)+ 1]();
int *y= new int[strlen(string2)+ 1]();
int **previous = &x;
int **current = &y;
int max_length = 0;
int result_index = 0;
int length;
int M=strlen(string2) - 1;
for(int i = strlen(string1) - 1; i >= 0; i--)
{
for(int j = M; j >= 0; j--)
{
if(string1[i] != string2[j])
(*current)[j] = 0;
else
{
length = 1 + (*previous)[j + 1];
if (length > max_length)
{
max_length = length;
result_index = i;
}
(*current)[j] = length;
}
}
swap(previous, current);
}
delete[] x;
delete[] y;
string1[max_length+result_index]='\0';
return &(string1[result_index]);
}
int main()
{
readNumberSubstrings();
cout << getMaxSubstring() << endl;
return 0;
}
It's still solving the generalised longest common substring problem, and now it's rather fast.
But there's a catch: if a user specifies, say, 3 as a number of strings he's about to enter, and then only actually enters one string, this code waits forever.
How do I change that?
If you read from a file and the number of arguments isn't equal to the number of arguments provided, just print a nice, clean error message to the user.
"Expected 7 arguments, received 3:"
Print out the arguments you found so the user has an idea of what the program is looking at when it spits out the error.
As for human input, I agree with the comments. The program should wait until the user close it or enters all the needed arguments.