C++ Function is not returning a value - visual-c++

here is my code, I can not figure out why it won't work as a function when the exact code in main() produces the correct answer. The assignment is to convert binary number to decimal.
#include <iostream>
#include <cstdlib>
#include "std_lib_facilities.h"
using namespace std;
int binaryCon(int biNum);
int main()
{
int num, bin, Bnum;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
Bnum = binaryCon(num);
cout << "The decimal equivalent of " << bin << " : " << Bnum << endl;
}
int binaryCon(int biNum)
{
long dec = 0, rem = 0, base = 1;
enter code here`while (biNum > 0)
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
return biNum;
}

corrected code:
#include <iostream>
#include <cstdlib>
using namespace std;
int binaryCon(int biNum);
int main()
{
int num, bin, Bnum;
cout << "Enter the binary number(1s and 0s) : ";
cin >> num;
bin = num;
Bnum = binaryCon(num);
cout << "The decimal equivalent of " << bin << " : " << Bnum << endl;
getchar();
return 0;
}
int binaryCon(int biNum)
{
long dec = 0, rem = 0, base = 1;
while (biNum > 0){
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}
return dec;
}

As you are not using { and } in your while loop may be its going in infinite loop. As its working for this line only
while (biNum > 0)
rem = biNum % 10; // running this line infinite as `biNum > 0`
Use
while (biNum > 0){
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}

maybe this?
while (biNum > 0)
{
rem = biNum % 10;
dec = dec + rem * base;
base = base * 2;
biNum = biNum / 10;
}

int main() or int main(int argc, char** argv) must return a value. If you return 0 then it means that there is no problem with code. Another numbers 1,2 etc means there is an error.(Returned numbers are error numbers)

Related

Why the output goes wrong when using pthread_join?

I am still learning about threads and I was trying to solve this problem in my code, when I am putting the pthread_join(thread[i],NULL) outside the loop that is creating the threads it always gives me wrong output and Thread with ID = 0 will not work(call the median func) and the last thread will work two times, for better understanding see the output below:
ThreadID= 0, startRow= 0, endRow= 0 // first thread doesn't call the median func
ThreadID= 1, startRow= 1, endRow= 1
ThreadID 1 numOfBright 0 numOfDark 1 numOfNormal 4
ThreadID= 2, startRow= 2, endRow= 2
ThreadID 2 numOfBright 0 numOfDark 1 numOfNormal 4
ThreadID= 3, startRow= 3, endRow= 3
ThreadID 3 numOfBright 0 numOfDark 0 numOfNormal 5
ThreadID= 4, startRow= 4, endRow= 4
ThreadID 4 numOfBright 0 numOfDark 5 numOfNormal 0
ThreadID 4 numOfBright 0 numOfDark 5 numOfNormal 0 // last thread is calling the median func two times.
This is the part of the code that prints the start and end row of each thread.
pthread_t* threads = new pthread_t[num_threads];
struct Th_Range* RANGE = (struct Th_Range*)malloc(sizeof(struct Th_Range*));
int thread_status;
RANGE->SizeOfImage = r; // 2d array with size (n*n) so rows(r) = columns(c)
if (n == num_threads) { //rows = num of threads then every thread will work in a single row
for (int i = 0; i < num_threads; i++) {
RANGE->ThreadId = i;
RANGE->StartRow = RANGE->EndRow = i;
cout << "ThreadID= " << i << ", startRow= " << RANGE->StartRow << ", endRow= " << RANGE->EndRow << endl;
thread_status = pthread_create(&threads[i], NULL, Median, RANGE);
if (thread_status)
exit(-1);
} //for loop ends here
for (int i = 0; i < num_threads; i++)
pthread_join(threads[i],NULL);
} //end of if statement
Here is the part of the code if needed with the median function and the above if statement.
#include <iostream>
#include <bits/stdc++.h>
#include <pthread.h>
pthread_mutex_t Lock;
pthread_mutex_t Pixels;
pthread_mutex_t Pixels2;
using namespace std;
int numOfBright, numOfDark, numOfNormal;
int** Oimage, ** Fimage; //original and filtered image
struct Th_Range {
int SizeOfImage;
int StartRow;
int EndRow;
int ThreadId;
};
void* Median(void* par)
{
struct Th_Range* Num = (struct Th_Range*)par;
int StartRow = Num->StartRow;
int EndRow = Num->EndRow;
int Size = Num->SizeOfImage;
int Neighbour[9] = { 0 };
int dark = 0, bright = 0, normal = 0;
if (EndRow == StartRow)
EndRow += 2;
else
EndRow++;
for (int i = StartRow +1; i < EndRow ; i++)
{
for (int j = 1; j < Size - 1; j++)
{
Neighbour[0] = Oimage[i - 1][j - 1];
Neighbour[1] = Oimage[i - 1][j];
Neighbour[2] = Oimage[i - 1][j + 1];
Neighbour[3] = Oimage[i][j - 1];
Neighbour[4] = Oimage[i][j];
Neighbour[5] = Oimage[i][j + 1];
Neighbour[6] = Oimage[i + 1][j - 1];
Neighbour[7] = Oimage[i + 1][j];
Neighbour[8] = Oimage[i + 1][j + 1];
pthread_mutex_lock(&Pixels); //it can be moved only to lock the Fimage and the numOfBright or any other global variables
sort(Neighbour, Neighbour + 9);
Fimage[i][j] = Neighbour[4];
if (Neighbour[4] > 200) {
bright++;
numOfBright++;
}
else if (Neighbour[4] < 50) {
dark++;
numOfDark++;
}
else {
normal++;
numOfNormal++;
}
pthread_mutex_unlock(&Pixels);
}
}
pthread_mutex_lock(&Pixels2); //when I try to remove this lock the output gets interrupted
cout << "ThreadID " << Num->ThreadId << " numOfBright " << bright << " numOfDark " << dark << " numOfNormal " << normal<<endl;
pthread_mutex_unlock(&Pixels2);
pthread_exit(NULL);
}
int main(int argc, char* argv[])
{
int num_threads, n, r, c; // n is the size of the matrix r and c are rows and columns
numOfNormal = numOfDark = numOfBright = 0;
if (argc >= 2)
num_threads = atoi(argv[1]);
else
exit(-1);
ifstream cin("input.txt");
cin >> n;
r = c = n + 2;
Oimage = new int* [r]();
Fimage = new int* [r]();
for (int i = 0; i < c; i++)
{
Oimage[i] = new int[c]();
Fimage[i] = new int[c]();
}
for (int i = 1; i < r - 1; i++)
for (int j = 1; j < c - 1; j++)
cin >> Oimage[i][j];
pthread_t* threads = new pthread_t[num_threads];
struct Th_Range* RANGE = (struct Th_Range*)malloc(sizeof(struct Th_Range*));
RANGE->SizeOfImage = r;
if (n == num_threads) { //rows = num of threads then every thread will work in a single row
//n+2
int thread_status;
for (int i = 0; i < num_threads; i++) {
RANGE->ThreadId = i;
RANGE->StartRow = RANGE->EndRow = i;
// pthread_mutex_lock(&Lock);
cout << "ThreadID= " << i << ", startRow= " << RANGE->StartRow << ", endRow= " << RANGE->EndRow << endl;
thread_status = pthread_create(&threads[i], NULL, Median, RANGE);
if (thread_status)
exit(-1);
}
}
I tried to move pthread_join inside the loop of pthread_create it gives a correct output but of course it is a wrong solution. I have no idea what to do next. Thanks in advance
Maybe you should use #include
or (using namespace sff) it must work

Why is this triggering a breakpoint?

I have looked extensively for the problem in this code, but I can't seem to figure out what tragic error I made and why it is triggering a breakpoint.
(After 3 or 4 inputs, it triggers and I don't know why it doesn't trigger at the start or what is causing it)
#include <conio.h> // For function getch()
#include <cstdlib> // For several general-purpose functions
#include <fstream> // For file handling
#include <iomanip> // For formatted output
#include <iostream> // For cin, cout, and system
#include <string> // For string data type
using namespace std; // So "std::cout" may be abbreviated to "cout", for example.
string convertDecToBin(int dec)
{
int *arrayHex, arraySize = 0;
arrayHex = new int[];
string s = " ";
int r = dec;
for (int i = 0; r != 0; i++)
{
arrayHex[i] = r % 2;
r = r / 2;
arraySize++;
}
for (int j = 0; j < arraySize; j++)
{
s = s + to_string(arrayHex[arraySize - 1 - j]);
}
delete[] arrayHex;
return s;
}
string convertDecToOct(int dec)
{
int *arrayHex, arraySize = 0;
arrayHex = new int[];
string s = " ";
int r = dec;
for (int i = 0; r != 0; i++)
{
arrayHex[i] = r % 8;
r = r / 8;
arraySize++;
}
for (int j = 0; j < arraySize; j++)
{
s = s + to_string(arrayHex[arraySize - 1 - j]);
}
delete[] arrayHex;
return s;
}
int main()
{
int input = 0;
while (input != -1)
{
cout << "\nEnter a decimal number (-1 to exit loop): ";
cin >> input;
if (input != -1)
{
cout << "Your decimal number in binary expansion: " << convertDecToBin(input);
cout << "\nYour decimal number in octal ecpression: " << convertDecToOct(input);
}
}
cout << "\n\nPress any key to exit. . .";
_getch();
return 0;
}
arrayHex = new int[] is your problem - C\C++ does not support dynamic sizing arrays. You need to specify a size for the array to allocation, otherwise you'll get memory block overruns.

How to solve http://www.spoj.com/problems/MST1/ in n is 10^9

Using Bottom to up DP approach, I am able to solve the problem How to solve http://www.spoj.com/problems/MST1/ upto 10^8.
If input is very large n upto 10^9. I will not be able to create lookup table for upto 10^9. So what will be better approach to solve the problem ?
Is there any heuristic solution ?
#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
int main()
{
const int N_MAX = 20000001;
int *DP = new int[N_MAX];
DP[1] = 0;
for (int i = 2; i < N_MAX; i++) {
int minimum = DP[i - 1];
if (i % 3 == 0) minimum = min(minimum, DP[i/3]);
if (i % 2 == 0) minimum = min(minimum, DP[i/2]);
DP[i] = minimum + 1;
}
int T, N; cin >> T;
int c = 1;
while (T--) {
cin >> N;
cout << "Case " << c++ << ": " << DP[N] << endl;
}
delete[] DP;
}

cannot display a string in visual c++

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <vector>
using namespace std;
class TheNumberGameDivTwo{
private:
public:
string find( int n ){
string n1 = "John";
string n2 = "Brus";
//cout << "Mahesh"<< n2 << n1;
int i,q;
q = 0;
int k = n;
i = n-1;
for ( i = 2 ; i < k ; ++i ){
if ( !(k % i) ){
q += k / i;
k = k % i;
}
}
if ( q % 2 )
return "John";
else
return "Brus";
}
};
int main(){
TheNumberGameDivTwo T;
cout << endl << T.find(6);
cout << endl << "End of Program " << endl;
system("PAUSE");
}
Error 1
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
d:\my documents\visual studio 2012\c++\topcoder\topcoder\source1.cpp 34 1 TopCoder
You are missing #include <string>

how do i avoid using pointer variables and pointer-based pass-by-reference in this program?

how do i avoid using pointer variables and pointer-based pass-by-reference in this program? as my instructor said there is no need to use pointers. This is a the tortoise and the hare simulator , you will use number generation to develop a simulation of this memorable event.
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
#include <iomanip>
using std::setw;
const int RACE_END = 70;
// prototypes
void moveTortoise( int *const );
void moveHare( int *const );
void printCurrentPositions( const int *const, const int *const );
int main()
{
int tortoise = 1;
int hare = 1;
int timer = 0;
srand( time( 0 ) );
cout << "ON YOUR MARK, GET SET\nBANG !!!!"
<< "\nAND THEY'RE OFF !!!!\n";
// loop through the events
while ( tortoise != RACE_END && hare != RACE_END )
{
moveTortoise( &tortoise );
moveHare( &hare );
printCurrentPositions( &tortoise, &hare );
timer++;
} // end loop
if ( tortoise >= hare )
cout << "\nTORTOISE WINS!!! YAY!!!\n";
else
cout << "\nHare wins. Yuch.\n";
cout << "\nTIME ELAPSED = " << timer << " seconds" << "\n" << endl;
system("pause");
return 0; // indicates successful termination
} // end main
// progress for the tortoise
void moveTortoise( int * const turtlePtr )
{
int x = 1 + rand() % 10; // random number 1-10
if ( x >= 1 && x <= 5 ) // fast plod
*turtlePtr += 3;
else if ( x == 6 || x == 7 ) // slip
*turtlePtr -= 6;
else // slow plod
++( *turtlePtr );
if ( *turtlePtr < 1 )
*turtlePtr = 1;
else if ( *turtlePtr > RACE_END )
*turtlePtr = RACE_END;
} // end function moveTortoise
// progress for the hare
void moveHare( int * const rabbitPtr )
{
int y = 1 + rand() % 10; // random number 1-10
if ( y == 3 || y == 4 ) // big hop
*rabbitPtr += 9;
else if ( y == 5 ) // big slip
*rabbitPtr -= 12;
else if ( y >= 6 && y <= 8 ) // small hop
++( *rabbitPtr );
else if ( y > 8 ) // small slip
*rabbitPtr -= 2;
if ( *rabbitPtr < 1 )
*rabbitPtr = 1;
else if ( *rabbitPtr > RACE_END )
*rabbitPtr = RACE_END;
} // end function moveHare
// display new position
void printCurrentPositions( const int * const snapperPtr,
const int * const bunnyPtr )
{
if ( *bunnyPtr == *snapperPtr )
cout << setw( *bunnyPtr ) << "OUCH!!!";
else if ( *bunnyPtr < *snapperPtr )
cout << setw( *bunnyPtr ) << 'H'
<< setw( *snapperPtr - *bunnyPtr ) << 'T';
else
cout << setw( *snapperPtr ) << 'T'
<< setw( *bunnyPtr - *snapperPtr ) << 'H';
cout << '\n';
} // end function printCurrentPositions
In C++ you can use references instead of pointers. For example, instead of
void foo(int *x) {
*x = *x + 1;
}
int main() {
int a = 0;
foo(&a);
return 0;
}
you can pass x by reference, like so:
void foo(int &x) {
x = x + 1;
}
int main() {
int a = 0;
foo(a);
return 0;
}
Passing a reference is sort of like passing a pointer, except you don't need to dereference the pointer every time you want to access the value it points to.
You can google "C++ pass by reference" for more information, such as this tutorial: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Alternatively, in your program, you could simply pass int arguments and return the new value:
int moveTortoise(int turtle) {
...
turtle = turtle + 3;
...
return turtle;
}
tortoise = moveTortoise(tortoise)
References& and pointers* are usefull when:
1. you deal with instances of complex classes that passing by reference is resource(CPU time & main memory) consuming operation;
2. when you want to change arguments what are passed(as any function in C++ can return only one value, opposit for ex. to python where multiply values can be returned, you can cope with that restriction by passing using & or *);
3. Other cases...
Built-in(atomic) types can be passed by value (which is you case) without decrease in efficiency.

Resources