Printf between two different for loops not working - c

I am trying to debug using printf. I have inserted it between for loops, but I do not receive the output of it. I am certain that the algorithm is continuing after it and arriving to the end, it's like the reader is ignoring it.
Here's the code :
for (i = 0; i < lower; ++i) {
buf3[i] = (buf[i] + buf2[i] )/2;
printf("\n %d",buf3[i]);
}
printf("hiiiiiiiiiiiiiiiiiiii %d",i);
for (i; i < upper; ++i) {
if (upper == num2) {
buf3[i] += buf2[i]/2;
printf("\n %d",buf3[i]);
}
else {
buf3[i] += buf[i]/2;
printf("\n %d",buf3[i]);
}
}
printf("\n %d",upper);
The "hiiiii..." message is the one not being seen on the screen. (I tried replacing it by many other messages such as int or anything else, but in vain. I also tried to put another printf right above the first for loop, again it returned nothing).
Please note that upper and lower aren't huge numbers.
Thanks in advance.

The printf in question does not print a newline, so the output is buffered until a later printf prints a newline.
Add the newline, and you should see the output:
printf("hiiiiiiiiiiiiiiiiiiii %d\n",i);

Try adding \n after %d.
Also i is not initialised in the second loop

Related

C Program which checks multiple numbers from user input and prints out if they are prime or not

I am a newbie programmer and just started to teach myself C then decided to tackle some simple problems taken from the internet. Specifically with this one: Problem
And my solution is:
#include <stdio.h>
int main(){
int n, i, test = 0;
char s[] = "";
do{
scanf("%d", &n);
if (n <= 1){
break;
}
for(i = 2; i <= n/2; i++){
if(n%i == 0){
test = 1;
break;
}
}
if(test == 0){
**s[] += "%d IS PRIME\n", n;**
}
else{
**s[] += "%d IS NOT PRIME\n", n;**
}
}while(i > 1);
printf("%s", s);
return 0;
}
However, the current problem I have is modifying my program so that it would print out like the expected results (see output from Problem). And for this, I would need to concatenate the results each time into a string variable where it would be printed last, after the user inputs 1 or a number lesser than 1 which would terminate the program. I have decent experience with Java and I have highlighted that part in this program. Basically, what would be the most logical way to write that part as a C command?
Move the print statement into the while loop so it is done each iteration of the loop.
test needs to be reset back to 0 in each loop iteration before doing the test for prime.
In addition the **s[] is not doing what you think it is. Remove it, and change it so that it prints the results at that point:
if(test == 0){
printf("%d is PRIME\n", n);
}
else {
printf("%d is NOT PRIME\n", n);
}

infinite loop in the guessing number program in c

