Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Am a beginner at C here; Would like to ask which of the following 2 code is better for printing odd integers between 1 and given number?
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i+=2)
printf("%d ", i);
printf("\n");
}
// Precond: n > 0
void print_odd_integers(int n) {
int i;
for (i=1; i<=n; i++)
if (i%2 != 0)
printf("%d ", i);
printf("\n");
}
If neither can be said to be clearly "better", what are the different trade-offs between the versions?
Use the First Loop if n is not the extreme case like INT_MAX and also when i starts from an odd integer, Since it already skips half the number iterations.
Else use the Second Loop because the first will become infinite loop if n = INT_MAX.
Absolutely the first one.
Reasons:
- less lines of code
- branching statements (if, if else, switch cases, ...) are mainly avoided if there is other ways of handling the situation.
- time complexity of both algorithms are the same O(n). So this is mainly a matter of which code is more beatifull. And always remember, a code that is more readable is prettier.
EDIT
the fact that on the edge the first solution has undefined behavior is obvious. but these input validations must be checked outside the algorithm part. and it's much recommended that you DO NOT mix validation codes with your logic. easily you can check for i at first of the function and print INT_MAX if i==INT_MAX-1 or i==INT_MAX
Functionally, they are the same, so it really doesn't matter all that much unless you really need max performance.
However, the solution where you skip the if statement would be a lot efficient. You're skipping half the numbers and don't need to check a condition with modulus.
Both loops have undefined behavior if n == INT_MAX because of arithmetic overflow.
The first loop will potentially give you better performance
The second loop is potentially more readable (for a beginner) and less error prone if you later change the code to start from an arbitrary value.
I would use braces around the for body as it is not a simple one line statement and spaces around binary operators to improve readability:
void print_odd_integers(int n) {
int i;
for (i = 1; i <= n; i++) {
if (i % 2 != 0)
printf("%d ", i);
}
printf("\n");
}
Note also that both loops will output a space after the last number before the newline, which may be incorrect.
You can address both issues with one extra test:
void print_odd_integers(int n) {
for (int i = 1; i <= n; i += 2) {
printf("%d", i);
if (i == n)
break;
}
printf("\n");
}
The second solution is the "professional" way.
One thing you could change would be the Layout:
void print_odd_integers(int n)
{
int i;
for (i=1; i<=n; i++)
{
if (i%2 != 0)
{
printf("%d\n", i);
}
}
printf("End.\n");
system("Pause"); //So you can see what you did :)
}
Have fun :)!
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Now im having problems with the new code in terms of compiling. I have two great answers but chux's answer is addressed to rectify my code . So by his/her directions my new code is:
#include <math.h>
#include <conio.h>
int main()
{
int n,i,r;
printf("Enter A Number to know its prime or non prime");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
{r==1;
break;
}
}
if(r==1)
printf("%d is a non-prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
But on the output it show as 87 is a prime number. I don't know why. But can someone spot my mistake?
At few problems
Assignment vs. compare
if (r=1) assigns 1 to r, so if (r=1) is always true. Certainly a compare was needed, #Ry
// if (r=1)
if (r == 1)
No early break
OP's code: The value of r depends on the last iteration. Certainly once a factor is found, loop should exit.
for(i=2;i<=n-1;i++) {
if(n%i==0)
// r=1;
{ r = 1; break; }
else
r=0;
}
Incorrect functionality for n == 0,1
All values n < 2 incorrectly report as prime.
Inefficient
Code performs up to n loops. Only need to perform sqrt(n) loops. Tip: Do not use floating point math here for an integer problem.
// for(i=2;i<=n-1;i++)
for(i = 2; i <= n/i; i++)
Alternate
Only peek if you must code.
First off, " ... conio.h is a C header file used mostly by MS-DOS compilers to provide console input/output. It is not part of the C standard library or ISO C .." I was able to get the code to compile without that library file, so you may wish to consider removing it. As for as the code goes, well here is what I came up with:
#include <math.h>
#include <stdio.h>
int isPrime(int value) {
int i = 2;
for(; i < value; i++) {
if((value % i) == 0) {
return 0;
}
}
return value > 1;
}
int main(void){
int n=0,i=0, r=0;
char * s;
printf("\nPlase enter a number to learn if it is prime:");
scanf("%d",&n);
r = isPrime(n);
printf("\n%d is ", n);
s = (r==0)? " not a prime number" : "a prime number";
puts(s);
return 0;
}
After the user inputs a number, the code checks whether it is prime by calling the function isPrime(), a function that returns an int. isPrime is a simple function that attempts to factor a number.
See here for similar live code that I devised.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Trying to complete a larger task in C, but for some reason this one small simple (or so I thought) piece of the puzzle isn't working.
I want to print 0 to 9, each on individual lines:
#include <stdio.h>
#include <stdlib.h>
#define MAX 9
int main()
{
for (int counter = 0; counter == MAX; counter++)
printf("%d \n", counter);
return 0;
}
However, nothing* happens when I build & run. I've been staring it for over an hour...
*Nothing = Process returned 0 (0x0)...
My guess is that you think the statement after the first semicolon in the for loop is the condition that stops the loop when it is true. Actually, that statement has to be true/non-zero to the loop to execute.
Try for(int counter = 0; counter <= MAX; counter++) instead.
The for loop will keep on running so long as the checking expression counter == MAX remains true. Which is never the case in this code snippet. You probably meant counter != MAX.
This would print 0 - 8 and not 0 -9. For that you would need to make MAX 10 or change the loop condition to counter <= MAX.
Change counter == MAX to counter <= MAX. So in this case your loop will run until counter is less than or equal to MAX
The idea behind the middle area in the for is the condition for the loop to continue, and not to stop if it is true. While the condition returning true value, the loop will continue. In your case the condition have to look like this one: counter <= MAX. And in the whole loop:
for (int counter = 0; counter <= MAX; counter++)
printf("%d \n", counter);
There are two things that might prevent this code from running.
First thing is what everyone else have pointed. The condition is forever false in the conditional part of the for loop in
for(initialization; condition; increment/decrement)
{
//code here
}
the correct condition seems to be
counter <= MAX
Second thing might be that you are using an old compiler in which case you need to initialize the counter at the beginning of the code before performing any other action. Initialization is not allowed within for in many old compilers. The place where it would be most suited would be right after the opening braces { of the main() function block.
Thus the best approach would be
#include <stdio.h>
#include <stdlib.h>
#define MAX 9
int main()
{
int counter;
for (counter = 0; counter <= MAX; counter++)
printf("%d \n", counter);
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i passed this project in and the grader gave me 50% saying i did not use function for loops. The instructions said use while loops, or does he mean otherwise? here is the code. the project is supposed to count from 10 to 0 then 0 to 10.
#include <stdio.h>
int main()
{
int Integer;
printf("Please enter an integer\n");
scanf_s("%d", &Integer);
int count = Integer;
while (count >= 1)
{
printf("%d\n", count);
count--;
}
printf("*****\n");
while (count <= Integer)
{
printf("%d \n", count);
count++;
}
return 0;
}
This may be related to a specific style the grader wanted your class to learn, or a specific conversation. I suggest asking, as your grader's response was (clearly) missing some details for you.
Meanwhile, some suggestions of what your grader might have been looking for.
Did your grader literally mean for you to use for-loops?
for ( ; count >= 1; count--) {
printf("%d\n", count);
}
Did you forget to count to 0 the first time? (The above loop will stop printing at 1, not 0.
Does your grader want you to functionalize the loop kernels?
void countDownLoopKernel ( int value ) {
printf("%d\n", value);
}
...
while ( count >= 1 ) {
countDownLoopKernel( count );
count--;
}
For a functioning program, items 1 and 3 are arbitrary. They can be crucial when fitting into a larger program's (or company's) style, for readability, for following DRY principals, or for refactoring, but for small programs like this, they make no difference. I suspect your grader is trying to get you to think about alternatives beyond "It works, so it's good enough."
They may have wanted you to use both for and while loops. To count from Integer to 1, try this:
for (count = Integer; count >= 1; count--)
printf("%d\n",count);
Also, to count from 1 to Integer, try this:
for (count = 1; count <= Integer; count++)
printf("%d \n");
I hope this helps!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am having trouble finding understanding complexity. Could someone help me understand what the complexity of the code below is and why.
for (int i = 1; i < n; i++) { // (n is a number chosen by the user)
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
An explanation would be great.
Assuming i starts at 0, the complexity would be constant. The complexity is always expressed relative to a variable defining the number of executions, which is not the case here.
If one term should be used to describe this behavior, it is "constant". There will be a number of executions, but this number will never change
Original Question: Because i's initial value is undefined, the behavior of the code is unpredictable. There is no way to usefully answer the question other than that the complexity is undefined. There is no way to know how many operations the code will perform.
Updated Question: It's O(1). The code will always do precisely the same amount of work.
You can compute the time complexity of this code fragment by evaluating the number of operations, namely the number of calls to printf() which for simplicity's sake we shall assume to be equivalent:
Assuming i starts at 1 (you initially forgot to initialize it), the outer loop runs 99 times, for each iteration, the inner loop runs i times. Gauss was supposedly 9 years old when he computed the resulting number of iterations to be 99 * (99 + 1) / 2.
The complexity of the original piece of code was O(1) since it did not depend on any variable, but since instead you updated the code as:
void fun(int n) {
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
}
The time complexity would come out as O(n2).