Why is the line 12 is printed twice? - c

Given Problem
Implement the binary search algorithm in a non-recursive manner.
Keep the search array as a numeric array, initialized at time of declaration and keep it global.
The program should ask for a value to search, and then tell the location where it is found.
If the value is not found the program should display not found.
* Additionally the program should display the total number of comparisons done to locate the value ( or realize that the value was not found)
My Solution
#include<stdio.h>
int arr[]={1,3,4,6,8,9,10,15,17,21};
int bi_search(int n)
{
int start=0,end=9,mid=0,count=0;
while(start<=end)
{
count++;
mid=(start+end)/2;
if(n==arr[mid])
{
printf("\nThe total number of comparisons done to locate the value--%d\n",count);
return mid;
}
else if(n<arr[mid])
end=mid-1;
else
start=mid+1;
}
printf("\nThe total number of comparisons done to realize that the value was not found--%d\n",count);
return-1;
}
main()
{
int n=0,ch=0;
do
{
printf("\nEnter the value you want to search for--\n");
scanf("%d",&n);
if(bi_search(n)==-1)
printf("\nSORRY :( !! \nThe value was not found.");
else
printf("\nHurray :) !! \nThe value you entered found at %d position", bi_search(n)+1);
printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
scanf("%d",&ch);
}while(ch==1);
printf("\nThank You\n");
return 0;
}
When I run this code, in function bi_search(int n) whenever arr[mid] becomes equal to n, line The total number of comparisons done to locate the value-- is getting printed twice.

You are calling the bi_search function twice. Once in your if statement, and again in a printf statement. You should call it only once, and cache the value.
main()
{
int n=0,ch=0;
do
{
printf("\nEnter the value you want to search for--\n");
scanf("%d",&n);
if(bi_search(n)==-1) // Calling it here
printf("\nSORRY :( !! \nThe value was not found.");
else
printf("\nHurray :) !! \nThe value you entered found at %d position", bi_search(n)+1); // And here
printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
scanf("%d",&ch);
}while(ch==1);
printf("\nThank You\n");
return 0;
}

It is just because you are calling binary search function twice.
One on if part and other on else if part.
Alternatively you can do the same in following way
int temp = bi_search(n);
if (temp == -1)
printf("Value not found\n");
else
printf("Value found at position %d\n", temp);

Your main routine can look like this:
int main()
{
int n = 0, ch = 0;
do
{
printf("\nEnter the value you want to search for--\n");
scanf("%d", &n);
int res = bi_search(n); // store the result
if (res == -1) // check if not find
printf("\nSORRY :( !! \nThe value was not found.");
else
printf("\nHurray :) !! \nThe value you entered found at %d position", res + 1); // print if find
printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
scanf("%d", &ch);
} while (ch == 1);
printf("\nThank You\n");
return 0;
}
1) int main() (to make compiler calm)
2) int res = bi_search(n) (to avoid second bi_search() call)

Related

C Loop until the condition is met problem

