Getting maximum value from array in C++ using pointer - c++

I am gonna want maximum value from the array using a pointer. But I am not getting the accurate value. Please, help.
#include <iostream>
using namespace std;
int main()
{
int* largest;
int a[5]={4,5,666,7,8};
largest=a;
for(int i=1; i<5; i++)
{
if(*largest<*(largest+i))
{
*largest=*(largest+i);
largest=largest+i;
}
}
cout<<*largest;
}
I am getting 7339544 as an output rather than 666. I don't know what I am doing wrong.

You're indexing outside the array, causing undefined behaviour.
You're doing this
largest
|
v
| 4 | 5 | 666 | 7 | 8 |
^
|
largest + 1
then
largest
|
v
| 5 | 5 | 666 | 7 | 8 |
^
|
largest + 2
then
largest
|
v
| 5 | 7 | 666 | 7 | 8 | outside
^
|
largest + 3
(Note that you're also modifying the array, which you shouldn't.)
The main problem is that you're trying to use largest for three purposes simultaneously:
iterating,
storing the largest value,
storing the position of the largest value.
It should only point to the largest array element; you should only change its value, not the value of the element it points to.
int main()
{
const int a[5] = {4, 5, 666, 7, 8};
const int* largest = a;
for (int i = 1; i < 5; i++)
{
if (*largest < a[i])
{
largest = &a[i];
}
}
cout << *largest;
}

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generateNumber(int lower_limit, int upper_limit);
void fillArr(int *arr, unsigned int arrSize, int lower_limit, int upper_limit);
void printElementsArr(int *arr, unsigned int arrSize);
int maxElementArr(int *arr, unsigned int arrSize);
int main()
{
char expression;
int l_l, u_l;
int arrSize;
do{
srand(time(0));
printf("Insert array size:\n");
scanf("%d", &arrSize);
if(arrSize < 0){
while (arrSize<0){
printf("Insert positive array size:\n");
scanf("%d", &arrSize);
}
}
int array[arrSize];
printf("Insert lower limit of an array:\n");
scanf("%d", &l_l);
printf("Insert upper limit of an array:\n");
scanf("%d", &u_l);
while(u_l<l_l){
printf("the upper limit (%d) is smaller then the lower limit (%d), set a new upper limit of an array: ",u_l,l_l);
scanf("%d",&u_l);
}
fillArr(array, arrSize, l_l, u_l);
printElementsArr(array, arrSize);
maxElementArr(array, arrSize);
getchar();
printf("If you want to end the program insert 'n' else insert any key: ");
scanf("%c",&expression);
}while(expression != 'n');
}
//---------------------------------------------------------------------------------------------------------
int generateNumber(int lower_limit, int upper_limit){
return rand() % (upper_limit-lower_limit)+lower_limit;
}
void fillArr(int *arr, unsigned int arrSize, int lower_limit, int upper_limit){
int i = 0;
for (i; i < arrSize; i++){
*(arr+i)= generateNumber(lower_limit, upper_limit);
}
}
void printElementsArr(int *arr, unsigned int arrSize){
int i = 0;
printf("\n");
for (i; i < arrSize; i++){
printf("%d.element of an array: %d\n" ,i+1, *(arr+i));
}
}
int maxElementArr(int *arr, unsigned int arrSize){
int i = 1, max= *arr;
for(i; i<arrSize; i++){
if(max < *(arr+i)){
max = *(arr+i);
}
}
printf("\nThe max element of an array is: %d\n",max);
}
Because this code consists of multiple parts I created each independent functions for each problem a then I initially called them in my main function except the one that generates numbers. I used that one in the function where it fills the array with the numbers.
I created the function for generating a random numbers, filling an array with the numbers and printing every each element(number) of an array.
The reason I created the random number generator is because it is more dynamic than static array with pre-defined numbers and size of an array.
Also before the fill and print functions are called, first I ask the user for an array size and if the array size is lower than 0 therefore it will ask the user to insert a positive number and a I also ask user for a lower and an upper limit of an array and if the upper limit is lower than the lower limit a question with the information that the upper limit is lower than the upper one will pop-up over and over again with the option to insert a new upper limit unless the user inserts a number that is higher than the lower limit.
Also, the whole program is in loop with the question in the end if they want to end the program.

