PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label while-loop. Show all posts
Showing posts with label while-loop. Show all posts

Monday, October 31, 2022

[FIXED] How to determine, inside of "while(fscanf != EOF){blah}", if the next fscanf is going to return EOF?

 October 31, 2022     c, eof, loops, scanf, while-loop     No comments   

Issue

I've got some code executing in a while(fscanf != EOF) loop. However, even when fscanf has finished executing, I need to keep running that code until some conditions are met. I mean I guess I could copy/paste the code to outside the while(fscanf) loop, and only use global variables, but that seems messy. Surely someone has encountered something like this before and has a cleaner solution.


Solution

Couldn't you just modify the while condition to account for these additional conditions?

while(fscanf(...) != EOF || !(some_other_conditions_met)) 


Answered By - Andreas Brinck
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, October 30, 2022

[FIXED] Why is the last line of my input file running twice?

 October 30, 2022     c++, eof, file-io, while-loop     No comments   

Issue

INPUT FILE

Miller Andrew 65789.87 5
Green Sheila 75892.56 9
Sethi Amit 74900.50 6.1

ifstream inFile;
ofstream outFile;
string laastName;
string firstName;
double salary;
double percent;
double new Salary;
double increase;

inFile.open("Ch3_Ex6Data.txt");
outFile.open("Ch3_Ex6Output.dat");

while(!inFile.eof()) {

    inFile >> lastName;
    inFile >> firstName;
    inFile >> salary;
    inFile >> percent;

    percent /= 100;
    increase = salary * percent;
    newSalary = increase + salary;

    outFile << firstName << " " << lastName << " ";
    outFile << setprecision(2) << fixed << newSalary << endl;

}

inFile.close();
outFile.close();

return 0
}

Output File

Andrew Miller 69079.36
Sheila Green 82722.89
Amit Sethi 79469.43
Amit Sethi 74946.19

My question is why is the last line getting output twice and why is it different than the first one? I don't understand why the loop continues on. Is the end of file marker not hitting? I was able to hard code it by putting in an index variable and putting a second condition into the while loop by saying && less than index but i feel as if i shouldn't have to do that whatsoever.


Solution

The problem is that eof does not do what you think it does.

Imagine you are walking on a floor, tile after tile, picking up what's on the floor, putting it in your pockets and show up (print) your pockets content.

When you put you feet on the last tile the floor is not yet "ended" and your nose is still safe. You have not (yet) smashed the wall. You fill-up the pockets and print them.

eof,then, tells you when your nose is broken, not when the tile is the last.

So, you are on the last tile, check your nose, find it ok, and go one step forward. Your nose is now bleeding, nothing is there to peek up to put in our pockets, and your pockets still contain ... what they had before.

You print the content of your pocket (once again) and than check your nose. It's broken: you exit.

The idiomatic way to solve that problem is this one:

while(inFile >> lastName
             >> firstName
             >> salary
             >> percent)
{
   //all your computation here
}

I think you should understand by yourself why.



Answered By - Emilio Garavaglia
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do I need to include EOF in my loop condition?

 October 30, 2022     c, eof, getchar, while-loop     No comments   

Issue

I have been given a task to write a program that will take keyboard input (excluding space) and print to a .txt file without using an array.

I tried to use a while loop to do this but was getting an infinite loop, I then came on to stack overflow and found a solution within a different problem, EUREKA!

Adding:

&& ch != EOF 

solved my problem.

However, I do not fully understand why the solution works and would like help to understand why this second condition was needed.

while((ch=getchar()) != '\n' && ch != EOF)
   {
       putc(ch, fin);
   }
   fclose(fin);
   return 0;

Thank you.


Solution

Because the return value of getchar is the character read on success, and EOF on error or when the end-of-file has been reached:

man getchar

RETURN VALUE

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

There are several reasons as to why stdin might reach end-of-file:

  • The user pressed Ctrl+D (on Unix/Linux) which causes stdin to close
  • stdin was connected to a pipe ($ cat file.txt | ./myprogram) and the pipe closed because cat ended.
  • stdin was connected to a redirection ($ ./myprogram < file.txt) and it reached the end of file.txt

On all this cases, getchar will eventually return EOF and you cannot keep reading. If you do

while((ch=getchar()) != '\n')
{
    ...
}

