Diffrence Between The Following Codes - c

The Following two Codes Yield the same output but has some diffrence which i couldn't figure out
1.
#include<stdio.h>
int main(void)
{
int a=1;
while(a>0)
{
scanf("%d",&a);
if(a != 42)
printf("%d\n",a);
else
break;
}
}
2
#include <stdio.h>
int main(void) {
int x;
for(; scanf("%d",&x) > 0 && x != 42; printf("%d\n", x));
return 0;
}

The working is different because the semantics are different because the code is different.
If you would want to rewrite the 2nd part to the 1st, you would get
#include <stdio.h>
int main(void) {
int x;
while (scanf("%d",&x) > 0 && x != 42) {
printf("%d\n", x);
}
return 0;
}
or
int main(void) {
int a;
while (scanf("%d",&a) > 0) {
if (x != 42) {
printf("%d\n", x);
} else {
break;
}
}
return 0;
}
Do you see the difference? On the one, you base your decision on the variable being scanned (x or a) and on the other on the return value of scanf(), which is simply the number of values read:
while(a>0)
vs.
while (scanf("%d",&a) > 0)

In the first case it's simple looping structure.
In the second case. The For Loop arguements like initialization of looping variable, condition and incrementation/decremenation are always options.
here For loop initialization is omitted, the condition scanf("%d",&x) will return no of values properly read from console, in case if you give any random character as input scanf return 0 and the condition x!= 42 is obvious. printf in the incremation/decrematation place just prints.
Only when the condition fails the loop terminates.

Related

How to stop infinite looping the output?

I have code with a function that returns the biggest digit from a number. The requirement is to enter numbers until something that is not a number is entered. When something that isn't a number is entered, the program is supposed to stop, but in my case it just starts an infinite loop that prints the last result that the function returned. Here is the code:
#include <stdio.h>
int maxDigit(int n){
int temp = n, maxDig = 0;
while(temp){
int digit = temp % 10;
if(digit > maxDig){
maxDig = digit;
}
temp /= 10;
}
return maxDig;
}
int main()
{
int n = 1, broj;
while(n){
if(scanf("%d", &broj));
printf("%d\n", maxDigit(broj));
}
return 0;
}
What might be the problem?
You can look at the return value of scanf to see if you read a valid integer, and you can use break to terminate your loop. The n variable in your main function just had a constant value so I got rid of it, and cleaned up the function in a few other ways. Here is my resulting code:
...
int main() {
while (1) {
int input;
if (scanf("%d", &input) != 1) { break; }
printf("%d\n", maxDigit(input));
}
}

How to create a function in C that prompts the user for positive integers only and call it in the main function?

