Loop Limit in C/C++ - c

Is there a limit to how many times a loop can run in C?
void main()
{
int T,N,x,X,i;
x=0;
scanf("%d",&T);
while(T>0)
{
T--;
scanf("%d",&N);
X=0;
while(N>0)
{
N--;
scanf("%d",&x);
if(x>X){X=x;}
}
printf("Case: %d",x);
}
}
T has a range of 0-250, and N has a range of 0-1000. x has a range of 0-10,000.
Whenever the N exceeds something above 800, my console stops taking input.
Can this be due to a limit on the input buffer?

There is no limit to how many times a loop may loop. There are limits to the max and minimum values of an int, and those may play into your loop. In this case, 800 should be fine, so there is something else going on here.
Edit: Works for me... the only weird thing I see is that you reset X inside the innermost loop, so the output is always the last integer entered if it's >0, or 0.

Are you piping input to this program? There may be some buffering limitation with that. Try putting the data in a file and read from the file.

It's common practice to loop 10,000 times or (much) more to compare the performance of two small calculations.
If there was a limit, there wouldn't be such as thing as an infinite loop. ;)

Because the comments have gone irreverent on you, I will make this a community wiki and commence with an interrogative-like suggestion that belongs in comments:
Check the return values from all scanf calls. Do this first to determine whether the standard library API is already transmitting information to you -- via "electrostatic transmission", otherwise known as the contents of register eax after you call scanf on x86 architecture. Do not let the light in that register die unobserved. Take the register's electrical charges (bits) into a variable and compare them to both zero (0) and EOF. Those alien transmission were sent to you from the year 1976, when scanf was first written to return an informative numerical value to the caller.
As tomlogic pointed out in comments to an answer, if you are pasting the data, you should instead try using the technique known as "input redirection" or "piping." First, get your data into a file, let's say name filename.dat. Then, issue a command such as the following:
executable-name < filename.dat
Where executable-name is the file you are generating with the C compiler. Technically, the above syntax creates an "input redirection" or "stdin redirection" -- the shell opens the file for read access as file descriptor zero (0), also know as stdin. The child program as spawned from the shell will scanf from the file, rather than the terminal (your paste buffer).
Another approach is to create a "pipe indirection" in which the shell opens another process's output for reading and passes this to the child, again as stdin file descriptor. In this case, the shell probably uses popen rather than open. The syntax for this might be:
cat filename.dat | executable-name as if on a Unix-clone, or
type filename.dat | executable-name if in the context of an IBM® PC-DOS® clone.

Related