and stdin closes, then you end up in an endless loop, als EOF != '\n' always evaluates to true. So in order to protect yourself from that, you have to check if the read operation failed. And you do that by checking whether the reading function returned EOF. That's why

int ch;
while((ch=getchar()) != '\n' && ch != EOF)
{
    ...
}

is the correct way of looping with getchar. Also note that ch must be of type int.

Note also that this applies for all FILE buffers (opened in read mode), not only to stdin.



Answered By - Pablo
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use feof(FILE *f)?

 October 30, 2022     c, eof, feof, loops, while-loop     No comments   

Issue

I'm having a hard time with a do-while loop, that is supposed to stop when we reach the end of the file. Here's the loop code:

do  {
    if (pcompanyRow[0] != '#' && pass == 1) {
        strtok(pcompanyRow, ":");
        pcompanyName = strcpy(pcompanyName, strtok(NULL, ""));
        pass = 2;
        fgets(pcompanyRow, 1024, f);
    }
    if (pcompanyRow[0] != '#' && pass == 2) {
        strtok(pcompanyRow, ":");
        pcompanySMSPrice = strcpy(pcompanySMSPrice, strtok(NULL , ""));
        pass = 3;
        fgets(pcompanyRow, 1024 , f);
    }
    if (pcompanyRow[0] != '#' && pass == 3) {
        strtok(pcompanyRow, ":");
        pcompanyMMSPrice = strcpy(pcompanyMMSPrice, strtok(NULL, ""));
        pass = 4;
        fgets(pcompanyRow, 1024, f);
    }
    if (pass == 4)  {
        AppendCompanyNode(pcompanyList, pcompanyName, pcompanySMSPrice, pcompanyMMSPrice);
        pass = 1;
    }
} while (!feof(f));

After running with the debugger, I noticed that all the crash problems I have are because it doesn't go out of this loop even when it reached the whole lines.

How should I write it correctly?


Solution

I would change your loop and logic to use this:

while (fgets(pcompanyRow, 1024, f) != NULL) {

    /* do things */

}

when fgets() attempts to read past the end of the file, it will return NULL and you'll break out of the loop. You can still continue to use pass and your other flags/logic, but the conditions you check for will be slightly different.



Answered By - poundifdef
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get the while loop to recognise it is the end of the file

 October 30, 2022     eof, loops, python, readline, while-loop     No comments   

Issue

I have a text file with data that represents Line 1 name, email, phone Line 2 address Line 3 is an integer that says how many friends are listed. Line 4 ~ n Each line consists of a name

I have been able to get each line with

line = infile.readline()

I have a problem when I get to the end of the file.

It wants to loop around again as if it does not recognise the end of the file

infile = open(filename, "r")
lines = infile.readlines()

with open(filename) as infile:  
        line = infile.readline()
        count = 1
        while line:
            thisProfile = profile.Profile()          
            if count > 1:
                line = infile.readline()
                count += 1
            word = line.split()
            thisProfile.set_given_name(word[0])
            thisProfile.set_last_name(word[0])
            thisProfile.set_email_name(word[0])
            thisProfile.set_phone(word[0])

            ## LINE 2 -- ADDRESS
            line = infile.readline()
            count += 1
            thisProfile.set_address(line)

             ## LINE 3 -- GET FRIEND COUNT
             line = infile.readline()
             count += 1

             ## get all the friends and add them to the friends_list
             friendCount = int(line)
             thisProfile.set_number_friends(friendCount)
             friendList = []
             if friendCount > 0:
                 for allfreinds in range(0,friendCount):
                     line = infile.readline()
                     count += 1
                     friendList.append(line)
                 thisProfile.set_friends_list(friendList)

friends.txt

John Doe john.doe@hotmail.com 123456789
1 alltheway ave
1
Jane Doe
Paul Andrews paul.andrews@gmail.com 987654321
69 best street
0
Jane Doe jane.doe@facebook.com 159753456
1 alltheway ave
2
John Doe
Paul Andrews

Solution

The readline() method returns an empty string only when EOF is reached per the documentation, so you can add a condition to check if line is empty (not truthy) right after you call readline():

with open(filename) as infile:  
    while True:
        line = infile.readline()
        if not line:
            break
        thisProfile = profile.Profile()          
        word = line.split()
        thisProfile.set_given_name(word[0])