#include <iostream>
using namespace std;
int main()
{
int* largest;
int a[5]={4,5,666,7,8};
largest=a;
for(int i=1; i<5; i++)
{
if(*largest < a[i])
{
largest = &a[i];// This works perfectly
//largest = largest+i; There is no meaning of this line
}
}
cout<<*largest;
}

Related

check if the array can be split to subarrays which are equal in sum

my problem i face is i cant run my code when i use cin>>arr
can i make it work with this code
#include <bits/stdc++.h>
using namespace std;
int checkEqualSumUtil(int arr[1000], int N,
int sm1, int sm2,
int sm3, int j)
{
if (j == N)
{
if (sm1 == sm2 && sm2 == sm3)
return 1;
else
return 0;
}
else
{
int l = checkEqualSumUtil(arr, N,
sm1 + arr[j],
sm2, sm3, j + 1);
int m = checkEqualSumUtil(arr, N, sm1,
sm2 + arr[j],
sm3, j + 1);
int r = checkEqualSumUtil(arr, N, sm1, sm2,
sm3 + arr[j], j + 1);
return max(max(l, m), r);
}
}
void checkEqualSum(int arr[], int N)
{
int sum1, sum2, sum3;
sum1 = sum2 = sum3 = 0;
if (checkEqualSumUtil(arr, N, sum1,
sum2, sum3, 0)== 1)
{
cout << "YES";
}
else
{
cout << "NO";
}
}
int main()
{
int n;
cin>>n;
int arr[n/2];
for(int i=0;i<n;i++){
cin>>arr[i];
int N = sizeof(arr) / sizeof(arr[0]);
checkEqualSum(arr, N);
return 0;
}}
my code
i have edited my code the input is typed correctly
but it always outputs no
i dont know why any ideas??
also thank you for helping me all
i tried the input
3
1 1 1
it should print yes
put the output is no?
Let's analyze your code in main:
int main()
{
int arr[1000],n;
You have allocated an array, arr, that has a capacity of 1000 integers.
The array is not initialized.
An alternative declaration:
const unsigned int N = 1000;
int array[N];
The statement below reads the quantity of numbers to read into the array.
cin>>n;
If the User or Operator enters a value larger than 1000, you will have undefined behavior. Quantities less than 1000 are a waste of space. Use std::vector<int> to contain elements when the capacity is not known during runtime.
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
Here you are calculating the capacity of the array. The capacity was already declared as 1000. See my suggestion about using N as the capacity.
int N = sizeof(arr) / sizeof(arr[0]);
The above line is not necessary. Another option is to use a macro:
#define MAXIMUM_NUMBERS (1000)
The present form of the statement below, tells the function to use 1000 values, regardless of the quantity of numbers entered by the User.
checkEqualSum(arr, N);
For example, if I enter 5 numbers, the function call will translate to:
checkEqualSum(arr, 1000);
This because you initialized N to the capacity of the array.
Maybe you want to pass the quantity of numbers read into the array:
checkEqualSum(arr, n);
This is why variable names should differ in more than case.
This code is fine, telling the Operating System that your code run with no errors.
return 0;
}

getting array index from a function

