How do I edit the given program to get all possible combinations of array values which will provide the given data using addition operator?
The following code works fine only if there is only one combination. For example, in the array = {1,2,3,4,5}, the given value = 6; the only possibility is the sum of 2 and 4. Thus the output desired is array [1] & array[3]. Attached coding works fine for this. But for array ={1, 3, 3, 4, 2}, there is two possibilities but the code returns nothing...
#include<iostream>
using namespace std;
int main() {
int n = 5; int m = 0;
int givendata;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cin >> givendata;
if (m < n) {
for (int i = 0; i < n; i++) {
int sum = a[n - i] + a[m];
if (sum == givendata) {
cout << m << " " << n - i;
}
}
}
m = m + 1;
return 0;
}
You need to use a double loop to compare all the values:
// start at 0, the first position of the array. Loop until the 2nd to last element
for (int i=0; i<n-1;i++)
{
// start this index at one higher than i. Since a+b == b+a, there's no need to
// add the later values in the array with the previous ones, we've already
// done that
for (int j=i+1; j<n; j++)
{
int sum = a[i]+a[j];
if (sum == givendata)
{
std::cout << a[i] << " + " << a[j] << " = " << givendata << std::endl;
}
}
}
Demonstration
Also see Why is "using namespace std;" considered bad practice?
I'm trying to convert an histogram with absolute values to an histogram showing the relative frequency of letters in a string, written by the user. The letters frequency should be represented by *. So, if the letter "A" is 1% of a string, there should be two *. 1% = two *.
When trying to calculate the frequency, the output is zero. I don't really understand why.
I've tried to search the internet, but I can't really find something that helps me. I guess I'm stuck, both in my head and coding.
This is the code for my three functions:
void berakna_histogram_abs(const string inm, int arr[ANTAL_BOKSTAVER]){
int i, j = 0;
while (inm[i] != '\0'){
if (inm[i] >= 'a' && inm[i] <= 'z'){
j = inm[i] - 'a';
++arr[j];
}
if (inm[i] >= 'A' && inm[i] <= 'Z'){
j = inm[i] - 'A';
++arr[j];
}
i++;
}
}
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int (&ree)[ANTAL_BOKSTAVER]){
for(int i = 0; i < ANTAL_BOKSTAVER; i++) {
ree[i] = arr[i] / 26;
printf("%c %lf \n", i + 'a', ree[i]);
}
for (int x = 0; x < ANTAL_BOKSTAVER; x++){
}
}
void plotta_histogram_rel(int (&ree)[ANTAL_BOKSTAVER]){
cout << "Frekvensen av bokstäver i texten är: " << endl;
for (int i = 0; i < ANTAL_BOKSTAVER; i++){
cout << char(i + 'a') << " : " << ree[i] << endl;
}
}
I'm not allowed to do any calculations in the third function, that is only for writing the histogram. The whole program is pretty big, if you'd like, I'll provide all the code.
Any help forward is much appreciated.
Thanks!
So, you have some errors that need to be corrected. You do not pass the array as reference in the first function. You pass it by value. So all modifications that will be done to that arra in the first function berakna_histogram_abs will not be visible to the outside world.
You need to do the same as in you other functions -->
void berakna_histogram_abs(const std::string inm, int (&arr)[ANTAL_BOKSTAVER]) {
By the way, the string should also be passed as reference. Anyway. Not so important.
Next problem. You forgot to initialize variable i to 0 in your first function. So, it will have some random value and the program will fail, becuase you access some random index with inm[i].
In your calculation function abs_till_rel you are using the wrong formular. You need to multiply with 100 to get integer results between 0 and 100 for the percentage. And you divide by 26, which makes the result relative to the amount of the number of letters in an alphabet. My guess is that you want to have the relations to the number of letters in the string.
For that, you first need to calculate all counts of letters to get the overall count. Like for example with:
int sum = 0;
for (int i = 0; i < ANTAL_BOKSTAVER; i++) sum += arr[i];
and then divide by this sum, like so:
ree[i] = (arr[i] * 100) / sum;
And to output the histogram, you can simply build a string with stars, using the std::string constructor number 2
Your updated program would look like this:
#include <iostream>
#include <string>
#include <stdio.h>
constexpr int ANTAL_BOKSTAVER = 26;
void berakna_histogram_abs(const std::string inm, int (&arr)[ANTAL_BOKSTAVER]) {
int i = 0, j = 0;
while (inm[i] != '\0') {
if (inm[i] >= 'a' && inm[i] <= 'z') {
j = inm[i] - 'a';
++arr[j];
}
if (inm[i] >= 'A' && inm[i] <= 'Z') {
j = inm[i] - 'A';
++arr[j];
}
i++;
}
}
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int(&ree)[ANTAL_BOKSTAVER]) {
int sum = 0;
for (int i = 0; i < ANTAL_BOKSTAVER; i++) sum += arr[i];
if (sum >0) for (int i = 0; i < ANTAL_BOKSTAVER; i++) {
ree[i] = (arr[i] * 100) / sum;
std::cout << (char)(i + 'a') << '\t' << ree[i] << '\n';
}
for (int x = 0; x < ANTAL_BOKSTAVER; x++) {
}
}
void plotta_histogram_rel(int(&ree)[ANTAL_BOKSTAVER]) {
std::cout << "Frekvensen av bokstäver i texten är: " << std::endl;
for (int i = 0; i < ANTAL_BOKSTAVER; i++) {
std::cout << char(i + 'a') << " : " << std::string(ree[i]*2,'*') << std::endl;
}
}
int main() {
std::string test{"The quick brown fox jumps over the lazy dog"};
int frequencyArray[ANTAL_BOKSTAVER] = {};
int frequencyInPercent[ANTAL_BOKSTAVER] = {};
berakna_histogram_abs(test, frequencyArray);
abs_till_rel(frequencyArray, frequencyInPercent);
plotta_histogram_rel(frequencyInPercent);
}
But in C++, we would use the standard approach and write the followin:
#include <iostream>
#include <map>
#include <string>
#include <cctype>
// Our test string. This is a standard test string that contains all letters
std::string test{ "The quick brown fox jumps over the lazy dog" };
int main() {
// Count all letters
std::map<char, size_t> counter{};
for (const auto& c : test) if (std::isalpha(c)) counter[std::tolower(c)]++;
// Show histogram
for (const auto& [letter, count] : counter)
std::cout << letter << '\t' << std::string((count * 200) / test.size(), '*') << '\n';
return 0;
}
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int langd, double frekArr[ANTAL_BOKSTAVER]){
//Function to calculate the relative frequency of letters in a string.
for (int i = 0; i < ANTAL_BOKSTAVER; i++){
frekArr[i] = arr[i]; //Writes over the input from the user to a new array.
frekArr[i] = frekArr[i] * 200 / langd; //Calculates the relative frequency
//*200 since 1% should be represented by two (2) *.
}
}
void plotta_histogram_rel(double frekArr[ANTAL_BOKSTAVER], int langd){
int j = 0;
for (int i = 0; i < ANTAL_BOKSTAVER; i++){
cout << char(i + 'A') << " : ";
//Creates a histograg, horizontal, with A-Z.
if(frekArr[i] > 0){
for ( j = 0; j < frekArr[i]; j++){
cout << "*";
}
cout << endl;
}
//If the index in frekArr is NOT empty, loop through the index [i] times and
//write double the amount of *.
else {
cout << " " << endl;
//Else, leave it empty.
}
}
}
I've solved the issue. See the working code above.
I'm working through one of the classic C++ exercises of writing a program to determine which numbers are primes. The version I'm working on now requires me to be able to determine which values are prime up to a value inputted by the user called max.
The algorithm I'm attempting to construct behaves in the following fashion:
1) Enter the desired max value.
2) Take this max and then put it into a function which will calculate the sqrt(max).
3) Using sqrt(max) I will construct a vector of the primes up to the value of sqrt(max)
4) using this sqrt(max) vector I will then evaluate which values are prime up to the value max by creating a specific function to determine what values in the list up to max are prime. Then I will generate a list of all these primes.
With this being the structure here is my code for the endeavor:
#include "pch.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::string;
using std::vector;
int determine_prime(int x) {
// function made to determine if a number is prime
// used the fact that to determine if number is prime only need to check if
// prime values less than sqrt(x) divide x
vector<int> vector_of_sqrt_primes = list_of_prime_sqrt();
vp_1 = x % vp_1 = x % vector_of_sqrt_primes[i];
for (int i = 0; i < vector_of_sqrt_primes.size(); i = i + 1) {
if (vp_1 == 0 &&
x != vector_of_sqrt_primes[i]) { // verifying if value is prime
cout << x << " is not a prime number. \n";
return 0;
}
else {
cout << x << " is a prime number. \n";
return 1;
}
}
}
int list_of_prime_sqrt(int y) {
// using this vector as reference for all values less than the sqrt of max
vector<int> vector_of_primes_sqrt = {2};
int vps = 0;
for (int i = 2; i < round(sqrt(y)); i = i + 1) {
for (int j = 0; j < vector_of_primes_sqrt.size(); j = j + 1) {
vps = i % vector_of_primes_sqrt[j];
if (vps == 0 && i != vector_of_primes_sqrt[j]) {
cout << i << " is not a prime number. \n";
} else {
cout << i << " is a prime number. \n";
vector_of_primes_sqrt.push_back(i);
}
}
}
}
int main() {
int max = 0;
vector<int> primes_list = {};
cout << "Please enter the number of integers you would like to inspect "
"whether they are prime.\n";
cin >> max;
list_of_prime_sqrt(max);
for (int i = 1; i < max + 1; i = i + 1) {
int p = determine_prime(i);
if (p == 1) {
primes_list.push_back(i);
}
}
for (int j = 0; j < primes_list.size(); j = j + 1) {
cout << primes_list[j] << "\n";
}
}
So what I was hoping was that I would be able to use vector_of_sqrt_primes in the determine_prime() function and then work out which values are primes a return them to my main(). But I am hitting a wall. So all of this to askif there is a way for me to be able to do this? I haven't gotten to the point to be able to use pointers or anything advanced. I'm working through Stroustroup Programming Principles and Practices and this is Chapter 4.
Below are two different ways in solving your problem. One returns a vector and the other uses pass by reference to be able to modify the vector passed into the parameter
#include <iostream>
#include <vector>
#include <string>
bool is_prime(int number){
//exceptions
if(number == 1) return false;
if(number == 2 || number == 5) return true;
std::string str = std::to_string(number);
if(str.back() == '1' || str.back() == '3' || str.back() == '7' || str.back() == '9'){
for(int i = 3; i * i <= number; i++){
if(number % i == 0){
return false;
}
}
return true;
}
return false;
}
//adds the value to the vector passed in and the values will 'save'
void find_primes(std::vector<int>& primes, int max){
for(int i = 0; i < max; i++){
if(is_prime(i)) primes.push_back(i);
}
}
//adds the results to a vector and returns that vector
std::vector<int> return_vec_primes(int max){
std::vector<int> results;
for(int i = 0; i < max; i++){
if(is_prime(i)) results.push_back(i);
}
return results;
}
int main(){
std::vector<int> reference_vec;
//pass the vector into the function
find_primes(reference_vec, 100);
//the function will return the vector into 'returned_vec'
std::vector<int> returned_vec = return_vec_primes(100);
//same results
for(int i : reference_vec) std::cout << "prime: " << i << "\n";
for(int i : returned_vec) std::cout << "prime: " << i << "\n";
return 0;
}
I need some help, I know this question was asked before but I don't get it and I cant solve it, so I need help. I need to move the elements of my array to a position to left. So if the input will be 1,2,3,4,5 then the output will be 2,3,4,5,1. I have done the same to right but to left I cant figure it out, please also explain the logic , thanks.
#include <iostream>
using namespace std;
int a[100],n,i,tempr,templ;
int main()
{
cin>>n;
for(i=1;i<=n;i++) cin >> a[i];
for(i=1;i<=n;i++)
{
tempr = a[n];
a[n] = a[i];
a[i] = tempr;
cout<<"Right: "<<a[i]<<endl;
}
for(i=1;i<=n;i++)
{
templ = a[2];
a[2] = a[i];
a[i] = templ;
cout<<"Left: "<<a[i]<<endl;
}
return 0;
}
Please help!
First problem is bad indexing:
for(i=1;i<=n;i++) cin >> a[i]; //wrong logic, C++ indexing start from 0
Correct approach:
for(i=0;i<n;i++) //all your loops
Second problem is wrong logic for shifting elements:
Corrected version:
//input example: 1 2 3 4 5
//to the left
int temp = a[0]; //remember first element
for(i=0;i<n-1;i++)
{
a[i] = a[i+1]; //move all element to the left except first one
}
a[n-1] = temp; //assign remembered value to last element
//output: 2 3 4 5 1
cout << "To left: " << endl;
for(i=0;i<n;i++)
cout << a[i] << endl;
//to the right
temp = a[n-1]; //remember last element
for(i=n-1;i>=0;i--)
{
a[i+1] = a[i]; //move all element to the right except last one
}
a[0] = temp; //assign remembered value to first element
//output: 1 2 3 4 5 because elements are shifted back by right shift
cout << "To right: " << endl;
for(i=0;i<n;i++)
cout << a[i] << endl;
EDIT:
How to display both shifts:
#include <iostream>
using namespace std;
int to_left[5], to_right[5],n,i,tempr,templ;
int main()
{
cout << "Input array size: ";
cin >> n;
for(i=0;i<n;i++)
{
cin >> to_left[i]; //read values to first array
to_right[i]=to_left[i]; //then copy values to second one
}
//shift first array to left
int temp = to_left[0];
for(i=0;i<n-1;i++)
{
to_left[i] = to_left[i+1]; //move all element to the left except first one
}
to_left[n-1] = temp; //assign remembered value to last element
//output: 2 3 4 5 1
cout << "To left: " << endl;
for(i=0;i<n;i++)
cout << to_left[i] << endl;
//shift second array to right
temp = to_right[n-1]; //remember last element
for(i=n-1;i>=0;i--)
{
to_right[i+1] = to_right[i]; //move all element to the right except last one
}
to_right[0] = temp; //assign remembered value to first element
//output: 1 2 3 4 5 because elements are shifted back by right shift
cout << "To right: " << endl;
for(i=0;i<n;i++)
cout << to_right[i] << endl;
return 0;
}
Note that your code look very much like C code. In C++, you can declare variables in any segment of code, not just at the beginning. In C++, you can declare variable in for loop like this: for(int i=0; i<...) - no need for global variable i
For reference, this would be good C++ code example that satisfies problem you are facing:
#include <iostream>
#include <vector>
int main()
{
std::size_t n; //size_t is unsiged type used for various sizes of containers or types
std::cout << "Input array size: ";
std::cin >> n;
std::vector<int> to_left(n), to_right(n); //two dynamic arrays containing integers, takin n as their size
for(std::size_t i=0;i<to_left.size();++i) //use vector size(), instead of n, also ++i in considered better for loops that i++ (may be faster)
{
std::cin >> to_left[i];
to_right[i]=to_left[i];
}
int temp = to_left[0]; //declare temp here, not at the begining of code
for(std::size_t i=0;i<n-1;++i)
to_left[i] = to_left[i+1];
to_left[n-1] = temp;
std::cout << "To left: " << std::endl;
for(std::size_t i=0;i<n;++i)
std::cout << to_left[i] << std::endl;
temp = to_right[n-1]; //reuse temp
for(int i=to_right.size()-1;i>=0;--i) //note int, not std::size_t, because size_t is always >=0, loop would never end.
to_right[i+1] = to_right[i];
to_right[0] = temp;
std::cout << "To right: " << std::endl;
for(std::size_t i=0;i<n;i++)
std::cout << to_right[i] << std::endl;
return 0;
}
And here would be ideal C++ code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::size_t n;
std::cout << "Input array size: ";
std::cin >> n;
std::vector<int> to_left(n), to_right(n);
for(std::size_t i=0;i<to_left.size();++i)
{
std::cin >> to_left[i];
to_right[i]=to_left[i];
}
// rotate first array to the left
std::rotate(to_left.begin(), to_left.begin() + 1, to_left.end());
// rotate second array to right
std::rotate(to_right.rbegin(), to_right.rbegin() + 1, to_right.rend());
std::cout << "To left:" << std::endl;
for(auto x : to_left) //C++11 feature, x iterates through container
std::cout << x << std::endl;
std::cout << "To right:" << std::endl;
for(auto x : to_right)
std::cout << x << std::endl;
return 0;
}
Or you can use memmove(...) projected exactly for those purpose, here your sample:
#include <iostream>
#include <cstring>
using namespace std;
//rotate Left
void r_left(int *a,int n)
{
int tmp=a[0];
memmove(a,a+1,sizeof(int)*(n-1));
a[n-1]=tmp;
}
//rotate right
void r_right(int *a,int n)
{
int tmp=a[n-1];
memmove(a+1,a,sizeof(int)*(n-1));
a[0]=tmp;
}
void show(int *a,int n)
{
while(n--)
cout<<*a++<<' ';
cout<<endl;
}
int main()
{
int ar[]={1,2,3,4,5};
int n=sizeof(ar)/sizeof(ar[0]);
r_left(ar,n);
show(ar,n);
r_right(ar,n);
show(ar,n);
return 0;
}
easiest way to swap elements in C++ is to use std::iter_swap()
so for an array of 4 elements to swap elements 1 and 4 you would do the following
int a[4];
std::iter_swap(a, a+3);
note that you also need to #include <algorithm> for this to work
the basic logic of the function is that you give the location in memory of the 2 elements, so as the first element of an array is also its location in memory, you can pass a + n, when n is equal to the n-1 index number of the element you want to swap
As other already have stated it's all about indices. In a for-loop you are almost always in trouble if your stop condition is i <= size, because arrays in C++ are zero-indexed.
Where Black Moses alogrithm is far the easiest to understand (and probably the fastes), I read your code as if you try to swap the first value of the array through the array to the last position. Below I have tried to pin out this approach.
#include <stdio.h>
#include <tchar.h>
#include <iostream>
void ShiftLeft(int* pArr, size_t length)
{
for (size_t i = 1; i < length; i++)
{
int tmp = pArr[i - 1]; // Preserves the previous value
pArr[i - 1] = pArr[i]; // Overwrites the previous position with the current value
pArr[i] = tmp; // Stores the previous value in the current position
// All in all the first value is swapped down the array until it is at the length - 1 position
// and all the other values are swapped to the left.
/* For an array with 4 values the progression is as follows:
i = 0: 1 2 3 4
i = 1: 2 1 3 4
i = 2: 2 3 1 4
i = 3: 2 3 4 1
*/
}
}
void ShiftRight(int* pArr, size_t length)
{
for (size_t i = length - 1; i > 0; i--)
{
// This code does exactly the same as for ShiftLeft but the loop is running backwards
int tmp = pArr[i - 1];
pArr[i - 1] = pArr[i];
pArr[i] = tmp;
}
}
void Print(int* pArr, size_t length)
{
for (size_t i = 0; i < length; i++)
{
std::cout << pArr[i] << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
size_t length = sizeof(arr) / sizeof(arr[0]);
Print(arr, length);
ShiftLeft(arr, length);
Print(arr, length);
ShiftRight(arr, length);
Print(arr, length);
return 0;
}
#include <iostream>
using namespace std;
int a[100], outR[100], outL[100], n, i;
int main() {
cin >> n;
for (i = 0; i < n; i++) cin >> a[i];
// Right
for (i = 0; i < n; i++) {
outR[i+1]= a[i];
}
outR[0] = a[n-1]; // add first number
// Left
for (i = 1; i < n; i++) {
outL[i-1]= a[i];
}
outL[n-1] = a[0]; // add last number
// Answer
cout << "Right:\n";
for(i=0; i<n; i++) {
cout << outR[i] << endl;
}
cout << "Left:\n";
for(i = 0; i < n; i++) {
cout << outL[i] << endl;
}
return 0;
}
Simple answer where you can easily see everything, good luck.
You may be interested in ,,vector coding", it seems be easier if you spend some time on this:
#include <iostream>
#include <vector>
using namespace std;
vector <int> a, outR, outL;
size_t i;
int main () {
int n, temp_int;
cin >> n;
while (n--) {
cin >> temp_int; // here you read number to your vector
a.push_back(temp_int); // here you add this to vector
// remember that vector start from element 0 as like arrays
}
// Left
// remember that last element will be first
// you may have acces to size of your vector easily
for (i = 0; i < (a.size()-1); i++) {
outL.push_back(a.at(i+1)); // here you create new vector
}
outL.push_back(a.at(0)); // add last elemet which rotated
// Right
// to rotate left first you have push last element so
outR.push_back(a.at(a.size()-1)); // add first elemet which rotated
for (i = 1; i < a.size(); i++) {
outR.push_back(a.at(i-1)); // here you push rest
}
cout << "Left" << "\n";
for (i = 0; i < a.size(); i++) {
cout << outL.at(i) << endl; // here you print value
}
cout << "Right" << "\n";
for (i = 0; i < a.size(); i++) {
cout << outR.at(i) << endl; // here you print value
}
return 0;
}
int* leftShiftOneByOneWIthoutTemp(int arr[], int sz)
{
for (int i=0 ;i < sz-1; i++)
{
arr[i] = arr[sz-1] + arr[i];
arr[sz-1] = arr[i] - arr[sz-1] ;
arr[i] = arr[i] - arr[sz-1] ;
std::cout << "iter "<< i << std::endl;
printArray(arr,5);
}
std::cout << "final "<< std::endl;
printArray(arr,5);
return arr;
}
Replace your code (to shift array left) with below code.
templ = a[0];
for(i=0;i<n-1;i++)
{
a[i] = a[i+1];
cout<<"Left: "<<a[i]<<endl;
}
a[n-1] = templ;
cout<<"Left: "<<a[n-1]<<endl;
I was making an app that calculates the mean, median, and range of any integers, but I ran into the issue: Vector subscript out of range. I've looked at some other posts about this, and still haven't been able to fix it.
Here's my code:
#include <iostream>
#include <Algorithm>
#include <Windows.h>
#include <vector>
using namespace std;
int main() {
//Variables
int sze;
int mraw = 0;
double mean;
double median;
double range;
int fullnum = 0;
int lastnum = 1;
vector<int> med;
cout << "How many numbers do you have? ";
cin >> sze;
int *arr = new int[sze];
for (int i = 0; i < sze; i++) {
med.push_back(arr[i]);
}
//Getting numbers
for (int i = 0; i < sze, i++;) {
system("cls");
cout << "Enter number #" << i + 1 << ": ";
cin >> arr[i];
}
//Mean
for (int i = 0; i < sze; i++){
fullnum += arr[i];
}
mean = fullnum / sze;
//Median
sort(med.begin(), med.end());
int mvs = sze;
while (med.size() >= 2) {
med.erase(med.begin());
med.erase(med.begin() + med.size() - 1);
mvs--;
}
if (mvs == 2) {
mraw = med[1] + med[2];
median = mraw / 2;
}
else {
median = mvs;
}
//Range
vector<int> rnge;
for (int i = 0; i < sze; i++) {
rnge.push_back(arr[i]);
lastnum++;
}
sort(rnge.begin(), rnge.end());
int bigsmall[2];
bigsmall[1] = rnge[1];
bigsmall[2] = rnge[lastnum];
range = bigsmall[2] - bigsmall[1];
//Outputs
cout << "Mean: " << mean << "\nMedian: " << median << "\nRange: " << range;
system("cls");
return 0;
}
You have what would be an off-by-one error if lastnum was initialized to 0.
When rnge is empty, presumably lastnum is 0. This means access rnge[lastnum] is in error, as rnge is empty.
Applying an inductive argument shows that lastnum is the count of number of elements, and not the index of the last element. Thus, rnge[lastnum] is always out of range.
In actuality, you have initialized lastnum to 1, so your bug is actually off-by-two.