Function call [table] not working - c++

I have big problem.
The task is:
Write a function in C ++ that takes a array of ints tab, array size n, and the number k. The function returns returns true if each of the numbers in the table tab, at least k digits long, and false otherwise. Checking how many digits has the number should be included in the additional auxiliary functions that call from inside a basic function. You should also write the main function that reads the data, calls the base and outputs its result.
For calls (record [] is an array):
f ([123,4425,2224,222,55553], 5, 3)
The function should return true. Since each of the numbers 123,4425,2224,222,55553 at least three digital
Calls for:
f ([123,4425,2,222,5], 5, 2)
The function should return false
Because there are a number, for example 2 which is a digital one and is less than 1 k = 2
My code :
#include <iostream>
int ile_cyfr(int a)
{
int temp=0;
do
{
a = a/10;
temp++;
} while(a>0);
return temp;
}
bool funkcja(int *tab, int n, int k)
{
bool stan = false;
for (int i=0; i<n; i++)
{
if (ile_cyfr(tab[i])<k)
{
stan = false;
if (stan == false)
{
return stan;
return 0;
}
}
else
{
stan = true;
return stan;
}
}
}
int main() {
using namespace std;
int n=0, k=0;
int *tab = new int[n];
cout << "Podaj ilosc liczb: " << endl;
cin >> n;
cout << "\nPodaj liczby: " << endl;
for (int i=0; i<n; i++) {
cin >> tab[i];
}
cout << "\nPodaj minimalna ilosc liczb: " << endl;
cin >> k;
cout << funkcja([444,856,671,321], n, k);
return 0;
}
The problem is that the line:
cout << funkcja([444,856,671,321], n, k);

For starters the function funkcja is invalid. It returns true in case when the first element of the array has the number of digits greater than or equal to k. As I have understood you have to check that all elements of the array satisfy the condition.
The function can be written the following way
bool funkcja( const int *tab, int n, int k )
{
int i = 0;
while ( i < n && !( ile_cyfr( tab[i] ) < k ) ) i++;
return n != 0 && i = n;
}
As for this statement
cout << funkcja([444,856,671,321], n, k);
then it has an incorrect syntax.
You have to pass the variable tab as the first argument of the function call. These values 444,856,671,321 should be assigned to elements of the array pointed to by the pointer tab.
Thus write
cout << funkcja( tab, n, k );

Related

I want to sum all my vector indexes with a recursive function but starting backwards

I am stuck with this program so far, and I don't know what else to do.
I just need help with the recursive function so I can do the other modes too, which are multiplication and subtraction.
#include "std_lib_facilities.h"
//this contains all the libraries my university offers.
int sum(vector <int> test, int i){
if (i < 0){
return 0;
}
else {
return test[i] + sum(test, i - 1);
}
}
int main(){
int n;
int x;
int mode;
int result = 0;
cout << "give the size of the vector:\n";
cin >> n;
while (n < 0){
cout << "you can't give negative number!give again:\n";
cin >> n;
}
vector <int> myvector;
for (int i = 0; i <= n-1; i++){
cout << "give numbers to fill the vector:\n";
cin >> x;
myvector.push_back(x);
}
cout << "give 1 for sum 2 for multiplication 3 for substraction\n";
cin >> mode;
while (mode < 1 && mode > 3){
cout << "this mode doesn't exist.give again:\n";
cin >> mode;
}
if (mode == 1){
result = sum(myvector, n);
cout << "result is:" << result;
}
}
I want to get all the indexes starting from backwards to sum them all.
You are accessing outside the bounds of your array.
The simple fix to your issue is to pass n-1 to your sum function.
result=sum(myvector,n - 1);
However, there is no need for you to pass n at all, rather i would suggest you add a function that starts the recursion like this. (this is a rather common pattern for recursion)
int sum(const vector<int>& test, int i);
int sum(const vector<int>& test)
{
if(test.empty())
{
return 0;
}
if(test.size() == 1)
{
return test[0];
}
return sum(test, test.size() - 1);
};
int sum(const vector<int>& test, int i)
{
if(i < 0)
{
return 0;
}
return test[i] + sum(test, i - 1);
};
then call it like sum(myvector);

