For looping in C confused [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 6 years ago.
Improve this question
What problem if I use strlen() in the condtion of for loop.
char s[i];
for (int i = 0; strlen(s); i++)
So if I use upper code there took a lot of time.
But if I store the value of strlen of s it took little time inspect to upper code.
What difference between these?

You should not use i < strlen(s) as a condition because the length of the string in s gets recomputed for each iteration of the loop. It is better to use a separate variable and compute the length in the initialization part:
for (size_t i = 0, len = strlen(s); i < len; i++) {
...
}
Note that your definition of s looks like a typo: char s[i];. What variable i are you referring to? what would be its value before the beginning of the for loop that defines a new i variable?
EDIT
After reformatting your code, I realized there is even more confusion:
for (int i = 0; strlen(s); i++)
This for loops iterates as long as string s is not empty. Is this your intent? Do you modify s inside the loop? s is uninitialized, the test invokes undefined behavior. Do you initialize s in code you did not post between the definition and the for loop? If you do, it would still be more efficient to write such a loop this way:
for (int i = 0; *s != '\0'; i++)

The condition is evaluated before every iteration of the loop.
C strings are just an array of characters, then a NULL. So to work out the length you have to start at the start and inspect every character from there until you find the NULL.
So in complexity terms, strlen is O(n). Your for is also O(n). If you check the strlen every time then your implementation is O(n*n). If you work it out once in adavance then yours os O(n). Try it with longer ss to see a much bigger difference.

Related

Is it possible to have the intersection of two strings without using a loop in C? [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 last year.
Improve this question
I would like to ask you if it was possible to get the characters common to two strings without having to resort to a loop on the character array. I wonder why this could greatly affect the total cost (asymptotically for n-> infinite) of algorithms such as eg. Charm or Eclat (just think that it would be like adding a new cycle to those already present). Thank you.
Specifically, the algorithm I am referring to is the following. As can be seen from the photo (line 6) it is necessary to obtain the intersection by iterating on the indices i and j, so I suppose it is necessary to iterate. I guess I get an O(m + n) best assuming the insert and search operations use O(1).
If your characters are byte-encoded (US-ASCII, KOI8-R, etc), you can create array, where your char is index, and iterate 1st string, and set "1" here. Thereafter, iterate 2nd string, and print only chars, presents in the array. See the example:
void print_intersection(const unsigned char *s1, const unsigned char *s2) {
unsigned char arr[0x100], c;
bzero(arr, sizeof(arr)); // cleanup
while(c = *s1++)
arr[c] = 1;
while(c = *s2++)
if(arr[c] != 0) {
putchar(c);
arr[c] = 0; // Disable print dups
}
}

The logic of nested loops in C [closed]

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
I am new to programming and I'm following the CS50 course. I'm trying to fully understand the logic behind nested loops in C. I think I've got it, but I'd like to be sure before I move on to the next set of problems. Here's the code (provided by the course). It creates a cube made of hashes. My explanations are below the code.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n, j++)
{
printf("#");
}
printf("\n");
}
The first loop starts: It creates a new variable called i and sets it to 0. The command checks the new variable: If it is lesser than n (true), run it, starting the inside loop.
The inside loop also creates a new variable, j, sets it to 0, checks it and, if it is true (j < n), runs the code below and print a hash. Afterwards, the inside loop is incremented and this process occurs again until the inside loop condition is not met anymore. This will create a ROW of hashes if n is greater than 2.
The outer loop creates a new line, increments and the process starts all over again. It will run until the condition is false (i > n).
The next times the inside loop is accessed, the variable j is set to 0 again, that's why it is possible to print various rows in this program.
Is that correct? Thank you very much in advance!
Yes, your explanation is spot on.
With a minor mistake:
It will run until the condition is false (i > n).
The condition is false when i >= n.
And what I assume it's a typo:
for (int j = 0; j < n, j++);
// ^
// |
remove the ;

sizeof vs strlen in long running programs [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 3 years ago.
Improve this question
Which of these is faster and can be used in programs which runs 100s of times in a loop (for size of strings)?
sizeof - it is a macro and a compile time expression.
or
strlen - it's run time expression.
In my mind I want to avoid strlen as it's a function and calling it again and again might slow things down - Am I correct?
These do not do the same thing.
sizeof is an operator which, in most cases, is evaluated at compile time. It gives the size in bytes of a variable, including arrays and structs. In contrast, strlen is a function which returns the length of the string passed to it.
For example:
char str[100] = "hello";
printf("size = %zu\n", sizeof str); // prints 100
printf("len = %zu\n", strlen(str)); // prints 5
That being said, if you're looking to optimize something like this:
int i;
for (i=0; i<strlen(str); i++) {
...
}
You should do this instead:
int i;
int len = strlen(str);
for (i=0; i<len; i++) {
...
}
If your strings are not string literals or arrays then strlen is your only choice. Either way, it will be fast—strlen is usually very heavily optimized.

Which is quicker between printf %s and for loop %c [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 5 years ago.
Improve this question
Please I'd like to know which is better/quicker to process between:
printf("%s", foo);
and
for(int i = 0; i < len; i++)
printf('%c', foo[i]);`
I have noticed that the output is not always the same.
The single call printf("%s", foo); is most likely faster. You only make one function call to printf instead of n function calls, each of which has to parse the format string.
Even if the latter was faster, the former is still preferred because it is clearer to the reader.
Performance test it. Trying to come up with any rule that A is faster than B is bad practice. The assumption will become incorrect over time or in slightly different scenarios. Always performance test when optimizing.
Write a test case and test it with a high precision timer. Make sure your performance timer has a high enough granularity to show differences. On Windows you can use QueryPerformanceCounter. Googling that function should get you started.
Note that there is a syntax error in: for(int i = 0; i < len; i++) printf('%c', foo[i]);. It should read:
int len = strlen(foo);
for (int i = 0; i < len; i++)
printf("%c", foo[i]);
This loop, assuming the length of foo fits in a int, is quite inefficient. printf("%s", foo); is very likely faster than that, but if you have noticed different output, there is something fishy going on... Maybe len was not computed properly.
Note also that you could write a potentially more efficient version:
for (int i = 0; i < len; i++)
putchar(foo[i]);
And you could also improve on printf("%s",foo); with this variant:
fputs(foo, stdout);
But as always, you should test and benchmark on your system to measure actual performance. Some compilers will optimize the printf("%s", foo); into fputs(foo, stdout); automatically.
The statement without loop is probably faster than the statement with loop.
Using for loop
for(int i = 0; i < len ; i++)
printf("%c", foo[i]) ;
In every iteration, i is compared with 'len' and i is incremented after every character is printed.
Without loop
printf("%s", foo) ;
foo here is basically a pointer to string and it will go on printing every character after foo[0] until a '\0' character (or terminating character) is found.
So, in the 2nd case, we save the time to update i and access foo[i] with respect to foo[0].
To add a disclaimer, the actual performance testing might lead you to results that would depend on the compiler and the operating system you are working on.

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

Resources