Wednesday, January 24, 2018

C Simple Puzzles

-------------------------------------------------------------------
How to print numbers from 1 to N without using any semicolon in C.
/ A recursive C program to print all numbers from 1
// to N without semicoolon
#include<stdio.h>
#define N 10
int main(int num)
{
   if (num <= N && printf("%d ", num) && main(num + 1))
    {
    }   
}
------------------------------------------------------------------
Find sum of two numbers without using any operator
int main()

{
printf("sum=%d",printf("%*c%*c",3,' ',4,' '));

return 0;

}
------------------------------------------------------------------
Write a one line C function to round floating point numbers
1.6
Algorithm: roundNo(num)
1. If num is positive then add 0.5.
2. Else subtract 0.5.
3. Type cast the result to int and return.

Example:
num = 1.67, (int) num + 0.5 = (int)2.17 = 2
num = -1.67, (int) num – 0.5 = -(int)2.17 = -2

Implementation:

/* Program for rounding floating point numbers */
# include<stdio.h>
int roundNo(float num)
{
    return num < 0 ? num - 0.5 : num + 0.5;
}

int main()
{
    printf("%d", roundNo(-1.777));
    getchar();
    return 0;
}
Run on IDE
Output: -2

Time complexity: O(1)
Space complexity: O(1)

No comments:

Post a Comment