Alternatively, you can use the file object as an iterator with a for loop instead:

with open(filename) as infile:  
    for line in infile:
        thisProfile = profile.Profile()          
        word = line.split()
        thisProfile.set_given_name(word[0])


Answered By - blhsing
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] Why does my program print something before it ends when I press ctrl + D?

 October 29, 2022     c, eof, feof, while-loop     No comments   

Issue

So I wrote a simple program that converts a decimal to binary, that only accepts positive whole numbers. So numbers like -2 and 1.1 would output "Sorry, that's not a positive whole number." It infinitely asks the user to input a number until the user presses ctrl + D. However when I tested it it prints out the "Sorry..." statement before it ends the program.

Here is my code:

#include <stdio.h>
#include <stdlib.h>

void DecToBin(int userInput){
    int binary[32];
    int i = 0;
    while (userInput > 0) {
        binary[i] = userInput % 2;
        userInput /= 2;
        i++;
    }
    for (int j = i - 1; j >= 0; --j) {
        printf("%d", binary[j]);
    }
}

int main(void) {
    double userDec;
    int temp;

    printf("Starting the Decimal to Binary Converter!\n\n");

    while(!feof(stdin)) {
        printf("Please enter a positive whole number (or EOF to quit): ");
        scanf("%lf", &userDec);
        temp = (int)(userDec);
        if ((userDec > 0) && (temp / userDec == 1)) {
            printf("\n\t%.0lf (base-10) is equivalent to ", userDec);
            DecToBin(userDec);
            printf(" (base-2)!\n\n");
        }
        else {
            printf("\tSorry, that was not a positive whole number.\n");
        } 
    }
    printf("\n\tThank you for using the Decimal to Binary Generator.\n");
    printf("Goodbye!\n\n");
    return 0; 
}

(All the tab and newlines are just how it's supposed to be formatted so don't pay attention to that) So from what I'm understanding, my program reads ctrl + D as the else in my while loops. So, any idea why that is?


Solution

It seems like you think C-d would trigger some kind of break in the code. Like the keyword break. This is not true.

Read this post to see what's happening when you press C-d: https://stackoverflow.com/a/21365313/6699433

That does not cause anything special to happen in the C code. scanf will simply not read anything. After the scanf statement, the code will continue as usual, so the code WILL unconditionally enter the if statement.

This is also a pretty severe thing, because you'll be using userDec uninitialized. scanf returns the number of successful assignments, and you should always check the return value. So in your case you want this:

if(scanf("%lf", &userDec) != 1) { /* Handle error */ }

Because if scanf does not return 1, userDec is unassigned.

To achieve what you want, simply do this:

if(scanf("%lf", &userDec) != 1)
    break;


Answered By - klutt
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do i have to input EOF 3 times when using fgets?

 October 29, 2022     c, eof, fgets, stdin, while-loop     No comments   

Issue

So basically I want to copy everything i write to stdin (including newline char) to string for hash purposes. I managed to accomplish that and made small code to represent my problem.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFERSIZE 10000

int main()
{
char *myStr = calloc(1,1);
char buffer[BUFFERSIZE];

while( fgets(buffer, BUFFERSIZE , stdin) != NULL ){
  myStr = realloc(myStr, strlen(myStr)+1+strlen(buffer) );
  strcat( myStr, buffer );
}
printf("\n%s\n",myStr);

}

everything works when I enter some text then press ENTER and after I call EOF.

But when I start program enter "a" then I try to call EOF (using Ctrl Z + ⏎ (Windows cmd prompt), Ctrl D (Linux)) I have to do it three times for program to actually break the loop. I was expecting maximum of 2 times.

Can someone explain how using EOF, stdin and fgets works? Or should I use something else (for example getline)? I am sorry if I am not clear about my problem, just ask anything you need.

Thank you.


Solution

First of all, ^Z or ^D are control characters that mean something to the terminal you are using, and sometimes that means for the terminal to signal end-of-file condition.

