0% found this document useful (0 votes)
19 views4 pages

Time Complexity Examples in C

The document provides examples of C code snippets that demonstrate different time complexities based on loop structures. It explains how the number of iterations affects the time complexity, with examples showing linear, logarithmic, and double logarithmic complexities. Each example includes the output and a brief analysis of the time complexity associated with the code.

Uploaded by

Sonal Balpande
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

Time Complexity Examples in C

The document provides examples of C code snippets that demonstrate different time complexities based on loop structures. It explains how the number of iterations affects the time complexity, with examples showing linear, logarithmic, and double logarithmic complexities. Each example includes the output and a brief analysis of the time complexity associated with the code.

Uploaded by

Sonal Balpande
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Rules:

For comments and declaration count is 0


Return and assignment count 1
Ignore lower order Exponents

Example 1:
#include <stdio.h>
void main()
{
int i, n = 8;
for (i = 1; i <= n; i++) {
printf("Hello World !!!\n");
}
}

Output:

Hello World !!!


Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Time Complexity: In the above code “Hello World !!!” is printed only n times on
the screen, as the value of n can change.
So, the time complexity is linear: O(n) i.e. every time, a linear amount of time is
required to execute code.

Example 2:
#include <stdio.h>
void main()
{
int i, n = 8;
for (i = 1; i <= n; i=i*2) {
printf("Hello World !!!\n");
}
}
Hello World !!!
Hello World !!!
Hello World !!!
Hello World !!!
Time Complexity: O(log2(n))

Example 3:
#include <stdio.h>
#include <math.h>
void main()
{
int i, n = 8;
for (i = 2; i <= n; i=pow(i,2)) {
printf("Hello World !!!\n");
}
}

Hello World !!!


Hello World !!!
Time Complexity: O(log(log n))

You might also like