This is the problem I'm trying to solve.
This is my attempt:
#include <iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
long long int a[n],b[n],i,max1=0,max2=0;
a[0]=0;
for(i=1;i<n+1;i++){
cin>>a[i];
if(abs(a[i]-a[i-1])>max1)
max1=abs(a[i]-a[i-1]);
}
b[0]=0;
for(i=1;i<n+1;i++){
cin>>b[i];
if(abs(b[i]-b[i-1])>max2)
max2=abs(b[i]-b[i-1]);
}
if(max1>max2)
{ cout<<"Dom"<<endl;
cout<<max1;}
else if(max1<max2)
{ cout<<"Brian"<<endl;
cout<<max2; }
else
{
cout<<"Tie"<<endl;
cout<<max1;
}
//cout << "Hello World!" << endl;
return 0;
}
On execution, it segfaults, though.
Can anybody help me resolve the problem?
The loop will always write one element beyond the array boundaries, since the maximum value of i is n in the loop. Either allocate n + 1 memory for the arrays each or set the looping condition to i < n.
Related
I am currently writing a script about finding the nearest duplicate from a user entered size array.
The array must be between 1 and 10^5 and its value has to be between 1 and 10^5 also.
It compiles normally on my computer but whenever I submit it, it returns a run_error.
Here's what I wrote.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void input (int *);
int main(){
int n;
input (&n);
int a[n];
for(int i=0;i<n;i++){
if (scanf("%d",&a[i])!=1)
return 0;
if ((a[i]>100000)||(a[i]<1))
return 0;
}
for (int i=0;i<n;i++){
if (a[abs(a[i])]>=0){
a[abs(a[i])]=-a[abs(a[i])];
} else {
printf("%d",abs(a[i]));
return 0;
}
}
return 0;
}
void input(int *x){
if (scanf("%d",x)!=1)
exit(0);
if ((*x>100000)||(*x<1))
exit(0);
}
This program is logically incorrect. There is no connection between the size of the array defined in n and the limit of the allowed elements.
Since you have allowed a[i]>100000 to go up to 10^5 with no regards to the size of the array defined by a[n], the following access will attempt to access outside the bounds of the array, a[abs(a[i])] for any a[i] > n.
Also, you can pass by reference for syntactical simplicity
input(n);
void input(int &x){
if (scanf("%d",&x)!=1)
exit(0);
if (x>100000 ||x<1)
exit(0);
}
First of all, if you are writing in C, please tag this question as C question, and not as C++ one. scanf & printf are C functions, as much as your includes stdio.h & stdlib.h & math.h. In c++ you have the include iostream, and in this case it's all you really need.
The second problem here is the way you handle the input validation when it wrong. exit is very dangerous way, and very not recommended. If you want to throw exception use throw method (Read about the difference between the two: https://stackoverflow.com/a/56406586/8038186). But, in this case I don't understand why do you need to throw exception at all. you can simply finish the program in more gentle way. Consider the following flow:
#include <iostream>
using namespace std;
// Num is moved by reference and not by pointer
bool input(int &num) { // return true if the input is good, otherwise return false.
cout << "Please enter number: " << endl; // Tell the user that he should enter a number.
cin << num;
bool is_valid = num >= 1 && num <= 1e5; // 1e5 = 100000
if (!is_valid) cout << "Invalid input." << endl;
return is_valid;
}
int main() {
int n;
if (!input(n)) {
return 0;
}
int a[n];
int i;
for (i = 0; i < n && input(a[i]); i++);
if (i < n) {
return 0;
}
for (i = 0; i < n; i++) {
// The following if is useless, the validation make sure already that all of the numbers are legal.
//if (a[a[i]] >= 0) { // You don't need abs(a[i]), a[i] > 1
if (a[i] < n)
a[a[i]] = -a[a[i]];
else cout << "Consider what do you want to do" << endl;
/*} else {
printf("%d", a[i]);
return 0;
}*/
}
return 0;
}
Read about the difference between reference and pointer: What are the differences between a pointer variable and a reference variable in C++?
I have to find the minimum and maximum value of elements in a array using divide and conquer. I have written a code but it is not working for more then 6 elements in array. I don't know whats the problem
#include<iostream>
using namespace std;
int minimum=999,maximum,mi,ma;
void result(int mi,int ma)
{
if(maximum<ma)
{
maximum=ma;
}
if(minimum>mi)
{
minimum=mi;
}
}
void maxmin(int arr[],int i,int j)
{
cout<<" i ="<<i<<" j= "<<j<<endl;
if(i==j)
{
mi=ma=arr[i];
result(mi,ma);
}
else if(i==j-1)
{
if(arr[i]>arr[j])
{
ma=arr[i];
mi=arr[j];
}
else
{
mi=arr[i];
ma=arr[j];
}
result(mi,ma);
}
else
{
int mid=i+j/2;
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
}
int main()
{
int arr[10],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
maxmin(arr,0,n-1);
cout<<" max "<<maximum<<" min "<<minimum<<endl;
return 0;
}
Your code has a few mistakes
Your code reads n from the user input, but you provided only 10 sized array, and user can try to input 10+ numbers, so we will have an undefined behavior in that case.
You write it very bad and unreadable. If you want somebody else to read your code, check in the your favourite book or in the internet information about how to write beautiful and readable code.
You implemented that algorithm yourself. It is a bad habit, use the standard library algorithms and you will not encounter such mistake.
.
#include <iostream> // std::cin, std::cout
#include <cstddef> // std::size_t
#include <algorithm> // std::min_element, std::max_element
int main ()
{
std::size_t array_size;
std::cin >> array_size;
int *some_array = new int[array_size]; // Allocate memory dynamically
for(std::size_t i = 0; i < array_size; ++i)
{
std::cin >> some_array[i];
}
/* Standard library operate on iterators, they are special classes
* that have interface that is similar in many cases to pointers (so we can use pointers as iterators).
* std::min/max_element needs one iterator for the sequence beginning
* and one iterator after the end. It returns iterator to a found element.
*/
int min = *std::min_element(some_array, some_array + array_size);
int max = *std::max_element(some_array, some_array + array_size);
delete[] some_array;
std::cout << "Min = " << min << std::endl << "Max = " << max;
std::cout << std::endl;
}
Code isn't well written and first dry run your code, you will find the problem easily.
Change
else
{
int mid=i+j/2;
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
To
else
{
int mid=(i+j)/2; /*** Adding brackets ***/
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
And check the logic for calling the result function (because according to your logic the two subsets are individually calculating MIN and MAX in itself not in whole array)
I am writing a simple code to calculate Fabonacci numbers as an exercise. The code works, but i don't get why. I have some special cases for n=1 and n=2 which is the place of the number in the sequence (the numbers are 0 and 1). However after those, the number is calculated in this loop.
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
Going in to the loop, Fib_1=0, Fib_2=0, and Fib_n=1. Why does not this loop just spit out 0 no matter what? The whole code is below.
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >>n;
cout <<endl;
int Fib_n;
int Fib_1;
int Fib_2;
int LoopCount=1;
if(n>1)
{
Fib_n=1;
LoopCount++;
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
}
cout <<Fib_n;
return 0;
}
int Fib_1;
int Fib_2;
were never initialized. Therefore, the first time you calculate Fib_n=Fib_1+Fib_2;, Fib_n will get the sum of two uninitialized variables.
I have modified your code so it would work.
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >> n;
cout << endl;
int Fib_1 = 1;
int Fib_2 = 1;
int count = 0;
while(n > count)
{
Fib_1 = Fib_1 + Fib_2;
Fib_2 = Fib_1 - Fib_2;
count++;
}
cout << Fib_1;
return 0;
}
Fib_1
You have that as an uninitalized variable, so you may get a garbage value for output.
Fib_2 = Fib_1
Next, you initialize Fib_2 with Fib_1, meaning they both share the same (random) value.
In debug mode, these are both initialized to 0, and adding them:
Fib_n=Fib_1+Fib_2;
makes the sum equal 0. In release mode, you can expect random values from the compiler. Here is more info on Uninitialized Variables.
Below is my code, for solving problem 7 of PE ("find the 10001th prime"):
#include <iostream>
using namespace std;
bool isPrime(int n, int primes[], int l){
int i=0;
for (int i=0; i < l; i++){
if (primes[i] != 0 && n%primes[i] == 0){
return false;
}
}
return true;
}
int main()
{
int k=3;
int primes[10001] = {0};
primes[0]=2;
const int l=sizeof(primes)/sizeof(primes[0]);
int N=0;
while (N < l){
if(isPrime(k, primes, l)==true){
primes[++N]=k;
}
k+=2;
}
cout << primes[l-1] << endl;
return 0;
}
This code solves the problem, but there is a mistake in it: on the final iteration of the while loop, the instruction is to set primes[10001]=k;, which attempts to change a value of an element of an array that doesn't exist. If I don't declare it to be constant, and (as a means of troubleshooting) replace l by 10001 in the while loop, the value of l becomes equal to the 10002th prime at the end of the loop.
Here is the main function part of this happening:
int main()
{
int k=3;
int primes[10001] = {0};
primes[0]=2;
int l=sizeof(primes)/sizeof(primes[0]);
int N=0;
while (N < l){
if(isPrime(k, primes, 10001)==true){
primes[++N]=k;
}
k+=2;
}
cout << l << endl;
return 0;
}
My question is, why does this happen? I do know that a simple fix is to stop the loop at l-1 (or better, initialize with N=1 instead and increment N after), but I'm more interested in how this code can affect a variable that isn't being explicitly (directly?) involved in the bad part of the code.
Thank you!
The [] Operator does no bounds checking. some_array[102], will simple go 102 * sizeof(type) if thats outside your array, thats outside your array. C++ won't care.
These are some of the nastiest bugs that can generated if you are lucky you program will crash, sometimes you can just end up changing somebody else's variable.
Which is why I harp on at work about using std::array and std::vector alot because they come with .at(i) functions which have bounds checking.
Here is my code for printing the divisors and then number of divisors of a given number.
Now suppose I take 2 test cases: 5 and 8; this code gives count of 5 as 2 and 8 as 6 (i.e it adds the previous count).
Even if I declare it as int count = 0; it returns the same output.
The other problem arises when I declare int count = 0 inside function factors.
The code gives count as 0 for all cases.
#include<iostream>
using namespace std;
int count;
long long factors(long n, long f=1)
{
if(n%f==0) {
cout << f << endl;
count++;
}
if(f==n) {
return 0;
}
factors(n,f+1);
return count;
}
int main()
{
int n;
int t;
cin >> t;
while(t--)
{
cin >> n;
cout << factors(n) << endl;
}
return 0;
}
Using globals is not usually a good idea. It is especially bad in recursive functions, which should preferably be re-entrant. Of course you can fix your function by resetting the count in the loop, like this:
while(t--)
{
cin>>n;
count = 0; // Reset count before the recursive call
cout << factors(n) << endl;
}
You could also make factors "wrapper" that resets the count to free the callers from the need to reset count before calling factors, like this:
long long factors(long n) {
count = 0;
return factors(n, 1);
}
long long factors(long n,long f /* Remove the default */) {
... // the rest of your code
}
you can achieve this by passing count as reference -
#include<iostream>
using namespace std;
long long factors(long n, int& count, long f=1)
{
if(n%f==0)
{
cout<<f<<endl;
count = count + 1;
}
if(f==n)
return 0;
factors(n, count, f+1);
return 0;
}
int main()
{
int n,t;
cin>>t;
while(t--)
{
cin>>n;
int count = 0;
factors(n, count);
cout << count << endl;
}
return 0;
}
-Gaurav
First, why are you declaring the count variable in the global space?
Second, you can not perform arithmetic operations to an undeclared variable (the int "count" in this case is never declared).
Third, why do you create an infinite loop by doing while(t--)?
You said the function gives you count as 0 for all input,
Can this be due to count never being declared?