I want to write a loop that runs until the user enters a number greater than 10, but I have to do something wrong because it creates an infinite loop.
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
for(int i=0;a<10;i++){
printf("Enter value>10");
i++;
printf("%d",&a);
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
You mix an index that does not make sense. Also you print the memory address of variable instead of its value, not sure it is what you wanted?
Code partially corrected (because I don't know what is your ultimate goal):
#include <stdio.h>
int main()
{
int a;
do {
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
printf("\na: %d\n",a);
} while (a <= 10);
printf("Result:%d\n",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
ps: \n is line return and added do while which is what you want when you want to execute a loop at least once.
Have a look at your for-loop: you let i start at zero, you continue until a is not smaller than ten anymore, but it's not the value of a you need to check, it's the one of i.
In top of that, you are doing a i++ within your for-loop, while this is already covered in the definition of the for-loop.
I think this is the code that you are looking for: See comments
#include <stdio.h>
int main()
{
int a, ok = 0, end_of_input = 0;
do {
printf("Please input an integer value (min. 10): ");
fflush(stdout); // So the user can see the above line!
switch(scanf("%d",&a)) {
case EOF: // End of input - Give up!
end_of_input = 1;
break;
case 1: // Got a number - Check it!
if (a < 10)
{
ok = 1;
} else {
printf("%d - Not appropriate input. Please try again.\n\n",a);
}
break;
default: // Summat else - "eat" the input to the next line
scanf("%*[^\n]\n"); // "eats" the rest of the line in the buffer w/o assignment
break;
}
} while (end_of_input == 0 || ok == 0);
if (ok) { // User entered a valid number
printf("Got a that is smaller than ten %d\n", d);
} else { // We have ran out of input
printf("See you want to leave us :-(\n");
}
return 0;
}
I am not sure what you are trying to achieve but one problem that I found in your logic is you prompting user for input outside the loop. So whenever you enter number less than 10 it always goes in infinite iteration.
Try following code, with scanf inside loop
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
int i=0;
for(;a<10;){
printf("Enter value>10");
scanf("%d",&a);
printf("%d",a);
i++;
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}

Why does my program not add numbers until -1 is given?

The following code should prompt the user for prices and add that to a total. If the user inputs -1 the adding loop must terminate and the program should print a total and exit. But for some reason this is not happening.
#include <stdio.h>
int main()
{
int price;
int sum;
int exit;
do
{
printf(" Enter a price(-1 to exit)");
scanf("%d", & price);
sum = sum + price++;
printf("the sum of prices is % d ", sum);
}
while (exit != -1);
return 0;
}
Q: Why does my program not add numbers until -1 is given?
You should use if-else statement to resolve it. Like shown below:
while(price != -1)
{
printf(" \nEnter a price(-1 to exit)");
scanf("%d", &price);
if (price == -1)
{
break;
}
else{
sum = sum + price;
printf(" \ntotal sum till now is %d", sum);
}
}
You aren't assigning exit to anything. If you want the user to enter the string -1, the check if price is -1 and break from the loop. If you meant for the user to enter a character with a value of -1, then use fgetc(stdin), and check if the character is -1.
Also, to calculate the sum correctly, you shouldn't be incrementing price with sum = sum + price++;. If this was meant to circumvent the situation where price is -1 and you don't want to subtract from the sum, you should check if exit is -1 inside the loop, and use the break keyword.
It isn't the largest issue, but you should be formatting your code according to conventions (e.g. indenting properly, address-of-operator next to the identifier, etc).
Hello man look now in what is the problem u named a int exit right ?
But you only make exit only int varible and the memory is unfiltered so the computer get a memory from something else and its not a -1 you need to put the %d price in the wile
int price;
do
{
block_of_command
}
While(price!=-1);
Or
int exit;
int price
do
{
scanf("%d",&price);
exit=price;
}
while(exit!=-1);
i updated the code but i dont know how to add all the user inputted prices before exiting. here is my code.
#include<stdio.h>
int main()
{
int price;
int sum = 0;
while(price != -1)
{
printf(" Enter a price(-1 to exit)");
scanf("%d", & price);
if (price == -1)
{
sum = sum + price;
printf(" adds is %d", sum);
break;
}
}
return 0;
}

Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)

Detection of data type through scanf + usage of it in further functions

So I'm relatively new to C and am trying out some beginner programs. One of which is a program that reads user input from stdin (through usage of scanf).
I'm gonna explain everything step by step for sake of easier comprehension of my intentions (although this part of code is functional/operational and does not require any specific help. So if you wish, you may skip straight to the question below)
So we have a program that reads input from scanf() and decides if it's number or string.
#include <stdio.h>
int isNumber(const char *input){
/* while not end of string */
while (*input != '\0'){
/* if we do not detect a number, return 0 */
if (*input < '0' || '9' < *input)
return 0;
input++;
}
return 1;
}
int main(void){
char uInput[30];
/*Ask user for input */
printf("Please enter number or word \n");
scanf("%29s", uInput);
if (isNumber(uInput)){
printf("We found a number %s \n", uInput);
}
else {
printf("We found a word %s \n", uInput);
}
return 0;
}
So yeah, in the program so works so far. Hopefully everything's clear. Now I know this is not the optimal way of the detection, but that's currently not of concern.
Question begins from here:
Now I've decided to spice things up a little, by adding another function.
To be more specific, it's concerning about prime numbers.
So I've began with the function of
int prime(int number){
int divider;
for (divider = 2; divider <= number - 1; divider++){
if (number%divider == 0)
return 0;
else if (number == divider)
return 1;
}
}
Under presumption everything in my function is correct, I decided to initialize the function in my main() function.
Basically what I want to do:
if the user input is a word - print out the word
if the user input is a number - check if the number is prime and then print out the number and whether it's prime.
So here's how I change up the code:
int main (void){
char uInput[30];
int result;
/*User input goes here*/
printf("Please enter a number or a word \n");
scanf("%29s", uInput);
/* if it contains any numbers do */
if(isNumber(uInput)){
result = prime(uInput);
/* now I've created another if condition, if it is a prime number */
if(result == 1){
printf("It is a prime number: %d \n", uInput);
} else {
printf("It is a number: %d \n", uInput);
}
else {
printf("It is a word %s \n", uInput);
}
return 0;
}
Suspicion: Now I'm 99% sure there is an error in this code (and not just a syntax one). I probably even know where it lies, but due to my lack of knowledge I'm not really sure how to fix it.
So as I was doing the function for the prime number, I wasn't certain if I should make it as a result of string or an integer. Issue is, my program runs through the word as a string and even if it is a number, technically it remains a string under 'illusion that it's a number'.
Issue was, I'm not really sure how would I compare a prime number, that's not an integer but a string. So I've changed %s to %d on my printf. I assume there must be some form of conversion, that I'm not aware of.
But was of no succes. Currently, the word detection works, but when I input for example 2, my output results in
"I input 2 into scanf() through console"
It is a number 2686752
Desired result would be
It is a prime number: 2
(Which also means by deduction, it doesn't even use the first if and skips to else, because if it would have been a prime number the printf for it is different. So there may be something wrong with my "prime" function as well.
So issue is, I can't use scanf(%d, uInput) because otherwise the string detection wouldn't work and clearly my solution is not correct either.
Any suggestions?
First there is a problem in your prime function. Check for (number == divider) is incorrect. You can simply remove the else if part as below.
int prime(int number){
int divider;
for (divider = 2; divider <= number - 1; divider++){
if (number%divider == 0)
return 0;
}
return 1;
}
Next issue is in the way you get a number from uInput. You can use atoi for this as below
if(isNumber(uInput)){
result = prime(atoi(uInput));
/* now I've created another if condition, if it is a prime number */
if(result == 1){
printf("It is a prime number: %s \n", uInput);
} else {
printf("It is a number: %s \n", uInput);
}
else {
printf("It is a word %s \n", uInput);
}
Complete code is as below
#include <stdio.h>
#include <stdlib.h>
int isNumber(const char *input){
/* while not end of string */
while (*input != '\0'){
/* if we do not detect a number, return 0 */
if (*input < '0' || '9' < *input)
return 0;
input++;
}
return 1;
}
int prime(int number){
int divider;
for (divider = 2; divider <= number - 1; divider++){
if (number%divider == 0)
return 0;
}
return 1;
}
int main (void){
char uInput[30];
int result;
/*User input goes here*/
printf("Please enter a number or a word \n");
scanf("%29s", uInput);
/* if it contains any numbers do */
if(isNumber(uInput)){
result = prime(atoi(uInput));
/* now I've created another if condition, if it is a prime number */
if(result == 1){
printf("It is a prime number: %s \n", uInput);
} else {
printf("It is a number: %s \n", uInput);
}
}
else {
printf("It is a word %s \n", uInput);
}
return 0;
}
You can convert a string to a number with atoi or strtol.
In your main, after determining the input is a number, convert it to an int and pass that to prime:
...
/* if it contains any numbers do */
if(isNumber(uInput)){
int iInput = atoi(uInput);
result = prime(iInput);
/* now I've created another if condition, if it is a prime number */
...
Then you can either print the number with %d:
printf("It is a prime number: %d \n", iInput); /* note: iInput */
or with %s:
printf("It is a prime number: %s \n", uInput); /* note: uInput */
You will need to first get the line with fgets, and then scan it with sscanf:
char line[80], word[32];
int num;
if (fgets(line, 79, stdin)) {
if (sscanf(line, "%31s", word) == 1)
printf("%s\n", word); // it's a string
else if (sscanf(line, "%d", &num) == 1) // it's a number
printf("%d: %s\n", num, (isprime(num)) ? "Prime" : "Not Prime");
}
char *isprime(int n)
{
int i;
for (i = 2; i < n - 1; ++i)
if (n % i == 0)
return 0;
return 1;
}

error in if condition even i enter code correctly in c programming

#include <stdio.h>
#include <process.h>
int main()
{
int check;
int enter[7];
int i,j;
printf("enter any 7 number to be stored");
for(i = 0; i < 7; i++)
scanf("%d" ,&enter[i]);
printf("\nenter any number to check:");
scanf("%d" ,&check);
for (i = 0; i < 7; i++)
{
if (enter[i]=check)
{
printf("your entry is valid");
exit(0);
}
else if(enter[6]!=check)
{
printf("your entry is not valid");
exit(0);
}
else
continue;
}
return 0;
}
this executes without error but dont work correctly .. always prints out the input is valid.... even i enter the number which is not in array :(
This is assignment, not equality:
if (enter[i]=check)
Change to:
if (enter[i] == check)
Additionally, always check the result of input operations:
if (1 != scanf("%d" ,&enter[i]))
{
/* Handle invalid value. */
}
to ensure subsequent code is operating on variables that have been assigned values.
This line
if (enter[i]=check)
does not do what you expect. You probably meant
if (enter[i]==check)
The assignment is valid C, but instead of checking for equality, it sets enter[i] equal check, and then checks the value of check for being zero. If it is non-zero, the condition succeeds, regardless of the initial value of enter[i]. If the check is zero, then the condition fails, - again, regardless of the initial value of enter[i]. This is a very common mistake; many compilers issue warnings to alert you to the situation.
= is the assignment operator, not equality at all. Doing:
if (enter[i]=check)
enter[i] will take the value check, and then it will check whether enter[i] is nonzero.
if (enter[i] == check)
enter[i]==check)// 2 for compare
proper usage of = is assignment operator whilst == is testing the equality
#include<stdio.h>
#include<process.h>
int main()
{
int check;
int enter[7];
int i,j;
printf("enter any 7 number to be stored");
for(i=0;i<7;i++)
{
scanf("%d" ,&enter[i]);
}
printf("\nenter any number to check:");
scanf("%d" ,&check);
for (i=0;i<7;i++)
{
// printf("\nvalue of i is %d\n" ,i);
if (check==enter[i])
{
printf("your entry is valid");
exit(0);
}
else if(enter[i]!=check && i==6)
{
printf("your entry is not valid");
exit(0);
}
else
continue;
}
return 0;
}
now i got it all right . thanks :)

Resources