Anyway, your three keypresses are processed by the terminal to take the following actions, after entering text:

  1. Flush the input (i.e. send the characters that have been input so far from the terminal to the program - by default this doesn't happen as the terminal uses line buffering)
  2. Set end-of-file condition
  3. Set end-of-file condition again

Inside your program that corresponds to:

  1. Nothing happens: even though a is received, fgets keeps reading until end-of-file or newline
  2. fgets completes because of end-of file. However it does not return NULL because characters were read, "a" to be specific.
  3. A bug in old versions of glibc causes fgets to try to read again, even though it previously reached end-of-file. fgets completes because of end-of-file, and returns NULL because there were no characters read.


Answered By - M.M
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is “while( !feof(file) )” always wrong?

 October 29, 2022     c, eof, feof, file, while-loop     No comments   

Issue

What is wrong with using feof() to control a read loop? For example:

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char **argv)
{
    char *path = "stdin";
    FILE *fp = argc > 1 ? fopen(path=argv[1], "r") : stdin;

    if( fp == NULL ){
        perror(path);
        return EXIT_FAILURE;
    }

    while( !feof(fp) ){  /* THIS IS WRONG */
        /* Read and process data from file… */
    }
    if( fclose(fp) != 0 ){
        perror(path);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

What is wrong with this loop?


Solution

TL;DR

while(!feof) is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.

I'd like to provide an abstract, high-level perspective. So continue reading if you're interested in what while(!feof) actually does.

Concurrency and simultaneity

I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists "concurrently" with your program. As with all things concurrent, questions about the "current state" don't make sense: There is no concept of "simultaneity" across concurrent events. Many properties of state simply don't exist concurrently.

Let me make this more precise: Suppose you want to ask, "do you have more data". You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says "yes" – by the time you try reading, it may no longer have data. Similarly, if the answer is "no", by the time you try reading, data may have arrived. The conclusion is that there simply is no property like "I have data", since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a "yes, I have data" that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)

So we conclude that it is impossible, and in fact unreasonable, to ask an I/O system whether it will be able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to attempt the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a "synchronisation point", if you will.)

EOF

Now we get to EOF. EOF is the response you get from an attempted I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply cannot know whether further, future operations will succeed. You must always first try the operation and then respond to success or failure.

Examples

In each of the examples, note carefully that we first attempt the I/O operation and then consume the result if it is valid. Note further that we always must use the result of the I/O operation, though the result takes different shapes and forms in each example.

  • C stdio, read from a file:

      for (;;) {
          size_t n = fread(buf, 1, bufsize, infile);
          consume(buf, n);
          if (n == 0) { break; }
      }
    

    The result we must use is n, the number of elements that were read (which may be as little as zero).

  • C stdio, scanf:

      for (int a, b, c; scanf("%d %d %d", &a, &b, &c) == 3; ) {
          consume(a, b, c);
      }
    

    The result we must use is the return value of scanf, the number of elements converted.

  • C++, iostreams formatted extraction:

      for (int n; std::cin >> n; ) {
          consume(n);
      }
    

    The result we must use is std::cin itself, which can be evaluated in a boolean context and tells us whether the stream is still in the good() state.

  • C++, iostreams getline:

      for (std::string line; std::getline(std::cin, line); ) {
          consume(line);
      }
    

    The result we must use is again std::cin, just as before.

  • POSIX, write(2) to flush a buffer:

      char const * p = buf;
      ssize_t n = bufsize;
      for (ssize_t k = bufsize; (k = write(fd, p, n)) > 0; p += k, n -= k) {}
      if (n != 0) { /* error, failed to write complete buffer */ }
    

    The result we use here is k, the number of bytes written. The point here is that we can only know how many bytes were written after the write operation.

  • POSIX getline()

      char *buffer = NULL;
      size_t bufsiz = 0;
      ssize_t nbytes;
      while ((nbytes = getline(&buffer, &bufsiz, fp)) != -1)
      {
          /* Use nbytes of data in buffer */
      }
      free(buffer);
    

    The result we must use is nbytes, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).

    Note that the function explicitly returns -1 (and not EOF!) when an error occurs or it reaches EOF.

You may notice that we very rarely spell out the actual word "EOF". We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.

  • A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:

      std::string input = "   123   ";   // example
    
      std::istringstream iss(input);
      int value;
      if (iss >> value >> std::ws && iss.get() == EOF) {
          consume(value);
      } else {
          // error, "input" is not parsable as an integer
      }
    