Displaying prime numbers less than or equal to input in c++ using two functions

I need to create a c++ program which displays all the prime numbers less than or equal to an inputted value. The catch is (and the part I can't seem to do) is that I have to use two functions to do so, and I cannot output the values within the same function that determines if they are prime or not. Below are two programs, the first is a program which does not work, this is as far as I got through trial and error after realizing that the second program does not meet the requirements. The second program works, but does not fulfill the requirements stated above. Thank you in advance, this has been driving me bonkers.
First:
bool is_Prime(int);
#include <iostream>
using namespace std;
int main() {
int m, n;
n = 2;
cout << "Your input: ";
cin >> m;
cout << "The prime numbers less than or equal to " << m << " are:" << endl;
while ( n <= m)
{
is_Prime(m);
if (true) {
cout << n << endl;
}
n++;
}
return 0;
}
bool is_Prime(int m) {
for (int n = 1; n < m; n++) {
bool prime = true;
for (int x = 2; x*x <= m; x++) {
if (m % x == 0) {
prime = false;
}
}
if (prime = true)
{
return true;
}
}
}
Second:
bool is_Prime(int m);
#include <iostream>
using namespace std;
int main() {
int m;
cout << "Your input: ";
cin >> m;
cout << "The prime numbers less than or equal to " << m << " are:" << endl;
is_Prime(m);
return 0;
}
bool is_Prime(int m) {
for (int n = 1; n < m; n++) {
bool prime = true;
for (int x = 2; x*x <= n; x++) {
if (n % x == 0) {
prime = false;
}
}
if (prime)
cout << n << " " << endl;
}
return 0;
}
So, the problem is that following function prints the numbers itself.
bool is_Prime(int m) {
for (int n = 1; n < m; n++) {
bool prime = true;
for (int x = 2; x*x <= n; x++) {
if (n % x == 0) {
prime = false;
}
}
if (prime)
cout << n << " " << endl;
}
return 0;
}
Solution one:
Modify the function so that it only checks one given number if it is a prime, and in main, make a loop from 1 up to the max number, call is_prime for each numer, and print the number if the function returns true.
bool is_Prime(int p) {
for (int x = 2; x*x <= p; x++) {
if (p % x == 0) {
return false;
}
}
return true;
}
...
//in main:
for(int p = 1; p < m; p++)
{
if(is_prime(p))
cout << p << endl;
}
Solution two (better):
Make another variable in the function, eg. a std::vector<int> v;, and instead of printing found primes, add them to the vector with v.push_back(n);. The return the whole vector (after all numbers are checked). In main, just print every number contained in the vector. This enables you to use better algorithms in the function (because one call checks all numbers), like sieve approaches, to make everything faster.
There are quite a few errors in your second attempt (labeled as first).
is_Prime(m);
This is constantly checking the one number, not all of the numbers less than m, replace m with n.
if (true) {
This will always be executed. Either store the return value of is_Prime, or call it directly in the if statement.
if (prime = true)
This will set prime to true and then test prime. You want ==.
You don't return false at the end of is_Prime
for (int n = 1; n < m; n++) {
This isn't necessary in the is_Prime function as you have the while loop in the outside function.

Unordered Array Linear Search c++

My assignment is to : Create a method to search an un-ordered array of integers for a value,
if the value is found return the index of its position in the array, if not found, return -1.
It is only finding the number I enter if it is in Index 0, otherwise it is saying it is not found. I am not sure what went wrong, it was working when I had initialized my own array, but now it won't since I have the user create their own array.
Any help would be great! thanks!
So far my code is:
#include <iostream>
using namespace std;
//SearchArray prototype
int SearchArray( int arInt[], int elementAmount, int intSearched);
int main()
{
int arInt[50];
int elementAmount;
int intSearched = 0;
int i;
cout << "How many elements would you like to add to your array?\n";
cin >> elementAmount;
for( i = 0; i < elementAmount; i++)
{
cout << "Enter Number: ";
cin >> arInt[i];
}
cout << "Search array for integer:\n";
cin >> intSearched;
//Call search array method
SearchArray(arInt, elementAmount, intSearched);
system("pause");
return 0;
}
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
int i;
bool foundInt = false;
for (i=0; i < elementAmount; i++)
{
if( arInt[i] == intSearched)
{
foundInt = true;
cout << "Integer was found in array at index " << i << endl;
}
else if (!foundInt)
{
cout << "Integer was not found in array\n";
system("pause");
return -1;
}
}
}
Added the following code to the SearchArray method in your code, and it works fine
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
for(int i=0; i< elementAmount; i++)
{
if (arInt[i] == intSearched)
return i;
}
// element not found!
return -1;
}
And add the following at the end of your main to retrieve the ans
int ans = SearchArray(arInt, elementAmount, intSearched);
cout<<"Indexed of the element"<<ans<<endl;
That's because you always end your search on first element. Suppose array is
arr=[3,5,7] and intSearched is 5.
Now in your SearchArray() function foundInt is initially set to false. So when i = 0 and arInt[i] == intSearched condition is not true, it goes to else statement since foundInt is false. And from there you return -1. Something like below would be simpler and do the job:
int SearchArray(int *arInt, int elementAmount, int intSearched)
{
int i;
for(i=0; i < elementAmount; i++)
{
if(arInt[i] == intSearched)
{
cout << "Integer was found in array at index " << i << endl;
return 1;
}
}
cout << "Integer was not found in array\n";
system("pause");
return 0;
}

C++ insertion sort

I have this function called WordSort(worddata W [], int count) that is fed two variables
1 - worddata is the array holding information on a given word in a file. count is just the counter variable to see which word in the array we are looking at.
the words.txt file that is read into this program would just be a string of words.
this is a list of words
there are letters and numbers
23 people recommend this program.
Heres the function:
void WordSort (worddata W [], int count)
{
for (int i=1; i < count; i++)
{
for (int j=i; j > 0 && W[j-1].word > W[j].word; j--)
{
Swap(W[j], W[j-1]);
}
}
}
The swap function is suppose to swap every element with the one before it as long as j > 0 or the list is over. Im confused on how to complete the swap function, here's the example i was given.
void Swap (worddata & a, worddata & b)
{
int += a;
a = b;
b =+;
}
Swap is suppose to swap every element with the one before it
I think the WordSort function works fine, the only thing missing is the Swap function. Could anyone point me in the right direction or explain insertion sorting better to me?
void insertion_sort()
{
/* Algorithm : Insertion Sort
* Coded by .
*/
int num;
/*
* Asking the User no of Integers he/she wants to enter
*/
cout << "Enter no of integers u want to enter: ";
cin >> num;
/* Creating an Array to store the integers*/
int s[num];
/*Taking Integers from the User */
for(int i = 0 ; i < num ; i++)
{
cout << "Integer " << i+1 << " is : ";
int x;
cin >> x;
s[i] = x;
}
/* The Magic of INSERTION SORT */
for(int j = 1 ; j <= (num-1) ; j++)
{
int key = s[j];
int k = j-1;
while(k >=0 && key <= s[k])
{
s[k+1] = s[k];
k = k - 1;
}
s[k+1]=key;
}
/*Printing Out the Sorted List */
cout << "The Sorted List is \n\n";
for(int i = 0 ; i < num ; i++)
{
cout << s[i] << " ";
}
}
Use standard library std::swap instead. In your loop:
for (...)
{
std:swap(W[j], W[j-1]);
}
std::swap requires worddata class to have a copy constructor and an assignment operator defined explicitly or implicitly.
Swap should look like this -- I have no idea how your example is even close.
void Swap (worddata & a, worddata & b)
{
worddata temp = a;
a = b;
b = temp;
}
Insertion sort using "for loop" (2 iterations)
#include<iostream>
using namespace std;
int insertion(int arr[], int size_arr)
{
int i,j,n, temp;
for(i=1;i<size_arr; i++){
j=i-1;
temp = arr[i];
for (j; j >= 0; j--)
{
if(arr[j] > temp){
arr[j+1] = arr[j];
arr[j] = temp;
}
}
arr[j] = temp;
}
for(i=0;i<size_arr;i++){
cout<<arr[i]<<endl;
}
return 0;
}
int main(){
int arr[] = {3,38,1,44,66,23,105,90,4,6};
int size_arr = sizeof(arr) / sizeof(arr[0]);
insertion(arr,size_arr);
return 0;
}

algorithm moves the array elements

I can not figure out an algorithm for this task, maybe you have an idea?
Task: Move the array to the array in the first half would be all the elements of the odd lines and the second all elements of the pair of lines.
The simplest option would be to move elements to another array, as it could make one using temp variable?
Input data array = {1,2,3,4,5,6,7,8}
output data array = {2,4,6,8,1,3,5,7}
Is this homework? If not, use std::stable_partition():
struct IsEven {
template<class T>
bool operator()(const T& v) const { return v % 2 == 0; }
};
int* arr = {1,2,3,4,5,6,7,8};
int* mid = std::stable_partition(arr, arr+8, IsEven());
If it is a homework, then your instructor probably expects you to write the algorithm. If you don't have to maintain the ordering as in the input sequence then you can do it rather efficiently:
Find the first element that doesn't satisfy the predicate (i.e., is odd).
Find that last element that does satisfy the predicate (i.e., is even)
swap the two elements.
Repeat, starting from the positions you just found, until the two positions meet.
The point where the two positions meet is the middle of the partition, where even numbers stop and odd numbers begin.
This is roughly how std::partition() works. If you do have to maintain the relative ordering in the input array then you can still do it in-place, but it will be faster if you use a temporary buffer. Copy the elements that don't match the predicate into that buffer, and squeeze in place those that do. Finally bring back in the elements that don't match, at the end of the array, in order.
I'm reading this question such that the output array should have the elements at even indices followed by those at odd indices, though I may be incorrect.
If not, then this is how I would do it.
template<typename T>
void moveValues(const T[] input, T[] output, std::size_t length)
{
int current outputIndex = 0;
if (length > 1) // in case we have a single element array.
{
for (int i = 1; i < length; i+=2)
{
output[++outputIndex] = input[i];
}
}
for (int j = 0; j < length; j+=2)
{
output[++outputIndex] = input[j];
}
assert(outputIndex == length); // should have filled up array
}
/* *********************************************************************** */
/* Author: Bigyan Shrestha */
/* Description: C++ source code for arranging even numbers */
/* numbers of an array to one half and odd */
/* numbers to the other half. */
/* *********************************************************************** */
#include <iostream>
using namespace std;
inline bool isEven( int value ){
if( value % 2 == 0 ) {
return true;
}
else {
return false;
}
}
inline void swap( int sourceIndex, int destIndex, int **sourceArray ) {
int temp;
temp = (*sourceArray)[sourceIndex];
(*sourceArray)[sourceIndex] = (*sourceArray)[destIndex];
(*sourceArray)[destIndex] = temp;
}
void displayArray( int *sourceArray, int size ){
for( int i = 0; i < size ; i++ ) {
cout << sourceArray[i] << " " ;
}
cout << endl;
}
int main( void ){
int size;
int *input;
int evenIndex = 0; // for keeping track of even numbers
cout << "Enter the size of input array" << endl ;
cin >> size;
input = new int[size];
for( int i = 0; i < size ; i++ ) {
cout << "Please enter the input value ( " << size-i << " remaining )" << endl;
cin >> input[i] ;
}
cout << endl;
cout << "Original Input Array " << endl;
displayArray( input,size );
cout << endl;
for( int i = 0; i <size ; i++ ) {
if( isEven(input[i]) && i > evenIndex ) {
for( int j = i ; j > evenIndex; j-- ){
swap( j, j-1, &input);
}
++evenIndex;
}
}
cout << "Modified Array " << endl;
displayArray( input,size );
cout << endl;
return 0;
}