i've been assigned to write a program in C++ that, given an array of integers, finds the smallest (including its index) and largest number, and their subtraction. To do this, i decided to write three functions for each operation and it works perfectly. The problem is i don't know how to get the index of the smallest number.
I tried solving the problem by creating a variable and putting in inside a for loop and then print it. However, the program always says the index is 0.
Here you can see an example of how the output should be:
int myvector[200] = {40, 250, 9, 50} // Array containing 4 numbers
It should output:
The smallest number is: 9 at index 2
The largest number is: 250
Their subtraction is: 241
Here you can see my code:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int find_smallest (int myvector[], int smallest, int index){
smallest = myvector[0];
index = myvector[0];
for(int i=0; i<4; i++) {
if(myvector[i] < smallest) {
smallest = myvector[i];
index = i;
}
}
return smallest;
}
int find_largest (int myvector[], int largest) {
largest = myvector[0];
for(int i=0; i<4; i++) {
if(myvector[i] > largest) {
largest = myvector[i];
}
}
return largest;
}
int sub_minmax (int myvector[], int subtraction, int smallest, int largest){
subtraction = largest - smallest;
return subtraction;
}
int main()
{
int myvector[200], smallest, largest, subtraction, index;
for(int i=0;i<4; i++) {
cout<<"Enter the number " <<i+1<<endl;
cin>>myvector[i];
}
smallest = find_smallest(myvector, smallest, index);
largest = find_largest(myvector, largest);
subtraction = sub_minmax(myvector, subtraction, smallest, largest);
cout<<endl;
cout<<"the smallest number is: "<<smallest<<" at index "<<index<<endl;
cout<<"the largest number is: "<<largest<<endl;
cout<<"the substraction is: "<<subtraction<<endl;
return 0;
}
Any help will be appreciated, thanks
Pass index by reference.
int find_smallest (int myvector[], int smallest, int &index)
change this
int find_smallest (int myvector[], int smallest, int index)
to
int find_smallest (int myvector[], int smallest, int &index)
here index is not local variable it reference to value passed, so any changes in index in function reflect is original value.
if you want to return both you can use struct or class.

Finding the sum of n big numbers

Question: Given a number k, find the sum of k positive big integers.
This is my code,it works, but our Online Judge is rejecting it, says segfault. Why does it show segfault? I could do it with two strings but why isn't this working?
#include <iostream>
#include <string.h>
using namespace std;
void add(int l,int k);
void append(char a[], int temp);
int o;
int tf=0;
int carry=0;
char b[1000000];
char a[10000][10000];
char c[1000000];
int main()
{
int k,x=0,l=0,m=0;
cin>>k;
while(x<k)
{
cin>>a[x];
if(strlen(a[x])>l)
{
l=strlen(a[x]);
}
x++;
}
x=0;
while(x<k)
{
if(strlen(a[x])<l)
{
int temp=0;
append(a[x],l-strlen(a[x]));
}
x++;
}
add(l,k);
if(carry!=0)
{
cout<<carry;
}
while(o>=0)
{
cout<<(int)b[o];
o--;
}
}
void add(int l,int k)
{
int lb=l-1;
int r=k-1;
int sum=0;
int x=0;
int neg=0;
while(lb>=0)
{
r=k-1;
sum=0;
while(r>=0)
{
sum=sum+a[r][lb]-48;
r--;
}
sum=sum+carry;
lb--;
if(sum>=10)
{
b[x]=sum%10;
carry=sum/10;
}
else
{
b[x]=sum;
carry=0;
}
sum=0;
o=x;
x++;
}
}
void append(char a[], int temp)
{
int l=0,m;
int tempb=temp;
m=strlen(a)-1;
while(temp>0)
{
c[l]='0';
l++;
temp--;
}
int z=0;
while(z<=m)
{
c[l]=a[z];
z++;
l++;
}
z=0;
while(z<=m+tempb)
{
a[z]=c[z];
z++;
}
}
Input Format:
First line contains k , which specifies the number of big numbers. Each of the next k lines contains a
big positive integer.
Output Format:
For each test case print the new big integer in a new line
Sample Input:
3
1331331
1313
453535322
Sample Output:
454867966
Constraints:
1<=k<=10
1<=number of digits in big numbers<=10000
Based on the problem statement:
Each input entry my have at most nmax = 10000 digits
Since each entry is stored as a C-style, zero-terminated string, each character array must have a length of (nmax + 1) = 10001 characters, to accomodate for the C-string terminator '\0'.
As you stored the entries into character arrays without leaving room for the zero terminator, assuming each entry was 10000-characters long:
Each entry with k>=1 overwrote the terminator or entry k-1, thus coalescing the entries together;
You thus ended with one giant string, with l = strlen(a[0]) = 100000;
From then on, all further processings were performed with these incorrect (coalesced) inputs and length, leading to buffer overrun at some point later in the execution.

Linear search algorithm