We use two results here. The first is iss, the stream object itself, to check that the formatted extraction to value succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, iss.get(), and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.

In the C standard library you can achieve something similar with the strto*l functions by checking that the end pointer has reached the end of the input string.



Answered By - Kerrek SB
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 28, 2022

[FIXED] how can you explain me this?

 October 28, 2022     if-statement, is-empty, loops, range, while-loop     No comments   

Issue

It gives me an empty list if I didnt put x=list(range(a, b, -1)) again in the loop while, why ?

Image

Thanks.


Solution

If a < b then the range will be created as an empty range. The range won't magically update when a and b gain new values because the values have already been assigned to the range. That's why you have to recreate the range with the updated values of a and b.



Answered By - Aplet123
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 18, 2022

[FIXED] How do I make my Print Statement print on only one line?

 September 18, 2022     printing, python, random, while-loop     No comments   

Issue

In this program I am trying to print my code as "random letters here" instead of "r" "a" "n" "d" "o" "m" etc.

import random
import time

All = "abcdefghijklmnopqrstuvwxyz1234567890"
i = 0

while i < 6:
    time.sleep(1)
    print(All[random.randint(1,35)])
    i += 1

Solution

You can pass end='' to the print statement so that subsequent prints are not separated by a newline, which is the default behavior. Also, here it makes sense to use a range iterator with for instead of while.

Note: I've taken the liberty to cut the sleep time in half, so it's easier to test it out.

import random
import time

All = "abcdefghijklmnopqrstuvwxyz1234567890"

for _ in range(6):
    time.sleep(0.5)
    print(All[random.randint(1, 35)], end='')


Answered By - rv.kvetch
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 29, 2022

[FIXED] How to create comma separated list from a while-loop?

 August 29, 2022     csv, php, while-loop     No comments   

Issue

$personas = [
'Hermann' => [
  'status' => '0',
  'gender' => 'maskulin'
],
'Lida' => [
  'status' => '1',
  'gender' => 'feminin'
],
'Susi' => [
  'status' => '0',
  'gender' => 'feminin'
],
'Mara' => [
  'status' => '0',
  'gender' => 'feminin'
]
];

Personas with status 0

  echo 'Personas with status 0: ';
  while ($status = current($personas)) {
    if ($status['status'] == '0') {
    $status_list = key($personas);
    echo $status_list;

  }
  next($personas);
}

Result is: Personas with status 0: HermannSusiMara

is expected: Personas with status 0: Hermann, Susi, Mara


Solution

A bit different solution for you.

$statusZeroPersonae = [];

foreach($personas as $personaName => $persona) {
    if ($persona['status'] === '0') {
        $statusZeroPersonae[] = $personaName;
    }
}

echo 'Personae with status 0: ' . implode(", ", $statusZeroPersonae);


Answered By - MyLibary
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 18, 2022

[FIXED] How can I count the outputs of a while loop in python?

 August 18, 2022     count, output, python, while-loop     No comments   

Issue

I would like to be able to insert a line of code that counts the number of times the output is "watch".

This is the picture of my current code


Solution

Try this one:

counter = 0
while Amzn > 1000:
    counter+=1
    print("Watch")
    Amzn = Amzn - (Amzn*.0103)
else:
    print("buy")
print(counter)


Answered By - Gabio
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 30, 2022

[FIXED] How to make simple number identification Python?

 July 30, 2022     conditional-statements, control-structure, python, validation, while-loop     No comments   

Issue

I have this exercise:

  1. Receive 10 integers using input (one at a time).
  2. Tells how many numbers are positive, negative and how many are equal to zero. Print the number of positive numbers on one line, negative numbers on the next, and zeros on the next.

That i need to solve it with control/repetition structures and without lists. And i'm stuck in the first part in dealing with the loops

Until now I only writed the part that deal with the amount of zeros, I'm stuck here:

n = float(input())  #my input

#Amounts of:

pos = 0   # positive numbers
neg = 0   # negative numbers
zero = 0  # zero numbers

while (n<0):
    resto = (n % 2)  
    if (n == 0):    #to determine amount of zeros
        zz = zero+1
        print (zz)  
    elif (resto == 0): #to determine amout of positive numbers
        pp = pos+1
        print (pp)
    elif (n<0):    #to determine amount of negative numbers
        nn = neg+1
    else:
        ("finished")