I am fairly new when it comes down to C programmming. That's why i am working my way up by doing some of the easier exercises. The exercise i'm working on is the "guess the number" game, where the user must guess the number that lies between two numbers (upper and lower bounds). The program is doing what it must, with one exception: when the user enters a character instead of an integer, the program gets stuck in an infinite loop. The only way to break out of this loop is by using a break statement and restarting the program. What i want instead, is to have the program request for the users input again, untill an integer is entered.
Can someone tell me why the programm gets stuck in this infinite loop and why it is not requesting for input again trough scnanf like it did in the first iteration? your help will be appreciated. thank you.
//globals
int secret_nr;
int guess;
int upper_bound = 100;
int lower_bound = 1;
int total_guesses = 1;
void check_input(void) {
if (guess < lower_bound || guess > upper_bound) {
printf("Invalid input! Your guess must be between %d and %d\n", lower_bound, upper_bound);
}
else if (guess < secret_nr) {
printf("Higher\n");
total_guesses++;
}
else if (guess > secret_nr) {
printf("Lower\n");
total_guesses++;
}
else if (guess == secret_nr) {
printf("correct! You guessed the number after guessing %d times!\n", total_guesses);
}
}
int main(int argc, char* argv[]) {
srand(time(NULL));
secret_nr = (rand() % upper_bound) + 1;
printf("Guess the number between %d and %d:\n", lower_bound, upper_bound);
do {
if (scanf("%d", &guess)) {
check_input();
}
else {
printf("Invalid input! Only integer values are allowed!\n");
//break;
}
} while (guess != secret_nr);
return 0;
}
If scanf fails to parse its input according to the specified format, then the input will be left in the input buffer for the next call to scanf which will read the very same input and again fail. And so on and on and on...
The simple solution is to first of all read the whole line of input, using e.g. fgets. Then you can use sscanf in that (now extracted) input to attempt to parse it.
Further complicating your current code is the fact that if scanf fails in some other way, it will return EOF which is the integer -1, which is "true". That will of course lead to problems with your logic and looping as well.
I see this reply in another post: https://stackoverflow.com/a/1716066/5687321
scanf consumes only the input that matches the format string, returning the number of characters consumed. Any character that doesn't match the format string causes it to stop scanning and leaves the invalid character still in the buffer. As others said, you still need to flush the invalid character out of the buffer before you proceed. This is a pretty dirty fix, but it will remove the offending characters from the output.
char c = '0';
if (scanf("%d", &number) == 0) {
printf("Err. . .\n");
do {
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
//consume non-numeric chars from buffer
}

C program to find the number of elements in an array after inserting and without counting while inserting

Looking for a C program to count the number of elements in an integer array after inserting and without counting while inserting.Alternatively, what is the integer array substitution for strlen() ?
In this program I need to determine the value of c:
#include <stdio.h>
int main()
{
int a[300],mx=0,c=0,i=0,j;
for(i=0;i<=300;i++)
{
scanf("%d",&a[i]);
if(a[i]=='q') break;
}
c=??;
for(j=0;j<=c;j++)
{
printf("%d\n",a[j]);
if(a[j]>mx) mx=a[j];
}
printf("Max=%d\n",mx);
return 0;
}
From Your input seems that once you get q(113D) input you stop accepting any more input from user.
So need to iterate through array until you found q to get array length.
for(c=0;a[c] != 113;c++)
{
//do nothing
}
//Now you can use c as array length
I guess there is no alternative way like strlen() for what you are doing.
for(i = 0; i < 300; ++i)
{
scanf("%d", &a[i]); /* TODO: check if return value != 1 -> input error */
if (a[i] == 'q')
break;
}
for(j = 0; j < 300 && a[j] != 'q'; ++j)
{
printf("%d\n", a[j]);
if (a[j] > mx)
mx = a[j];
}
As vagish noted, having the input be terminated by 'q' in the way you attempt is pretty strange. The input "113" will map to the ASCII value of 'q', so that input value can't be processed by your program. Furthermore, if somebody actually tried to enter "q" to end the input, I believe the scanf would fail, return 0 and leave a[i] uninitialized, which is definitely not what you want.
You probably want your input to be terminated by EOF instead (ctrl-D if you are typing it into a terminal on most platforms) and you want to check the return code of your call to scanf for input errors and EOF.
I found the answer of my question. Smart vertion of the above program:
include
int main()
{
double a[100000],mx=0;
int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");
for(i=0;i<100000;i++)
{
if((scanf("%lf",&a[i]))==1)
c++;
//else break;
}
for(j=0;j<c;j++)
{
if(a[j]>mx) mx=a[j];
}
printf("You have inserted %d values and the maximum is:%g",c,mx);
return 0;
}

Program gets hung up when I use "delete" function

I'm trying to write a program where it'll take in info from a user, and the user will have options on what to do. The options are to add, modify, delete, display certain info, find the average, and exit.
I have written code for all of them but I can't get my delete function to work.
Here is my code:
void delete_student(struct students *list, int *count) //Delete's Selected student
{
int id4;
int k;
if (*count != 0)
{
printf("\nEnter the ID of the student you wish to delete: ");
scanf("%d\n", &id4);
for (int i = 0; i < *count; i++) //Searches for the selected student
{
k = i;
if (list[i].id == id4)
{
printf("\nStudent found.\nDeleting...\n");
for (int c = k; c < *count; c++) //Deletes the student if found
{
list[c].id = list[c + 1].id;
strcpy(list[c].name, list[c + 1].name);
list[c].age = list[c + 1].age;
strcpy(list[c].dept, list[c + 1].dept);
list[c].grade = list[c + 1].grade;
}
*count = *count - 1;
printf("\nDeletion Complete.\n");
break;
}
else
printf("\nStudent not found. Please try again.\n");
break;
}
}
else
printf("\nNo student's to delete.\n");
}
Edit:
When I go through the program, and I select to use this function, it'll ask me for the "ID" and then it does nothing and has a blinking cursor.
Could someone tell me what I'm doing wrong?
There's more code if you need it.
Is this how the last element would be deleted:
list[*count].id = 0;
strcpy(list[*count].name, NULL);
list[*count].age = 0;
strcpy(list[*count].dept, NULL);
list[*count].grade = 0;
Your scanf() statement has an incorrect format string. You don't need to add the trailing newline; scanf takes care of it. Change that line to scanf("%d", &id4); (no newline) and it should work.
I just wrote a small stub program that compares scanf with and without the newline, and it replicates your error.
You have a break statement at the end of your for loop that probably shouldn't be there. Just delete that one.
else
printf("\nStudent not found. Please try again.\n");
break;
} ^
|
+------ this one
That printf is a bit inaccurate too; it will get printed out on every iteration of the loop where you didn't happen to find a matching ID.
This loop:
for (int c = k; c < *count; c++)
should probably instead be:
for (int c = k; c < *count - 1; c++)
As written, it reads one past the end of the valid array. The results are undefined. And in particular, the strcpy calls may go quite badly. When it gets to the last entry in that loop, list[c+1] refers to an entry that does not exist (based on *count).
Your scanf hangs as it never gets to read your number. No \n needed. Use %d only.