my do, while loop not working as i meant :( ( C language)

hi guys Im about to finish some c basics course and am ending it with a full calculator project.
at arrays part my following do while loop keeps looping over and over cant break the condition.
I tried to add exit();
also changed return(0) to return(EOF) but nothing happens.
this is the code:
#include <stdio.h>
int main()
{
int row_num,colm_num;
do
{
printf("PLEASE! choose Array 'A' Rank (maximum 4x4)==>\n\n");
printf(" 'A' rows= ");
scanf("%i", &row_num);
printf(" 'A' columns= ");
scanf("%i", &colm_num);
printf("Array 'A' set to rank = %ix%i i.e. (A[%i][%i]) \n\n)",row_num,colm_num,row_num,colm_num);
}
while(( scanf("%i", &row_num)==1 || row_num<=4||row_num>=0)||( scanf("%i", &colm_num)==1 || row_num<=4||row_num>=0)); //restriction for user input
return(0);}
I have to mention that this is not the full code but I run this in separate file to debug each section alone btw if there is better way to debug sections of the code than starting another c file tell me "am using codelite editor IDE" thanks all also am open for any beginners\efficient c coding advices I would be grateful ^^.
Your scanf condition (scanf("%i", &row_num)==1) doesn't do quite what you expect it to do. From the scanf manpage:
RETURN VALUE
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in the
event of an early matching failure.
You have one input item being matched, so scanf always returns 1 as long as the input was numeric, and you never can exit the loop because the condition remains true.
Call scanf to read row_num and col_num before the end of the loop body (checking the return value to signal an error to the user) and then directly check the value of those two variables in the condition.
Alternatively, you could use && instead to verify that scanf did indeed read one value, and check the value in the same condition, but this arguably creates an overly messy and hard-to-read condition.
I run this in separate file to debug each section alone btw if there is better way to debug sections of the code than starting another c file
The best option is to create separate functions, which you can call and test individually from main as you test. Once your code matures, you can put all the functions together, and continue to test and debug using tools such as your debugger.

for loop brackets in c

I write a program to print integer values using for loop and after printing, the program should wait one second, after that those integers are overwrite with double space character in other words the purpose of the program is to erase those integer after wait for one second.
This the program:
#include <stdio.h>
#include <time.h>
int main (void) {
int i;
for(i=1;i<=5;i++){
printf("%d ",i);
}
for(;clock () < CLOCKS_PER_SEC;){} /*wait for one second*/
printf("\r"); /*move to the beginning of the line*/
for(i=1;i<=5;i++){
printf(" "); /*overwriting the integers*/
}
printf("\n");
return 0;
}
The problem is in the wait loop loop brackets `for(;clock () < CLOCKS_PER_SEC;){}' when i
remove those brackets the program work properly. but if the for loop with brackets. the program doesn't work,I mean the program still runs but it overwrite the integer instead of showing those integers first.
please someone explain what happen?
When you remove the brackets, the printf("\r") statement becomes the body of the for loop, logically equivalent to this:
for(;clock () < CLOCKS_PER_SEC;) {printf("\r");}
So the integers get overwritten right away instead of after the end of the delay period.
Of course, the real question is why you are using a busy-loop for a delay rather than just calling sleep(1), which is much more efficient (i.e. it won't pin your CPU at 100% during the delay period)
You aren't flushing stdout (the stream that printf writes to) yourself so it doesn't happen until the '\r' is written, and then you immediately clear it.
If you remove the {}, then your loop is equivalent to
for(;clock () < CLOCKS_PER_SEC;)
printf("\r");
which writes a bunch of \r, the first of which flushes the output and the rest of which are redundant. After the loop completes, you clear the line, working as you want it to.
You should call fflush(stdout) after printing the numbers. Or you could move the printf("\r") so it comes before the wait loop (the difference being where the cursor ends up).
Your loop is problematic, as there's no guarantee that clock() starts at 0, and it won't on many systems, and you shouldn't spin like that ... it slows down other programs running on your system. You could just use sleep(1), although it's not very accurate.
I suspect somehow the output buffer is being flushed differently between the two cases. You could check this by manually flushing the buffer using fflush(stdout) before the problematic loop.
Also note that the {} aren't mandatory in C, for single-line statements within the loop.
Here is the code you might want:
#include <stdio.h>
int main(int argc, char * argv[]) {
int seconds = 10;
while(seconds>0) {
printf("%10d", --seconds);
fflush(stdout);
sleep(1);
printf("\r");
}
printf("%10s\n", "time up!");
return 0;
}
(Since you ask about what fflush() acturally is, here is a little explanation base on my understanding)
It's all about io cache, 1 reason cache exists is: read/write memory could be over 1000 times quicker than hard disk.
So program should try do reduce the frequence of read/write hard disk, and use memory instead, but need a proper tradeoff for the user experience and io delay.
e.g
When read a file by lines, it could read 2kb or so at once instead a single line, then could read from the memory cache,
When write to console, the program might choose to write to the memory cache until meet a \n or \t char, and some other case.
fflush(FILE * file), is a function from stdio.h, it flush the cache of specified FILE. In your case, the file is stdout(standard output), which print to your console. When you use printf() to print a single number, it might write to cache of stdout, so you didn't see it in console, but calling fflush(stdout) flush out the cache to your console.
On the first 'for' loop you are printing values using printf. Here 'printf' uses 'stdout' which is a buffered output- meaning output will not be printed unless '\n' is provided or buffer full. so you can either uses flush(stdout) after the first loop or uses fprintf(stderr, "") to print to standard error which is not a buffered output.

Why does printf return a value?

I know that printf returns a negative error or number of characters printed on success. Only reason to check this return value is if the execution of program somehow depends on the printf status. But I could not think of a scenario where this return value is useful. I, for one, have never checked the return value of printf function.
What are the scenarios where return status from printf is useful?
There are at least 2 uses of the return value of printf:
To check for errors. This is rarely important when your output is interactive or purely informative, but for programs that are processing text from stdio or a file and writing the result to stdout, it's important to know whether an error (such as disk full, closed pipe, or dropped network connection) prevented the entire output from being written. This is especially important if the source file will be deleted/replaced by the output once the output is complete. However, due to buffering, checking the result of printf itself is usually not helpful. You'll want to check ferror(stdout) after writing the last output and flushing in order to get a reliable indication of whether any write errors occurred. On the other hand, checking the return value of printf allows you to detect failure early so you don't waste time attempting to write millions of lines when the first line already failed, so it can be a very useful check; it's just not a sufficient check by itself.
If the number of characters output is not obvious, you may want to know how many characters were written. A naive usage of this number would be for lining up columns, but assuming characters have fixed width in their visual presentation is rather antiquated. It might make sense if you were formatting source code, though. Another similar usage (not sure whether this is less or more antiquated) is writing fixed-width fields in a file. For example, if your fields are 80 bytes and printf returned 52, you'd want to write 28 more padding bytes to finish off the field.
There are a couple of situations in which you might want to check the return value of printf. One is to check for errors, as you mention; while there's usually nothing you can do if there's an error on printf, you may, if you're printing something really big, and get an error, decide to try printing it in smaller chunks.
You may also be interested in how wide the output was; printf() returns the number of characters written on success. If you are trying to line up output, and you do a printf() with something of variable width, you can check the return value to find out how many characters were printed, so you know what column you are on. Of course, this only works if all of your characters are 1 column wide (which is true of most ASCII characters), but there are some cases in which this might be useful.
snprintf() prints to a fixed-size buffer instead of stdout or a file. It will only print up to the size of the buffer that you give it; but it's possible that it would require more space to print the full string. It returns the amount of space it would have needed to print the full string; this way, you can use the return value to allocate a new buffer of the appropriate size, and try again, if your original buffer was too small. You almost always use the return value of snprintf(), for this reason.
One of the main reasons why this is used is for troubleshooting. Printf can be used to also write to a file (not only STDOUT). Ensuring that all the charachters have been writen to the file is crucial in some applications. An example of this can be found below:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
printf("This will display on the screen.\n");
if((fp=freopen("OUT", "w" ,stdout))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
if( printf("This will be written to the file OUT.") < 0){
return -1;
}
fclose(fp);
return 0;
}
You might ask why you should use printf to print a file. Consider this. Some software was developed that had no error logging implemented but instead used printf. A knowledgeable C programmer can redirect the output of printf to a file at the top of the code and thus implement error logging to a file instead of STDOUT. At this point he can use the return value of printf to ensure that the these errors were printed correctly.
It is mostly for the purposes of error checking. You can make sure that the operation was successful or not using the return value.
If a non-negative value is returned (indicating the number of characters written) it means the operation was successful. If a negative number is returned there was some error.
For example,
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int result = printf("This is a test!");
if (result > 0)
{
printf("%d characters were written!", result);
return EXIT_SUCCESS;
}
else return EXIT_FAILURE;
}
I, too have never used the return value.
But beside the error check, you might count the number of characters which have been output, to make some sort of statistic, or limitation
in some cases, printf is only able to put a part of your string into stdout, and this is not an error.
if you have to be sure that your string is sended complete, you could use the return value to see this.
its mos useful when working with fprintf and sockets, etc. but still could be useful.

Please Explain this Example C Code

This code comes from K&R. I have read it several times, but it still seems to escape my grasp.
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return(bufp>0)?buf[--bufp]:getchar();
}
int ungetch(int c)
{
if(bufp>=BUFSIZE)
printf("too many characters");
else buf[bufp++]=c;
}
The purpose of these two functions, so K&R says, is to prevent a program from reading too much input. i.e. without this code a function might not be able to determine it has read enough data without first reading too much. But I don't understand how it works.
For example, consider getch().
As far as I can see this is the steps it takes:
check if bufp is greater than 0.
if so then return the char value of buf[--bufp].
else return getchar().
I would like to ask a more specific question, but I literally dont know how this code achieves what it is intended to achieve, so my question is: What is (a) the purpose and (b) the reasoning of this code?
Thanks in advance.
NOTE: For any K&R fans, this code can be found on page 79 (depending on your edition, I suppose)
(a) The purpose of this code is to be able to read a character and then "un-read" it if it turns out you accidentally read a character too many (with a max. of 100 characters to be "un-read"). This is useful in parsers with lookahead.
(b) getch reads from buf if it has contents, indicated by bufp>0. If buf is empty, it calls getchar. Note that it uses buf as a stack: it reads it from right-to-left.
ungetch pushes a character onto the stack buf after doing a check to see if the stack isn't full.
The code is not really for "reading too much input", instead is it so you can put back characters already read.
For example, you read one character with getch, see if it is a letter, put it back with ungetch and read all letters in a loop. This is a way of predicting what the next character will be.
This block of code is intended for use by programs that make decisions based on what they read from the stream. Sometimes such programs need to look at a few character from the stream without actually consuming the input. For example, if your input looks like abcde12xy789 and you must split it into abcde, 12, xy, 789 (i.e. separate groups of consecutive letters from groups of consecutive digits) you do not know that you have reached the end of a group of letters until you see a digit. However, you do not want to consume that digit at the time you see it: all you need is to know that the group of letters is ending; you need a way to "put back" that digit. An ungetch comes in handy in this situation: once you see a digit after a group of letters, you put the digit back by calling ungetch. Your next iteration will pick that digit back up through the same getch mechanism, sparing you the need to preserve the character that you read but did not consume.
1. The other idea also shown here can be also called as a very primitive I/O stack mangement system and gives the implementation of the function getch() and ungetch().
2. To go a step further , suppose you want to design an Operating System , how can you handle the memory which stores all the keystrokes?
This is solved by the above code snippet.An extension of this concept is used in file handling , especially in editing files .In that case instead of using getchar() which is used to take input from Standard input , a file is used as a source of input.
I have a problem with code given in question. Using buffer (in form of stack) in this code is not correct as when getting more than one extra inputs and pushing into stack will have undesired effect in latter processing (getting input from buffer).
This is because when latter processing (getting input) going on ,this buffer (stack) will give extra input in reverse order (means last extra input given first).
Because of LIFO (Last in first out ) property of stack , the buffer in this code must be quene as it will work better in case of more than one extra input.
This mistake in code confused me and finally this buffer must be quene as shown below.
#define BUFSIZE 100
char buf[BUFSIZE];
int bufr = 0;
int buff = 0;
int getch(void)
{
if (bufr ==BUFSIZE)
bufr=0;
return(bufr>=0)?buf[bufr++]:getchar();
}
int ungetch(int c)
{
if(buff>=BUFSIZE && bufr == 0)
printf("too many characters");
else if(buff ==BUFSIZE)
buff=0;
if(buff<=BUFSIZE)
buf[buff++]=c;
}

Reading and comparing numbers from txt file C

I am new to C programming, so I am having difficulties with the problem below.
I have a text file inp.txt which contains information like the following:
400;499;FIRST;
500;599;SECOND;
670;679;THIRD;
I need to type a number and my program needs to compare it with numbers from the inp.txt file.
For example, if I type 450, it's between 400 and 499, so I need write to the word FIRST to the file out.txt
I have no idea how to convert a character array to an int.
I think you'll want these general steps in your program (but I'll leave it to you to figure out how you want to do it exactly)
Load each of the ranges and the text "FIRST", "SECOND", etc. from the file inp.txt, into an array, or several arrays, or similar. As I said in the comment above, fscanf might be handy. This page describes how to use it - the page is about C++, but using it in C should be the same http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/. Roughly speaking, the idea is that you give fscanf a format specifier for what you want to extract from a line in a file, and it puts the bits it finds into the variables you specify)
Prompt the user to enter a number.
Look through the array(s) to work out which range the number fits into, and therefore which text to output
Edit: I'll put some more detail in, as asker requested. This is still a kind of skeleton to give you some ideas.
Use the fopen function, something like this (declare a pointer FILE* input_file):
input_file = fopen("c:\\test\\inp.txt", "r") /* "r" opens inp.txt for reading */
Then, it's good to check that the file was successfully opened, by checking if input_file == NULL.
Then use fscanf to read details from one line of the file. Loop through the lines of the file until you've read the whole thing. You give fscanf pointers to the variables you want it to put the information from each line of the file into. (It's a bit like a printf formatting specifier in reverse).
So, you could declare int range_start, range_end, and char range_name[20]. (To make things simple, let's assume that all the words are at most 20 characters long. This might not be a good plan in the long-run though).
while (!feof(input_file)) { /* check for end-of-file */
if(fscanf(input_file, "%d;%d;%s", &range_start, &range_end, range_name) != 3) {
break; /* Something weird happened on this line, so let's give up */
else {
printf("I got the following numbers: %d, %d, %s\n", range_start, range_end, range_name);
}
}
Hopefully that gives you a few ideas. I've tried running this code and it did seem to work. However, worth saying that fscanf has some drawbacks (see e.g. http://mrx.net/c/readfunctions.html), so another approach is to use fgets to get each line (the advantage of fgets is that you get to specify a maximum number of characters to read, so there's no danger of overrunning a string buffer length) and then sscanf to read from the string into your integer variables. I haven't tried this way though.

Resources