The goal of my program is to find the number entered by user in an array of integers (array was created automatically), and to show the index of this number (or numbers, if they occurs several times). It works correctly when the desired number occurs only once in array. For example, if there is an array
7 8 0 4 2 7 2
and user entered "8", the output of program will be
Index of the number you entered is: 2
But when we have array:
0 5 3 9 3 7 2
And the user entered "3", the output will be
Index of the number you entered is: 3
And I wonder how to make the program include second "3" number which has index 5. The code of program:
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int i, N;
int LinearSearch(int Array[], int searchValue)
{
for (i=0; i<N; i++)
{
if (Array[i]==searchValue)
return i;
}
return -1;
}
int main()
{
int searchValue, Array[1000];
cout<<"Size of array: ";
cin>>N;
cout<<"Array: ";
for (i=0; i<N; i++)
{
Array[i]=rand()%10;
cout<<Array[i]<<" ";
}
cout<<"Search value: ";
cin>>searchValue;
if (LinearSearch(Array, searchValue)==1)
cout<<"\nIndex of the number you entered is: "<<LinearSearch(Array, searchValue)+1;
else
cout<<"\nNothing found";
}
You can do it in two ways:
1. Change the LinearSearch's return value to vector, write it like this:
vector<int> LinearSearch(int Array[], int searchValue)
2.Add a vector reference variable in the parameters, it should like this:
int LinearSearch(int Array[], int searchValue, vector<int> &results)
And the the method body in LinearSearch should have little change accordingly.
Because you return from the search function as soon as the value is located:
for (i=0; i<N; i++)
{
if (Array[i]==searchValue)
return i; // <-- as soon as we get here, we break the loop
}
therefore, you will get the first position in which searchValue is located, which is 2 (0-based). Thus, you get 2+1 = 3. To get the last one, you will have to remove the early exit, and keep the current index in a variable, like this:
int LinearSearch(int Array[], int searchValue) {
int index = -1;
for (i = 0; i < N; i++) {
if (Array[i]==searchValue) {
index = i;
}
}
return index;
}

Floating point exception

#include <cstdio>
#include <ctime>
int populate_primes(int array[])
{
const int max = 1000000;
char numbers[max+1];
int count=1;
array[0]=2;
for(int i=max;i>0;i-=2)numbers[i]=0;
for(int i=max-1;i>0;i-=2)numbers[i]=1;
int i;
for(i=3;i*i<=max;i+=2){
if(numbers[i]){
for(int j=i*i;j<max+1;j+=i)numbers[j]=0; array[count++]=i;
}
}
int limit = max/2;
for(;i<limit;i++) if(numbers[i])array[count++]=i;
return count;
}
int factorize(int number,int array[])
{
int i=0,factor=1;
while(number>0){
if(number%array[i]==0){
factor++;
while(number%array[i]==0)number/=array[i];
}
i++;
}
printf("%d\n",factor);
return factor;
}
int main()
{
int primes[42000];
const int max = 1000000;
int factors[max+1];
clock_t start = clock();
int size = populate_primes(primes);
factorize(1000,primes);
printf("Execution time:\t%lf\n",(double)(clock()-start)/CLOCKS_PER_SEC);
return 0;
}
I am trying to find the no. of factors using simple algo. The populate primes part is running okay , but the factorize part does not execute and gives the floating point exception error.
Please see the code and tell my mistake.
In your factorize method you access array[0], because the initial value of i is 0.
This array is the primes array which is populated by populate_primes. But populates prime doesn't write to primes[0], since the initial value of count is 1.
Thus the first element is not initialized and you probably get a div by 0 error.
You need to pass the size which you got from populate to factorize.
factorize(int number, int array[], int size);
problem is your array[] is not fully loaded, it is loaded only till size variable. So you may want to check for that.
Also the logic inside factorize is wrong. You need to check (number > 1) rather than (number >0).
Try with the function below to see some problems:
#define MAX_PRIMES 42000
int factorize(int number,int array[])
{
int i=0,factor=1;
for (i=0; number>0 && i< MAX_PRIMES; i++){
if (array[i] == 0 || array[i] == 1) {
printf("Error: array[%d] = %d\n", i, array[i]);
} else {
if(number%array[i]==0){
factor++;
while(number%array[i]==0 && number>0) {
printf("%d %d\n", number, array[i]);
number/=array[i];
}
}
}
}
printf("%d\n",factor);
return factor;
}