How exactly does space work with scanf?

I am a math student, and I'm learning the very basics in programming in C. I need a program to read an input consisting in an array, the components of which must have certain requisites; I would like the program to ask the user for the components of the array. The user should then have to enter such components separating them with spaces. The details aren't important to get the main question across; I'll choose a simpler example then the one I am dealing with: let's say I want an array with 6 components not to contain the number 4. So I tried:
#include <stdio.h>
int main(void) {
int a[6];
printf("enter components: ");
int i;
for (i = 0; i < 6; i++) {
scanf("%d", &a[i]);
if (a[i] == 4) printf(" \n\n4 is not allowed, try again\n\n");
}
for (i = 0; i < 6; i++) {
printf("%d ", a[i]);
}
}
If I compile this and run it, and for example enter:
1 2 3 4 5 6
I will get my error message, but only after having pressed enter, that is after having entered all six components (not straight after having pressed space for the fourth time). So here are my questions (I am looking for solutions which don't make use of strings or pointers, unless it is impossible to do without them):
Is there a way to get the program to read a component (and to act accordingly) straight after its subsequent space has been entered? I'm guessing there isn't because scanf only works after the user presses enter, and not space, correct?
If there isn't, is there a way to get the program to read the components all at once after having pressed enter at the end, but letting the user pick up from the last right component? For example, with the above input, I would like the program to display something like this:
4 is not allowed
1 2 3 _
so that the user can correct his/her input (possibly changing the first three digits as well).
Sorry if this question is too dumb! Thank you for your help!!
EDIT: Well, thanks for the great answers, you have all been very helpful! It's a pity I can't accept more than one.
In for loop, after each iteration, the counter add by one automatically. If you get an invalid input, you should prevent the counter increasing. To do this, just add i--; to your code when you give an invalid input.
#include <stdio.h>
int main(void) {
int a[6];
printf("enter components: ");
int i;
for (i = 0; i < 6; i++) {
scanf("%d", &a[i]);
if (a[i] == 4){
printf(" \n\n4 is not allowed, try again\n\n");
i--;
}
}
for (i = 0; i < 6; i++) {
printf("%d ", a[i]);
}
}
Please see the bellow code:
#include <stdio.h>
int main(void) {
int a[6];
int i;
bool hasError = false;
int errorIndex = 0;
do{
hasError = false;
printf("enter components: ");
for (i = 0; i < errorIndex; i++)
printf("%d ", a[i]);
for (i = errorIndex; i < 6; i++) {
scanf("%d", &a[i]);
if (a[i] == 4 && hasError == false){
printf(" \n\n4 is not allowed, try again\n\n");
hasError = true;
errorIndex = i;
}
}
}while(hasError == true);
for (i = 0; i < 6; i++) {
printf("%d ", a[i]);
}
}
This is related to your terminal being in "cooked" mode. Characters aren't even sent to the program until the user presses enter.
You could do something like this:
int i,a[6];
for (int i=0;i<6;i++) {
scan: scanf("%d",&a[i]);
}
for (int i=0;i<6;i++) if (a[i]==4) {
printf("4 is not allowed. re-enter the last %d numbers\n",6-i);
goto scan;
}
note that in most case, it's better to avoid using goto, but in this case I think that it's natural.
If you really want, you can print the first i numbers (before the goto), but it's complicated (and platform-depended) to let the user change those numbers.
Improving on Mir Milad Hosseiny answer (I wrongly identified it as being an out of control infinite loop... it's actually exactly the infinite loop I describe in my comment)...
I would write a small function that has either a "white list" (things you want) or a "black list" things you don't want, and check each value to either belong or not (depending on the approach) to the list. That way you can keep a separate place where your store the values that you are willing to accept or the values you are not, so your primary function doesn't get really messy with exceptions or inclusions in the "if"
so your code would be
if(isAllowed(a[i]){
myList[j] = a[i]; //j is your alternate counter
}

Resources