My inputs are very random but there are like negatives and a bunch of zeros too and obviously some positive ones. What specific condition i write inside while to make it work and to make a loop passing by all the numbers inside a range of negative and positive ones?

Soo.. i made it turn into float because theres some broken numbers like 2.5 and the inputs are separated by space, individual inputs of numbers one after other

example input (one individual input at a time):

25
2.1
-19
5
0 
 # ------------------------------------------
 #  the correct awnser for the input would be:
3                 #(amount of Positive numbers)
1                  #(amount of Negatives numbers)              
1                 #(amount of Zeros numbers)
how to make them all pass by my filters and count each specific type of it?

obs: i can't use lists!


Solution

Why not something like this?

pos = 0
neg = 0
zer = 0
for x in range(10):
    number = int(input())
    if number > 0:
        pos +=1
    if number < 0:
        neg +=1
    else: # number is not positive and not negative, hence zero
        zer +=1
print(pos)
print(neg)
print(zer)

EDIT: Thanks @Daniel Hao for pointing out that casting to int is necessary with input().



Answered By - Damiaan
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 21, 2022

[FIXED] How to find max number and occurrences

 July 21, 2022     integer, java, java.util.scanner, loops, while-loop     No comments   

Issue

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .

my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.

But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .

 package myjavaprojects2;
import java.util.*;
public class Max_number_count {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        int count = 0;
        int max = 1;
        System.out.print("Enter a Integer:");
        int userInput = input.nextInt();    

        while ( userInput != 0) {
           
                        
        if (userInput > max) {
            int temp = userInput;
            userInput = max;
            max = temp;
         } else if (userInput == max) {
             count++ ;
             
             
         }
             
    
        System.out.println("The max number is " + max );
        System.out.println("The count is " + count );
        }
      }
    }

Solution

So how do you take multiple inputs from the user on the same line .

You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.

 int userInput = input.nextInt();    

    while ( userInput != 0) {
      //all above logic
      userInput = input.nextInt();        
    }


Answered By - Manh Nguyen
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 19, 2022

[FIXED] How to get sequence of numbers and then print the last 5?

 July 19, 2022     c, for-loop, integer, loops, while-loop     No comments   

Issue

Im trying to make a program that will get sequence from the user that end with 0, and then i want to print the last 5 numbers (not including the 0).

I can assume that the user will input all the numbers in one line and will end it with 0.

I wrote that code but something is wrong with it, I think its something about the scanf line.

Input:

1 6 9 5 2 1 4 3 0

Output: no output

#include <stdio.h>
#define N 5

int main()
{
    int arr[N] = {0};
    int last_input, j;
    
    printf("please enter more than %d number and than enter 0: \n", N);
    
    last_input = 0;
    while (last_input<N) {
       scanf(" %d", &j);
       if (j == '0') {
          last_input = N;
          break;
       }
       else {
          arr[last_input] = j;
       }
       if (last_input==(N-1)) {
          last_input=-1;
       }
       ++last_input;
   }
    
    
    printf("The last %d numbers u entered are:\n", N); 
    
    for (j=(last_input+1); j<N; ++j) {
       printf(" %d", arr[j]);    
    }

    for (j=0; j<last_input; ++j) {
       printf(" %d", arr[j]);  
    }

    return 0;
}

Solution

This comparison

