Sum of Odd Numbers Within a Given Limit in C

 


Code:

#include <stdio.h>

int main()
{
    int i,n,sum=0;
    
    printf("Enter Limit : ");
    scanf("%d",&n);
    printf("\nOdd Numbers : ");
    for(i=0;i<n;i++)
    {
        if(i%2 != 0)
        {
            printf("%d ",i);
            sum = sum + i;
        }
    }
    printf("\nSum of Odd Numbers : %d",sum);
}

Output:





With Time Complexity

Code:

#include <stdio.h>
#include <time.h>

int OddSum(int i,int n);

int main()
{
    int i,n;
    double time_taken;
    printf("Enter Limit : ");
    scanf("%d",&n);
    
    //Time Taken to run the function
    clock_t start = clock();
    OddSum(i,n);
    clock_t end = clock();
    time_taken=((double)(end-start))/CLOCKS_PER_SEC;
    printf("\nTime Taken: %f",time_taken);
}
int OddSum(int i,int n)
{
    int sum=0;
    printf("\nOdd Numbers : ");
    for(i=0;i<n;i++)
    {
        if(i%2 != 0)
        {
            printf("%d ",i);
            sum = sum + i;
        }
    }
    printf("\nSum of Odd Numbers : %d",sum);
}

Output:





AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page