This is my code. I failed to use the break keyword after the printf function in order to break out of the loop. When I enter a negative number or zero, it doesn't prompt me again to re-enter.
#include <stdio.h>
#include <cs50.h>
int get_positive_int(void);
int main (void)
{
get_positive_int();
}
int get_positive_int(void)
{
int i;
i = get_int("Integer: ");
while (true)
{
if (i<1)
{
return i;
}
else
{
printf("%i", i);
}
}
}
The algorithm in the function get_positive_int() is wrong:
You need to place i = get_int("Integer: "); inside of the while loop.
Your if condition:
if (i < 1)
is wrong as that would return i if i is a negative integer or 0. If you want to return i when i is a positive integer or 0 you should use if(i >= 0).
Note that you can also place:
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
after the call to maintain the occurrence of a read error. But if you want to only return INT_MAX then, you do not need to do so and can omit it since this would fit to the conditional statement ``if(i >= 0)` and its body.
The code is then:
int get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i == INT_MAX)
{
// optional error handling.
return INT_MAX;
}
else if (i >= 0)
{
return i;
}
printf("%i", i);
}
}
Side note: If you donĀ“t want to count 0 as positive integer, you need to have i >= 1 as the condition of the if statement.
As you said in the comments you only want to continue if i is a positive integer and exit if i is a negative characters or 0:
void get_positive_int(void)
{
int i;
while (true)
{
i = get_int("Integer: ");
if (i < 1)
{
return;
}
printf("%i\n", i);
}
}
Note that in this case, the return type of get_positive_int shall be void instead of int and it should omit to return i as it is not necessary to return any value from the function.

How to most effectively combine functions including checkprime

#include <stdio.h>
#include <string.h>
#include <math.h>
#define FALSE 0
#define TRUE 1
......................
int checkprime ( char number )
{
int i, valid;
valid = TRUE;
for ( i = 2; i <= number; i++ )
{
if ( number % i == 0 ) valid = FALSE;
}
return valid;
}
int main(void)
{
char inputarray[4];
int c, primeanswer;
........................
{
primeanswer = checkprime(c);
if ( primeanswer == 1)
{
printf("%d", "is a prime", inputarray);
}
else
{
printf("%d", "not prime", inputarray);
}
}
}
My issue here is trying to get the checkprime function working. I think I'm probably not initialising something as the numbers I'm getting seem to me like the program output isn't correct. Also when I do enter data for checkprime the numbers to me seem like uninitialised int values. And that the other functions don't seem to be called.
What is it that I am not initialising?
How can I combine the checkprime function more effectively with the others? Is it necessary to switch between char/int values as I've done in the functions?
EDIT:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
................
}
int checkprime ( int number )
{
int i, valid;
valid = TRUE;
for ( i = 2; i < number; i++ )
{
if ( number % i == 0 ) valid = FALSE;
}
return valid;
}
int main(void)
{
char inputarray[4];
int c, primeanswer;
.........................
else
{
c = atoi(inputarray);
primeanswer = checkprime(c);
if ( primeanswer == 1)
{
printf("%d", "is a prime", inputarray);
}
else
{
printf("%d", "not prime", inputarray);
}
}
}
You're passing c to checkprime, but you never set it to anything. As a result, the contents of c are undefined and trying to read it results in undefined behavior.
Pass your array to the atoi function to convert it to an integer and assign it to c. You should also change the type of the number parameter in checkprime to int to match what is being passed in.
It also looks like you're missing an else:
if ( !checknumeric(inputarray))
{
printf("Invalid input");
}
// else goes here
{
primeanswer = checkprime(c);
...
EDIT:
More issues with your code:
You're not printing the results correctly:
printf("%d", "is a prime", inputarray);
...
printf("%d", "not prime", inputarray);
There are two issues with these. First, the fixed portion of the string to print is the first parameter to printf. The rest get substituted in. So the first two parameters should be combined into a single string. Second, you use %d to print at int but inputarray is a char array. You should instead pass in c, which is the integer value you want to print.
printf("%d is a prime", c);
...
printf("%d not prime", c);
dbush's answer is correct, but you're still going to get the result that you're already seeing, because you have a bug in your checkprime method:
int checkprime ( char number )
{
int i, valid;
valid = TRUE;
for (i = 2; i <= number; i++) {
if (number % i == 0) valid = FALSE;
}
return valid;
}
Your problem is that number % number == 0 for all values of number, and you let i iterate up to number by using <= in your for-loop condition. Changing your for loop to:
for (i = 2; i < number; i++) {
if (number % i == 0) valid = FALSE;
}
Will fix the logic there.

C making a Function Return 1 when user input is 0-9 ASCII

The problem I have been given to solve is as follows:
-Write a function named "is_digit" that accepts a char as input, and returns an integer value of 1 if the parameter input is an ASCII digit between 0 and 9 inclusive. Otherwise the function must return a value of 0.
-In the main function, call is_digit, and pass in an argument based upon user input. The main function must then output the result from calling is_digit.
This is what i have so far
#include <stdio.h>
char is_digit(int x)
{
if (x > '48' && x < '57') //The ascII range between 0-9 (i think...)
{
return 1;
}
else
//Whatever the user input is it always runs the else
{
return 0;
//Is this what the question means by "function must return a value of 0"
}
}
int main()
{
char x;
printf("input: ");
scanf("%c", &x);
is_digit(x);
}
Why is my program not returning 1 if my user input is 0-9??
Updated version with comments taken into consideration:
#include <stdio.h>
char is_digit(char x)
{
if (x >= 48 && x <= 57)
{
printf("1");
return 1;
}
else
{
printf("0");
return 0;
}
}
int main()
{
char x;
printf("input: ");
scanf("%c", &x);
is_digit(x);
}
Try this:
Also to note use 'unsigned char x' in your main this basically means positive values 0-255
#include <stdio.h>
int is_digit(int x)
{
if (x >= 48 && x <= 57)
{
return 1;
}
return 0;
}
It would be better to change your method to return an int and not char.
Remove the single quotes because you are comparing the number values of the ASCII characters (int)
Also use the '<=' and '>=' signs because the question said inclusive. '<' and '>' is exclusive.
You don't need a else block since the answer is immediately returned if it is a number.
"//Is this what the question means by "function must return a value of 0"?"
Yes, that's what it means.
You could do a direct comparison:
int is_digit(char x)
{
int result;
if (x >= '0' && x <= '9')
{
result = 1;
}
else
{
result = 0;
}
return result;
}
Your mistake is with
if (x > '48' && x < '57') //The ascII range between 0-9 (i think...)
It should be
if (x > 47 && x < 58) //The ascII range between 0-9 (i think...)
The corrected code is shown below
#include <stdio.h>
int is_digit(char x)
{
if (x > 47 && x < 58) //The ascII range between 0-9 (i think...)
{
return 1;
}
else
//Whatever the user input is it always runs the else
{
return 0;
//Is this what the question means by "function must return a value of 0"
}
}
int main()
{
char x;
printf("input: ");
scanf("%c", &x);
printf("result is: %d",is_digit(x));
return 0;
}
A return statement in programming is a proof of what the computer did. In c and c++, returning 0 in main means your program ended correctly, without crashing but not necessarily that you code is wrong or right.
Your return type is char,
try this:
int is_digit(int x)
In short: because you're not telling it to. The final line should be:
return is_digit(x);
Without the return, the result from is_digit() is simply being thrown away...

C run time error (Program supposed to print first 1000 prime numbers)

I have used the isPrime() function in other programs and it works perfectly, I have even referenced it in the same way before. For some reason in this program the function isn't working. I used printf() to check what the function was returning and it seems to be memory locations. I don't know what to change though because, as I said, I am sure the function works.
#include <stdio.h>
int main(void){
int isPrime(int a);
int result;
int x = 1;
while(x <= 1000){
result = isPrime(x);
if (result == 1){
printf("%d\n",x);
}
x++;
}
}
int isPrime(int a){
int count;
int z;
if(a == 1){
return 0;
} else {
for (z = a; z != 0; z-- ){
if(a % z == 0){
count++;
}
}
if(count <= 2){
return 1;
} else {
return 0;
}
}
}
Initialize count to 0.
Apart from this, on my system it works fine.
Move int isPrime(int a); out of the main() function, up above it. Or put it into a separate header file. Review function prototypes when you have time.
The count variable, in your program is a local variable, and hence like all local variables should be initialized before use or it uses a leftover value from the stack, and with such an unpredictable and random value , your program behavior is undefined.

Resources