How to exit a loop (while loop) with an if statement from a function called within the loop? - function

So like:
void aLoop(){
int i = 0;
while(i < 10){
aFunction();
i++;
}
}
int aFunction(int i){
if(aVariable == 1){
i = 10;
}
if(aVariable != 1){
statement;
statement;
i = i;
}
return i;
}
Where aFunction() will be called for each i (0,1,2,3,...,9) and for each call will satisfy either the first if statement or the second.
Assuming all functions and variables are declared, would this be able to stop the while loop if aVariable == 1?
How else could you accomplish the same thing?
I'm really inexperienced with programming.
FIXED:
void aLoop(){
int i = 0;
while(i < 10){
i = aFunction(i);
i++;
}
}
int aFunction(int i){
if(aVariable == 1){
i = 10;
}
if(aVariable != 1){
statement;
statement;
i = i;
}
return i;
}

instead of
aFunction(x);
just use
i = aFunction(x);

use return to terminate a method.
USe break to terminate a for/ while loop or in a switch statement.

void aLoop(){
int i = 0;
do{
aFunction();
System.out.print(i+" ");
i++;
}while(i < 10);
}

Your suggested solution under "FIXED" will work but if you wrote a large program using this approach you'd end up with software that would be very complex and very costly to work on. This is because aFunction is dependent on the function aLoop that calls it. Functions should ideally be independent of each other, whereas aFunction only works if it's being called from a while loop. You almost never want a called function to be dependent on the structure of the function that calls it.
Try to code so that the the responsibilities or "intentions" of each part of the program are clear, so that any dependencies are minimal and obvious. E.g. here you could write
void aLoop(){
bool continueProcessing = true;
for(int i=0;
continueProcessing && i < 10;
i++) {
continueProcessing = aFunction(i);
}
}
int aFunction(int i){
bool stillProcessing = aVariable != 1;
if (stillProcessing) {
statement;
statement;
}
return stillProcessing;
}
Of course, in aLoop there are some other options which amount to the same thing. You could carry on with a while loop (I think for is clearer). Also, you could break out of the loop instead of having an extra continueProcessing variable.
void aLoop(){
for(int i=0; i < 10; i++) {
if (!aFunction(i))
break;
}
}
Finally I'm not sure you even need to pass the variable i into aLoop. If you don't, or some other data is more appropriate, it would be better to change this too.

Related

What is wrong with my code? prime factors

