A lab assignment that I have for a beginner C++ class involves printing the squareroot of a series of numbers stored in an array. The program itself works, but my teacher does not want us to use global variables.
void assignValue(){
for (int x=0; x<10; x++){
int num;
num = rand() % 100 + 1;
if (num % 2 != 0){
num += 1;
}
arr[x] = num;
}
Here's the main method
int main() {
srand(static_cast<unsigned int>(time(0)));
assignValue();
for (int f = 0; f < 10; f++){
cout << f << setw(8) << right << arr[f];
float square = sqrt(arr[f]);
cout << setw(8) << right << fixed << setprecision(3) << square << endl;
}
The arr is a global variable above the main method.
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
void assignValue(int arr[], size_t n) {
for (int i=0; i<n; ++i) {
int num;
num = std::rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
int main() {
const size_t size = 10;
int arr[size];
std::srand(static_cast<unsigned int>(std::time(0)));
assignValue(arr, size);
for (int i = 0; i < size; ++i){
std::cout << i << std::setw(8) << std::right << arr[i];
float square = std::sqrt(arr[i]);
std::cout << std::setw(8) << std::right << std::fixed << std::setprecision(3) << square << std::endl;
}
return 0;
}
Here is a suggestion for the function taking an array reference:
// headers omitted (you'll need additionally iomanip, ctime, cstdlib, cmath)
// The constant is necessary because the function takes
// a reference to an array *of this specific size*
const size_t ARR_SIZE = 10;
// Take a reference to the array (the array is not copied)
void assignValue(int (&arr)[ARR_SIZE])
{
for (int i = 0; i < ARR_SIZE; i++) {
int num = rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
You call the function simply with
int main()
{
int arr[ARR_SIZE];
// [...]
assignValue(arr);
// ...
}
The following is a more Core Guideline compliant way of doing this as no pointers, or size information is needed.
#include <cstddef>
#include <cstdlib>
template<typename T, std::size_t N>
void assignValue(T (&arr)[N])
{
for (auto &elem : arr) {
elem = rand() % 100 + 1;
if (elem % 2 != 0) {
elem += 1;
}
}
}
auto
main() -> int
{
constexpr const auto ARRAY_SIZE = 10;
int arr[ARRAY_SIZE];
assignValue(arr);
return 0;
}
Related
So I am making a program that calls functions to generate random numbers. Then calls a function to print those results. The second thing I want to print is the random numbers but after they are sorted in ascending order. After some tweaking with the ascending order function for an array, I try displaying it with my print function and nothing happens
Originally it did display as a second part of the output, but it didn't work and only showed 0's. Now I think I fixed the code but now it won't even display anything in the output so I have no way to check if its working and I am really confused as to why
#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;
#define lowerbound 10.0
#define upperbound 950.0
#define min_values 75
#define max_values 150
#define max_val_file 40
#define max_output 12
double randDouble();
int buildRandom(double array[]);
void print(string, double array[], int);
void sort(double array[], int);
int main()
{
srand(19);
int num_vals;
double random_array[max_values];
double sorted_array[max_values];
string title1 = "Random Values";
string title2 = "Sorted Random Values";
num_vals = buildRandom(random_array);
cout << "There are " << num_vals << " values in the first array" << '\n';
print(title1, random_array, num_vals);
sort(random_array, num_vals);
cout << '\n';
print(title2, sorted_array, num_vals);
}
double randDouble()
{
int random_integer = rand();
double random_value;
random_value = lowerbound + (random_integer / (RAND_MAX / (upperbound - lowerbound)));
return random_value;
}
int buildRandom(double random_array[])
{
int num_vals = min_values + rand() % (max_values - min_values + 1);
int i;
double random_num;
for (i = 0; i < num_vals; ++i)
{
random_num = randDouble();
random_array[i] = random_num;
}
return num_vals;
}
void print(string title, double random_array[], int num_vals)
{
int i;
cout << '\n' << title << '\n' << '\n'<< setw(8);
for (i = 0; i < num_vals; ++i)
{
cout << setprecision(3) << fixed << random_array[i] << setw(9);
if ((i + 1) % max_output == 0)
{
cout << '\n' << setw(8);
}
}
}
void sort (double sorted_array[], int numberOfValues)
{
int top = 0;
int x, SSF, PTR;
double swap;
double last = numberOfValues - 1;
for (top = 0; top < last; ++top)
{
PTR = top;
SSF = top;
for (x = 0; PTR < last; ++x)
{
if (sorted_array[PTR] < sorted_array[SSF])
{
SSF = PTR;
}
}
swap = sorted_array[SSF];
sorted_array[SSF] = sorted_array[top];
sorted_array[top] = swap;
}
}
Can you help me with this problem? All I could do was count all the negative numbers.
Here is my code:
using namespace std;
int main()
{
const int SIZE = 10;
int arr[SIZE]{};
int number=0;
srand(time(NULL));
cout << "Your array is: " << endl;
for (int i=0; i<SIZE; i++)
{
int newValue = rand()%20-10;
arr[i] = newValue;
cout << arr[i] << " ";
if (arr[i] < 0)
{
for (int j=-1; j<SIZE; j++)
{
number = arr[i];
sum += fabs(number);
break;
}
}
}
cout << endl;
cout << "Sum of elements after first element < 0 is: " << sum;
cout << endl;
}
One way is to have a flag that is zero to start with that is switched on after the first negative:
int flag = 0;
int sum = 0;
for (std::size_t i = 0; i < SIZE; ++i){
sum += flag * arr[i];
flag |= arr[i] < 0;
}
This approach carries the advantage that you don't need an array at all: substituting the next number from standard input for arr[i] is sufficient.
In your specific case, there are numerous simple and efficient solutions, like that offered by Bathsheba.
However, for a more general case of summing elements in an array after the first value satisfying a given condition, you can use the std::find_if and std::accumulate functions from the STL, providing appropriate lambda functions to do the test (checking for negative) and summation (the sum += fabs(number) in your code implies that you want to sum the absolute values of the remaining elements1).
Here's a possible implementation:
#include <cstdlib> // std::abs, std::rand
#include <ctime> // std::time
#include <algorithm> // std::find_if
#include <numeric> // std::accumulate
#include <iostream>
using std::cout, std::endl;
int main()
{
const int SIZE = 10;
int arr[SIZE]{};
// Generate random array...
std::srand(static_cast<unsigned int>(time(nullptr)));
cout << "Your array is: " << endl;
for (int i = 0; i < SIZE; i++) {
int newValue = std::rand() % 20 - 10;
arr[i] = newValue;
cout << arr[i] << " ";
}
// Sum all abs values after first negative ...
auto is_neg = [](int i) { return i < 0; };
auto fn = std::find_if(std::begin(arr), std::end(arr), is_neg);
auto sum_abs = [](int a, int b) { return a + std::abs(b); };
// Set the sum to ZERO if the first negative is the last element...
int sum = (fn == std::end(arr)) ? 0 : std::accumulate(++fn, std::end(arr), 0, sum_abs);
cout << endl;
cout << "Sum of elements after first element < 0 is: " << sum;
cout << endl;
return 0;
}
1 If this is not the case, and you just want the sum of the actual values, then you can omit the 4th (sum_abs) argument in the call to std::accumulate (and the definition of that lambda).
If input A < 10^1000 , b = common int <100000
how can Ii know that A is multiple of B or not?
int main()
{
int testcase = 0;
cin >> testcase;
for (int i = 0; i < testcase; i++)
{
long long num;
int div = 0;
cin >> num >> div;
if (num % div == 0)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
}
return 0;
}
this is what i tried.
The first step is to read (or set) the large number as a string.
The second step consists in convert this string to a vector of int, each int being less than 10000.
The last step is to calculate a modulo b, in the same way we are performing a division by hand
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
std::vector<int> conver_to_vect_int (const std::string &a) {
std::vector<int> x;
int n = a.size();
x.reserve (n/5 + 1);
for (int i = 0; i < n; i += 5) {
int max = std::min (i+5, n);
std::string s (a.begin() + i, a.begin() + max);
int number = std::stoi (s);
x.push_back (number);
}
return x;
}
int modulo (const std::string &a_string, int b) {
std::vector<int> a = conver_to_vect_int (a_string);
int mod = 0;
for (int val: a) {
int val_with_mod = mod * 100000 + val;
mod = val_with_mod % b;
}
return mod;
}
int main() {
std::vector<std::string> list_s = {"29", "111111111", "111111111111111111111111111111111111", "111111111111111211111111111111111111"};
int b = 9;
for (auto &s: list_s) {
int mod = modulo (s, b);
bool divisibility = mod == 0;
std::cout << "divisibility of " << s << " by " << b << " = " << divisibility << "\n";
}
}
I would like to create an array i_array with 15 elements and rate every element with formula
a = sin((Pi * (i - 7)) / 15)
and return it.
#include <cmath>
#include <cstddef>
#include <iostream>
void sinuss(double (&arr)[15]) {
for (int i = 0; i < 15; ++i) {
arr[i] = std::sin((M_PI * (i - 7)) / 15);
std::cout << arr[i] << ' ';
}
std::cout << '\n';
}
void modBinSearch(double arr[], double start, double end){
if (start > end){
return -1;
}
const int mitte = start +((end-start)/2);
if(arr[mitte] == 0.0){
return mitte;
}
else if(arr[mitte] > 0.0){
return modBinSearch(arr[], start, mitte-1);
}
return modBinSearch(arr, mitte+1,end);
}
int main() {
double i_array[15];
sinuss(i_array);
for (int i = 0; i < 15; ++i) {
std::cout << i_array[i] << ' ';
}
std::cout << '\n';
int arr[] = sinuss(i_array);
int n = sizeof(arr)/sizeof(arr[0]);
int result = modBinSearch(arr, 0, n-1);
return 0;
}
I have no idea. I don't know what my error is.
I am new in C++, because it I have a lot of problem with it:(
In my function sinuss() I should return rated elements as array and in function modBinSearch() I should return the least element who not smaller as 0.0 is. But my programm is wrong :(
There are usually better ways to write loops that use a sequence of floating-point values, such as using an integer for loop control and calculating the floating-point value from the integer in each iteration. (Alternatively, you can use a floating-point object for loop control but take care to use only integer values for the loop expressions.)
Define a type of what you desire. Suggesting a std::array<double,15>. It makes coding what you want more natural.
#include <array>
#include <iostream>
#include <cmath>
using namespace std;
using ArrOf15Dbl = array<double, 15>;
ArrOf15Dbl sinuss() {
ArrOf15Dbl i_array;
for (int i = 0; i < 15; ++i) {
i_array[i] = sin((M_PI * (i - 7)) / 15);
cout << i_array[i] << ' ';
}
cout << '\n';
return i_array;
}
int main() {
ArrOf15Dbl x = sinuss();
for (auto i : x) {
cout << i << ' ';
}
cout << '\n';
}
But returning arrays from a function is not possible with C++98/03. So one solution is to allocate the needed memory dynamically, but don't forget to release it later!
#include <cmath>
#include <cstddef>
#include <iostream>
int const kArrSiz = 15;
// OBS: caller assumes ownership of array pointer!
// Must be deleted with "delete [] foobar;"
double* sinuss() {
double* i_array = new double[kArrSiz];
for (int i = 0; i < kArrSiz; ++i) {
i_array[i] = std::sin((M_PI * (i - 7)) / kArrSiz);
std::cout << i_array[i] << ' ';
}
std::cout << '\n';
return i_array;
}
int main() {
double* x = sinuss();
for (int i = 0; i < kArrSiz; ++i) {
std::cout << x[i] << ' ';
}
std::cout << '\n';
delete [] x;
return EXIT_SUCCESS;
}
But with a change of interface to your function, it can be made safer by requiring the caller to allocate the array and your function instead fills it with your required values.
void sinuss(double (&arr)[15]) {
for (int i = 0; i < 15; ++i) {
arr[i] = std::sin((M_PI * (i - 7)) / 15);
std::cout << arr[i] << ' ';
}
std::cout << '\n';
}
int main() {
double i_array[15];
sinuss(i_array);
for (int i = 0; i < 15; ++i) {
std::cout << i_array[i] << ' ';
}
std::cout << '\n';
return EXIT_SUCCESS;
}
I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}
The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}
Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}
Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}