What does this mean regarding loops? [closed] - c

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!

Related

Thinking of a code to show if a number is prime or non prime? [closed]

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.

Which loop is better? [closed]

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 :)!

What is the complexity of the following simple program? [closed]

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).

Why a for loop isn't considered 'stylish' by my teachers? [closed]

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 9 years ago.
Improve this question
I had to write a piece of code which would search a given value in an array.
I made this piece of code, which works:
#include <stdio.h>
int index_van(int searchedValue, int array[], int lengthArray)
{
int i ;
for (i = 0; i < lengthArray; i++)
{
if (array[i] == searchedValue)
{
return i;
}
}
return -1;
}
int main()
{
int array2 [] = {0, 1, 3, 4, 5, 2};
printf("%i", index_van(2, array2, 6));
}
With the correction (the teacher put up online) of this exercise the notes of my teacher were:
You have to quit the moment you have found your value ,so you can't search through the entire table if you have found your value already. A for-loop therefore isn't tolerated.
Even if the for-loop has an extra built-in condition, THIS ISN'T STYLISH!
// One small note ,she was talking in general . She hasn't seen my version of the exercise.
So my question to you guys is, is my code really 'not done' towards professionalism and 'style' ?
I think she's implying that you should use a while loop because you don't know how many iterations it will take to get you what you're looking for. It may be an issue of her wanting you to understand the difference of when to use for and while loops.
"...Even if the for-loop has an extra built-in condition..."
I think this right here explains her intentions. A for loop would need a built-in condition to exit once it's found what it's looking for. a while loop already is required to have the condition.
There is nothing wrong with your code. I have no idea if using a for loop is less stylish than using another, but stylish is a very subjective attribute.
That being said, don't go to your teacher and tell her this. Do what she says, a matter like this is not worth contradicting your teacher for. Most likely this is just a way to teach you how while loops work.
After accept answer:
I've posted this to point out sometimes there is so much discussion of "style", that when a classic algorithmic improvement is at hand, it is ignored.
Normally a search should work with a const array and proceed as OP suggest using some loop that stops on 2 conditions: if the value was found or the entire array was searched.
int index_van(int searchedValue, const int array[], int lengthArray)
But if OP can get by with a non-const array, as posted, then the loop is very simple and faster.
#include <stdlib.h>
int index_van(int searchedValue, int array[], int lengthArray) {
if (lengthArray <= 0) {
return -1;
}
int OldEnd = array[lengthArray - 1];
// Set last value to match
array[lengthArray - 1] = searchedValue;
int i = 0;
while (array[i] != searchedValue) i++;
// Restore last value
array[lengthArray - 1] = OldEnd;
// If last value matched, was it due to the original array value?
if (i == (lengthArray - 1)) {
if (OldEnd != searchedValue) {
return -1;
}
}
return i;
}
BTW: Consider using size_t for lengthArray.

How do I do this with C? Fibonnacci Sequence [closed]

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 8 years ago.
Improve this question
Perhaps someone could help me out with this.
Using the concept of cycle generate the Fibonacci series until reaching 10000 or a little more than that.
So I have this code and it's supossed to work and show me what I want but it doesn't.
Can somebody tell me what's wrong with it? It opens but it doesn't work #_#
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0,j=0,sum=1,num;
while(sum>=1000){
{
printf("%d\n",sum);
i=j;
j=sum;
sum=i+j;
}
system("pause");
}
The code I made for calculating the Fibonacci sequence is the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0,j=0,sum=1,num;
printf("Introduce the limit for the Fibonacci sequence: ");
scanf("%d",&num);
while(sum<num)
{
printf("%d\n",sum);
i=j;
j=sum;
sum=i+j;
}
system("pause");
}
In the first snippet, you have a typo
while(sum>=1000){
should be
while (sum < 10000){
I said 'less than' rather than 'less than or equal to' because of the wording of your assignment.
You want to print out Fn where Fn is the first such number > 10000. Since j is really Fn-1 change the while loop condition to
while (j <= 10000)
{
while sum >= 1000 means it will never start because sum = 1. I think you want <=. The second is an infinite loop because sum is always greater than num

Resources