int main ()
{
int num, i=num, isPrime;
printf("Enter an integer: ");
scanf("%d", &num);
while (i>=2)
{
if (num%i!=0)
i--;
if (num%i==0) //check if it is a factor
{
isPrime = 1;
for (int j=2; j<=i; j++)
{
if (i%j==0)
{
isPrime = 0;
break;
}
}
if (isPrime==1)
{
printf("%d ", i);
num = num/i;
}
}
}
return 0;
}
May I know why is my code not working?
I was trying to write a C code which print all prime factors of a given number from the biggest factor to the smallest and when I run it just show nothing after I input a number.
#include of required header stdio.h to use printf() and scanf() is missing.
num is assigned to i before a value is read to num. This is assigning an indeterminate value to i and using the value invokes undefined behavior.
Looping j until it becomes i is wrong because i%i will always become zero unless i is zero.
You should decrement i also when num%i==0 and i is not prime. Otherwise, the update of i will stop there and the loop may go infinitely.
The two if statements if (num%i!=0) and if (num%i==0) may see different values of i. This happens when num%i!=0 at the beginning of the iteration because i is updated when the condition is true. You should use else instead of the second if statement.
Fixed code:
#include <stdio.h>
int main (void)
{
int num, i, isPrime;
printf("Please enter an integer: ");
if (scanf("%d", &num) != 1)
{
fputs("read error\n", stderr);
return 1;
}
i=num;
while (i>=2)
{
if (num%i!=0) //check if it is a factor
{
i--;
}
else
{
isPrime = 1;
for (int j=2; j<i; j++)
{
if (i%j==0)
{
isPrime = 0;
break;
}
}
if (isPrime==1)
{
printf("%d ", i);
num = num/i;
}
else
{
i--;
}
}
}
return 0;
}
At least one bug here:
int num, i=num, isPrime;
It seems you are trying to make i equal to num. But here `num isn't even initialized yet. You have to do the assignment after reading user input:
int num, i, isPrime;
printf("Please enter an integer: ");
scanf("%d", &num);
i=num;
Also the check for primes is wrong:
for (int j=2; j<=i; j++)
{
if (i%j==0)
{
isPrime = 0;
break;
}
}
Since you use j<=i then j will eventually be equal to i and i%j==0 will be true so you don't find any primes. Try j<i instead.

Can I use return 1, return 2 or any other integer instead of return 0 in a function if it is not returning an integer for a particular case?

here is my function:
int repeatedNTimes(int* A, int ASize)
{
int i, count, j, temp;
for(i = 0; i < ASize; ++i)
{
count = 0;
temp = A[i];
for(j = i; j < ASize; ++j)
{
if(A[i] == A[j])
count++;
}
if(count == ASize / 2)
return A[i];
else
continue;
}
return 0;
}
Can I use return 1, or return (any integer) instead of return 0?
And secondly, what if I don't return an integer?
If you do not return an integer, then the behavior is not well defined (probably undefined, but I don't have the standard memorized). Your compiler will likely emit a warning if you have warnings on.
As for returning an integer other than 0, yes, you can do that. What matters is the return type of the function when it comes to what you can and cannot return. That said, returning a different result may not have the effect you want depending on what your function does. Sometimes values like zero are reserved for special conditions like not found.

How to convert bytes 32 array?

I tried do this, but this return "0x0000000000000000000000000000000000000000"
// Convert bytes to address
function fromBytes(bytes32[] _additionalArgs) public view returns (address[]){
address[] memory path = new address[](_additionalArgs.length);
for(uint i = 0; i > _additionalArgs.length; i++){
path[i] = address(_additionalArgs[i]);
}
return path;
}
I need return array with addresses!
Your loop never executes.
for(uint i = 0; i > _additionalArgs.length; i++){
i begins at 0, and the loop condition is i > _additionalArgs.length, which can't ever be true. You almost certainly meant to use < instead:
for(uint i = 0; i < _additionalArgs.length; i++){
With that change, I believe your code should work.

C++ ROT13 Function Crashes

I'm not too good with C++, however; my code compiled, but the function crashes my program, the below is a short sum-up of the code; it's not complete, however the function and call is there.
void rot13(char *ret, const char *in);
int main()
{
char* str;
MessageBox(NULL, _T("Test 1; Does get here!"), _T("Test 1"), MB_OK);
rot13(str, "uryyb jbeyq!"); // hello world!
/* Do stuff with char* str; */
MessageBox(NULL, _T("Test 2; Doesn't get here!"), _T("Test 2"), MB_OK);
return 0;
}
void rot13(char *ret, const char *in){
for( int i=0; i = sizeof(in); i++ ){
if(in[i] >= 'a' && in[i] <= 'm'){
// Crashes Here;
ret[i] += 13;
}
else if(in[i] > 'n' && in[i] <= 'z'){
// Possibly crashing Here too?
ret[i] -= 13;
}
else if(in[i] > 'A' && in[i] <= 'M'){
// Possibly crashing Here too?
ret[i] += 13;
}
else if(in[i] > 'N' && in[i] <= 'Z'){
// Possibly crashing Here too?
ret[i] -= 13;
}
}
}
The function gets to "Test 1; Does get Here!" - However it doesn't get to "Test 2; Doesn't get here!"
Thank you in advanced.
-Nick Daniels.
str is uninitialised and it is being dereferenced in rot13, causing the crash. Allocate memory for str before passing to rot13() (either on the stack or dynamically):
char str[1024] = ""; /* Large enough to hold string and initialised. */
The for loop inside rot13() is also incorrect (infinte loop):
for( int i=0; i = sizeof(in); i++ ){
change to:
for(size_t i = 0, len = strlen(in); i < len; i++ ){
You've got several problems:
You never allocate memory for your output - you never initialise the variable str. This is what's causing your crash.
Your loop condition always evaluates to true (= assigns and returns the assigned value, == tests for equality).
Your loop condition uses sizeof(in) with the intention of getting the size of the input string, but that will actually give you the size of the pointer. Use strlen instead.
Your algorithm increases or decreases the values in the return string by 13. The values you place in the output string are +/- 13 from the initial values in the output string, when they should be based on the input string.
Your algorithm doesn't handle 'A', 'n' or 'N'.
Your algorithm doesn't handle any non-alphabetic characters, yet the test string you use contains two.

Returns and/or breaks in the middle of a loop. Is it ever acceptable?

Suppose we have an array of integers. We've written a function to fetch the index of the first specified value in the array, or -1 if the array does not contain the value..
So for example, if the array = { 4, 5, 4, 4, 7 }, then getFirstIndexOf(4) would return 0, getFirstIndexOf(7) would return 4, and getFirstIndexOf(8) would return -1.
Below, I have presented three different ways to write this function. It is a widely accepted coding standard that returns in the middle of functions, and breaks in the middle of loops are poor practice. It seems to me that this might be an acceptable use for them.
public int getFirstIndexOf(int specifiedNumber) {
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
return i;
}
}
return -1;
}
VS.
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
result = i;
break;
}
}
return result;
}
VS.
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber && result == -1) {
result = i;
}
}
return result;
}
What do you think? Which is best? Why? Is there perhaps another way to do this?
I think it's poor practice to run a full loop when you have already found your result...
If you really want to avoid using return from the middle of the loop, I would sugest to use a "sentinel" to stop your loop.
public int getFirstIndexOf(int specifiedNumber, int[] array) {
boolean found = false;
boolean exit = false;
int i = 0;
int arraySize = array.length();
while(!found && !exit) {
if(array[i] == specifiedNumber) {
found = true;
} else {
if(i++ > arraySize) {
exit = true;
}
}
if(found ==true) {
return i;
} else {
return 99999;
}
}
edit: I hate to indent code using spaces in StackOverflow...
That's why do...while & while loop was invented.
As requested:
public int getFirstIndexOf(int specifiedNumber) {
int i = array.Length;
while(--i > -1 && array[i] != specifiedNumber);
return i;
}