if (j == '0') {

does not make a sense because the user will try to enter the integer value 0 instead of the value (for example ASCII 30h or EBCDIC F0h) for the character '0'.

You need to write at least

if (j == 0) {

Due to these sub-statements of the if statement

  last_input = N;
  break;

this for loop

for (j=(last_input+1); j<N; ++j) {
   printf(" %d", arr[j]);    
}

is never executed and does not make a sense.

This statement

last_input=-1;

results in breaking the order of the N last elements in its output. And moreover the result value of the variable last_input will be incorrect.

You need to move elements of the array one position left. For this purpose you can use a loop of standard C function memmove.

The program can look the following way.

#include <stdio.h>
#include <string.h>


int main( void ) 
{
    enum { N = 5 };
    int arr[N];

    printf( "Please enter at least not less than %d numbers (0 - stop): ", N );

    size_t count = 0;

    for (int num; scanf( "%d", &num ) == 1 && num != 0; )
    {
        if (count != N)
        {
            arr[count++] = num;
        }
        else
        {
            memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
            arr[N - 1] = num;
        }
    }

    if (count != 0)
    {
        printf( "The last %zu numbers u entered are: ", count );
        for (size_t i = 0; i < count; i++)
        {
            printf( "%d ", arr[i] );
        }
        putchar( '\n' );
    }
    else
    {
        puts( "There are no entered numbers." );
    }
}

The program output might look like

Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9


Answered By - Vlad from Moscow
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 13, 2022

[FIXED] when i am putting the while loop inside a function why is the answer coming different?

 July 13, 2022     javascript, web-deployment, while-loop     No comments   

Issue

var count = 99;
var word = "bottles";

 
    
   
   {
   
 
  
     while(count>0){
      if(count === 1){
       var word = "bottle";
                           }
         console.log( count + word +" beer on the wall, " + count + word + "  of beer. take one down and pass it around, " );
     count--;
       if(count>0){
      if(count === 1){
        var word = "bottle";
                           }
     console.log( count + word + " beer on the wall.");
                        }
 else{
  if(count<1){
   var word = "bottles";
                   }
  console.log("no more " + word + " of beer on the wall.");
     }
    }
  }

and when i am putting it inside a function the result changes.

var count = 99;
var word = "bottles";

 
    
   
  function myName() {
   
 
  
     while(count>0){
      if(count === 1){
       var word = "bottle";
                           }
         console.log( count + word +" beer on the wall, " + count + word + "  of beer. take one down and pass it around, " );
     count--;
       if(count>0){
      if(count === 1){
        var word = "bottle";
                           }
     console.log( count + word + " beer on the wall.");
                        }
 else{
  if(count<1){
   var word = "bottles";
                   }
  console.log("no more " + word + " of beer on the wall.");
     }
    }
  }
  myName();

can anybody please tell me what is going wrong with putting function against the while loop. you can run the code in the snippet and see the difference of results. also the code looks a lot untidy can anyone suggest me ways to reduce the lines.


Solution

the issue come from the declaration of another word variable inside if

if(count === 1){
    var word = "bottle";
}

when you do this you declare a word variable only available in the if bracket

an idea to enhance your code is to have the two word bottle and bottles inside variables and calculate a true word at begining of while iteration

    var finalWord = (count === 1) ? word : words;

var count = 99;
var words = "bottles";
var word = "bottle";

function myName() {

  while (count > 0) {
    var finalWord = (count === 1) ? word : words;
    console.log(count + finalWord + " beer on the wall, " + count + finalWord + "  of beer. take one down and pass it around, ");
    count--;
    if (count > 0) {
      console.log(count + finalWord + " beer on the wall.");
    } else {
      console.log("no more " + finalWord + " of beer on the wall.");
    }
  }
}
myName();



Answered By - jeremy-denis
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] How to send form data on each page to different email address from database

 July 07, 2022     foreach, mysql, pdo, phpmailer, while-loop     No comments   

Issue

I create a web site like booking where on each page I have two forms. However, if I have just two recipients this forms work very well with AJAX, jQuery, PHP validation, PHPMailer and MySQL, but in second form I have problem, because on each page I need change email recipients which I need get from database using PDO, so I'm try the seguent lines of code, but this send form data to all emails from table owners_email which contain email addresses.

    $sql="SELECT email_address FROM neum.owners_email";
    foreach ($pdo->query($sql) as $row) {
    $mail->AddAddress($row[email_address]);
    } 

However, I understand why, because my sql query it's select all emails but I need to select for each page different email address and again how to use it in INSERT statement, because in table with form data I have referenced to email_address_id from table with email addresses, how you can see bellow:

CREATE TABLE IF NOT EXISTS `neum`.`owners_email` (
  `email_address_id` INT(11) NOT NULL AUTO_INCREMENT,
  `email_address` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  PRIMARY KEY (`email_address_id`))
ENGINE = InnoDB
AUTO_INCREMENT = 3
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'Table with information about email addresses of owners.';


-- -----------------------------------------------------
-- Table `neum`.`form_data`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `neum`.`form_data` (
  `form_data_id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  `tel` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  `from` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  `to` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  `mail` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  `message` TEXT CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL,
  `dateSent` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `email_address_id` INT(11) NOT NULL,
  PRIMARY KEY (`form_data_id`),
  INDEX `fk_form_data_idx` (`email_address_id` ASC),
  CONSTRAINT `fk_form_data`
    FOREIGN KEY (`email_address_id`)
    REFERENCES `neum`.`owners_email` (`email_address_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'Table with information about form data.';

Nevertheless, I'm try on google to find answer for this question, but probably nobody use PHPMailer for send email on each page to different email address, because on every my question google usually show me simple results like how to send mail or how to send multiple mails, but for my question dont exist answer, so if somebody know how to fix it thanks in advance for your help and for your appreciate time.


Solution

PHPMailer doesn't care who you send to – it just uses whatever you pass to addAddress(). If you want to send to different people, you need to figure out how to do get the list of addresses you want to send to, which is entirely independent of later sending them messages. Treat it as two independent tasks:

First task: get a list of addresses. This has nothing to do with PHPMailer.

Second task: send a message to an array of addresses. This has nothing to do with your database.

As it happens, PHPMailer provides an example that combines both of these tasks you should be able to adapt. Just because you're sending to 2 people rather than 10,000 doesn't mean you're not sending to a list, and the same code will work fine.

The only thing missing from your first code snippet is something in your MySQL query to limit who it selects for sending. Adapt it by doing something like:

$sql="SELECT email_address FROM owners_email JOIN form_data ON form_data.email_address_id = owners_email.id WHERE form_data_id = " . $form_data_id;

How you get the right $form_data_id value is up to you, and you might want to consider using a join table so that you can have any number of addresses associated with any number of pages, rather than just a single fixed one.



Answered By - Synchro
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, June 28, 2022

[FIXED] How does a recursive function inside a while loop works in Java?

 June 28, 2022     graph, java, recursion, while-loop     No comments   

Issue

I found this code on google but i couldn't find how does the recursive part actually work. The code is about finding the possible path between 2 vertices on a directed graph. Here is the method to print the total possible path :

public void  total_path(int source, int destination)
{
  result = 0;
  boolean[] visit = new boolean[size];
  for(int i = 0; i < size; i++)
  {
    visit[i] = false;
  }
  count_path(source, destination, visit);
  System.out.println(result);
}

Here is the recursive method to count all possible paths :

  public void  count_path(int start, int end, boolean[] visit)
     {
              if(start > size || end > size || start < 0 || end < 0 || node == null)
              {
                return ;
              }
        
              if(visit[start]==true)
              {
                return;
              }
        
              if(start == end)
              {
                 result = result + 1;
              }
              
              visit[start] = true;
              AjlistNode temp = node[start].next;
        
              while(temp!=null)
              {
                count_path(temp.id, end, visit); 
                temp = temp.next;
              }
              
              visit[start]=false;
     }

Here is the graph which i created :

g.addEdge(0, 1); 
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 5);
g.addEdge(3, 4);
g.addEdge(4, 2);
g.addEdge(4, 5);
g.addEdge(5, 6);

I already compiled and run the program which start point is 0 and end point is 6. The result is 3, already looked up on YouTube about the algorithm but i still can't understand on how to visualize and how does the code flow on the recursion part inside a while loop.


Solution

A recursive function must contain a base case to return a value rather than the result of the recursive call. In this case:

if(start > size || end > size || start < 0 || end < 0 || node == null)
{
    return;
}
    
if(visit[start]==true)
{
    return;
}

are those base cases that will break the recursive call chain. Remember, the method count_path returns void. If the method needed to return some value, you would've seen those if blocks returning some kind of default value. For instance, when you see examples of recursive Fibonacci, the base cases for Fib(0) and Fib(1) return the input value. Otherwise, it returns the result of the (cumulative) recursive call.

What are these base cases?

The method calculate the number of paths to some destination node from the current node. Therefore, if the node was already visited (and thus the paths should've been calculated already) simply return without recalculating. Also, if you have just one node in your graph, or no nodes, then there are no paths (so return without calculation).

Why is the answer 3 paths?

The picture below is based on the calls made to add edges. Each entry is a unidirectional path from a starting node to an ending node. So, starting at Node 0, to get to Node 6, there are three paths and they are outlined in the attached picture.

enter image description here



Answered By - hfontanez
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing