C Basics

1. Write a program to print numbers from 1 to 100 in such a way that, it prints "fizz" if number is divisible by 2, prints "buzz" if it is divisible by 3 and prints "fizzbuzz" if it it is divisible by both and prints the number itself if it is divisbile by neither.

This is a very simple program which iterates over numbers from 1 to 100 and uses modulo operator to check divisibility by 2 and 3.

If the number is divisible by 2, then Fizz is printed. If it is divisible by 3, then 3 is printed. As the inner ifs are not exclusive, if the number is divisible by both 2 and 3, then FizzBuzz will be printed.

#include<stdio.h>
int main()
{
   int i;
   for(i=1;i<100;i++)
   {
     if(i%3 && i%2)
        printf("%d ",i);
    else{
      if(i%2==0) printf("Fizz");
      if(i%3==0) printf("Buzz");
    }

       printf("\t");
    }
    return 0;
} 
2. What does the following function do?
int func(int num)
{
    int count = 0;
    while (num)    
   {        
        count++;        
        num >>= 1;    
    }
    return  count ;
} 

The function returns total numbers of bits in a given number excluding leading zeroes

e.g. if the number is 7- that is binary 111, then output is 3 and if the number is 16 - binary 10000, output is 5

It right shifts the number by 1 bit each time, until the number becomes 0. So, 111 becomes 11 in first iteration, becomes 1 in second iteration and 0 in third iteration. So count is 3

3. A 2-sum is the sum of a list of numbers, but every number that is next to a 2 is counted twice. Given a list of numbers, write a program print out their 2-sum.

For example, when given "1 2 3 4" as input, 2-sum is 14, because 1 and 3 which are next to 2, are added twice.
1+1+2+3+3+4 = 14

#include<stdio.h>

int twos_sum(int *arr,int sz);
int main()
{
   int arr[20];
   int len,sum;
   int i=0;
   int num=0;
   do
   {
      printf("Enter number - 0 to terminate:");
      scanf("%d",&num);
      if(num!=0)
        arr[i++] = num;
    }while (num!=0);
    len = i;
    sum = twos_sum(arr,len);
    printf("The two-s sum is %d\n",sum);
    return 0;
}

int twos_sum(int *arr,int sz)
{
    int i=0;
    int sum=0;
    for(i=0;i<sz;i++)
      {
         sum +=arr[i];
         if(arr[i]==2)
         {
             if( i-1 >=0)
                 sum+=arr[i-1];
             if( i+1 <sz)
                 sum+=arr[i+1];
          }
      }
   return sum;
}
4. What is the difference between ++a and a++? (pre-increment and post-increment operators)

In ++a or preincrement operator, variable a is first incremented and this incremented value is used in the expression.

Where as in a++, first variable is used in the expression and then it is incremented.

e.g.

m = a+++b;

is equivalent to
   m = a+b;
   a = a+1;
in that order

whereas
m= ++a+b;

is equivalent to
   a = a+1;
   m = a+b; 
in that order

Let us look at another example.

 b = a++;
or
b =++a;


If a is 10, after b = a++;, b will be 10 only and then a becomes 11. That is to say, first b is assigned to a and then a is incremented.

But after b=++a;, a will be incremented to 11, then b is set to 11. Here first a is incremented and then b is assigned to a.

5. Write C statement/s to print larger of two numbers without using if statement

printf("Larger number is %d",a>b?a:b);

If the numbers are integers and you can even write the statement without using relational operators.

 printf("Larger of two numbers is %d",a/b?a:b); 
Here if a is greater than b, then a/b is non-zero and a will be printed. If a is less than b, then a/b will be 0, as it is integer division. Zero is false, and hence b will be printed.
6. What is wrong with this statement
double pi = 22/7;

Syntactically the statement is correct. But the value of pi will be 3.0 instead of 3.14.

In the initialization, 22/7 uses integer arithmetic because both operands are integers. So 22/7 is truncated to 3, then it is type-cast to double. So pi value becomes 3.0 instead of 3.14.

The correct statement should be

double pi = 22.0/7;
If one of the operands is non-integer, then program uses real arithmetic.

Another way of avoiding such problems is to use type casting for one of the operands.
double pi = (double)22/7;
Here 22 is converted to double - 22.0. And real arithmetic takes place and gives correct answer.

7. Find the bug in this program
#include<stdio.h>
int main()
{
   double num;
   printf("enter a double number :");
   scanf("%f",&num);
   printf("the number you just entered is %f\n",num);
   return 0;
}

scanf("%f",&num);
should be replaced by
scanf("%lf",&num);
For scanf function, format specifier for double variable should be "%lf" not "%f".

If you use a wrong format specifier, there won't be any syntax error. There is undefined behavior instead. It may take a wrong value. It may even crash the program

There is a confusion regarding format specifiere of double data type because for printf function, format specifier for double is %f

8. How do you assign a float value 12 to a float variable m?

float m = 12.0f;
is the correct method.

By default a non-integer literal is treated as double. So 12.0 is a double value, not a float value. You should use suffix "f" or "F" to make a real constant as float constant.

But the program works fine, even if we use "m=12.0", as the compiler implicitly converts this double constant to float constant.

9. Write code to swap two variables without using third variable and using exor (^) operator

a = a^b;
b = b^a;
a = a^b;

Another way to write this code with + and - operators is

a = a + b;
b = a - b;
a = a - b;
10. A statement is written to print whether the number is odd or even. Is it correct?
if(n&1) 
      printf("%d is odd",n);
else 
     printf("%d is even", n);

It is correct

When we are using bitwise & operator, the individual bits of both operands are logically anded. So if we have two numbers as 7 and 8 - the operations will be 111 & 1000 = 0000

When we use & with 1, then if the number has LSB as 1, the result will be 1. If not, the result will be 0. Which means that the result is 1 for odd numbers and 0 for even numbers.

11. Write the output of the following program
#include<stdio.h>
int main()
{
    char ch;
    if(ch = printf(""))
        printf("It matters\n");
    else
        printf("It doesn't matters\n");
    return 0;
}

Output : It doesn't matter

The expression ch=print("") is an assignment statement. ch is assigned to return value of printf.

printf returns the total number of characters printed. Hence here it returns 0.

This 0 is assigned to ch and ch becomes the conditional expression. So if condition is false. And the program executes else part and prints "it doesn't matter"

12. What is the output of the following program?
#include<stdio.h>
int main()
{
    int x = 10, y = 20;
    if(!(!x) && x)
         printf("x = %d\n", x);
    else
         printf("y = %d\n", y);
    return 0;
}

Output : x is 10

x is true because in C, any non-zero value is true. !x is false. !(!x) is again true. true and true is true.

So the program executes the if clause and prints value of x.

13. Write a program to find the second largest number of an array using only one iteration

To find the second largest element,

  1. Initialize both largest and second-largest to 0th element of array.
  2. Iterate over each element from 1 to n-1
  3. If arr[i] element is larger than largest, then set second-largest = largest and largest = a[i]
  4. if not if arr[i] is larger than second-largest, second-largest = arr[i]
#include<stdio.h>
int second_largest(int arr[],int n);
int main()
{
    int arr[10];
    int i,la;
    for(i=0;i<10;i++)
      scanf("%d",&arr[i]);
    la = second_largest(arr,10);
    printf("Second largest element of the array is %d\n",la);
    return 0;
}

int second_largest(int *arr,int n)
{
   int lar,sec_lar=0;int i;
   lar = sec_lar= arr[0];arr++;
   for(i=1;i<n;i++,arr++)
   {
     if(*arr>lar)
     {
         sec_lar = lar;
         lar = *arr;
      }
      else if( *arr>sec_lar)
      {
           sec_lar = *arr;
      }
    }
    return sec_lar;
}   
14. What will be the output of the following C program segment?
char inchar = "A";
switch (inchar)
{
   case "A" :printf ("choice A ") ;
   case "B" :printf ("choice B ") ;
   case "C" :printf("choice C ");
   case "D" :
   case "E" :
   default:printf ("No Choice") ;
} 
The output is
choice A choice B choice C No choice

Since there are no break statements after each case statement, the execution seeps through to next statement until default. And default is also executed.

Correct way to use switch should be to include break after each case.

switch(inchar)
{
     case "A":printf("choice A\n");
                 break;
       ......
 }              
etc.
15. What does the following printf statement print? Assume that size of int is 4 bytes.
printf("%d %d %d %d",sizeof(2),sizeof(2.0),sizeof('2'),sizeof("2"));

It prints : 4 8 4 2

2 is an integer. Hence its size is 4 bytes.

2.0 is a double, not a float. (2.0f is a float literal) Hene its size is 8 bytes.

'2' is character literal and character literals are treated as integers. Hence its size is 4 bytes.

And "2" is a string literal with 2 characters, "2" and null("\0") so its size is 2

16. Explain the terms lvalue and rvalue with examples.

lvalue is something which has an address associated with it.
Literally lvalue is something which can be used in LHS of an assignment statement.

In an assignment statement, RHS is evaluated and its value is stored in the address of LHS variable. So we can not say 2 = a, because we can not store value of a in 2.

All variables are lvalues.

rvalue (right hand side value) is a temporary result of an expression, hence has no memory location for it.

int a;
a = 4;/*a is an lvalue*/
a+5=7; /*error. a+5 is not an lvalue.*/

Remember that rvalues can NEVER be used on LHS of a assignment statement.

17. What is an entry controlled loop and an exit controlled loop?

Entry controlled loop is a loop where the condition is tested before body of the loop is executed. Exit controlled loop is a loop where condition is tested after body of the loop is executed.

Both for and while loops are entry controlled where as do--while is an exit controlled loop.

e.g.

for(i=0;i<10;i++) 
        printf("%d",i);
When this loop is executed, the condition i<10 is tested. If only this contion is true, then printf() statement is executed. If it is false, the loop is terminated.

Similarly
while(a<5)  
         printf("%d",a++);
checks condition a<5 first before entering into the loop.

In
do 
      printf("%d",a++); 
 while(a<5); 
Here first printf() is executed and then condition is tested.

The advantage of exit controlled loop (do -while loop) - is that the body of the loop is executed at least one.

18. Write a function to set kth bit of a number.

#include<stdio.h>
int set_bit(int n,int k);
int main()
{
   int num,k;
   printf("Number:");
   scanf("%d",&num);
   printf("k:");
   scanf("%d",&k);
   num = set_bit(num,k);
   printf("After setting %dth bit number is %d\n",k,num);
   return 0;
}

/* function sets kth bit from LSB*/
int set_bit(int num,int k)
{
    int temp = 1;
    temp = temp<<k;
    num = num | temp;
    return num;
}

Bitwise OR (|) operator is be used to set a bit. (& operator is used to clear a bit)

We need to have a temporary variable which has only kth bit set and all other bits as 0. For that, we are taking temp as 1 and left shift it by k places.

Then we bitwise OR (|) this temp with the given number. The result will have kth bit set and other bits unmodified.

Let us look at an example.

Let us say n is 10 and k is 2

temp = 1<<2 = 0100

Now 10 | temp is 1010 || 0100 = 1110 = 14

So we have set 2nd bit from LSB in the number

19. Write a function to flip kth bit of a number. If bit is set, it should be cleared and if it is clear, it should be set.

#include<stdio.h>
int flip_bit(int n,int k);
int main()
{
   int num,k;
   printf("Number:");
   scanf("%d",&num);
   printf("k:");
   scanf("%d",&k);
   num = flip_bit(num,k);
   printf("After flipping %dth bit number is %d\n",k,num);
   return 0;
}

/* function sets kth bit from LSB*/
int flip_bit(int num,int k)
{
    int temp = 1;
    temp = temp<<k;
    num = num ^ temp;
    return num;
}

^(EXOR) operator can be used to toggle a bit. Because 1^1 is 0 and 1^0 is 1.

So the function first creates a temp with kth bit set and all other bits 0. Then it Exors the number with temp

20. Write a function to add two numbers using bitwise operators

 int getSum(int p, int q)
{
    int result = p ^ q; /* + without carry 0+0=0, 0+1=1+0=1, 1+1=0 */
    int carry = (p & q) << 1; /* 1+1=2 */
    if (carry != 0) {
        return getSum(result, carry);
    }
    return result;
}
21. Write an expression to find if the number is a power of 2

if (num && ((num&(num-1)) ==0)) 
     printf("power of 2");

If a number n is a power of 2, then it has MSB set and all other bits cleared. Numbers just before it - n-1 - has all bits set but its bit corresponding to MSB of n is 0.

When we bitwise and these two numbers, we get a 0.

e.g. 16 is 10000 in binary 15 is 01111 in binary

When we AND 15 and 16 using bitwise AND (&) then we get 10000 & 1111 = 0

To avoid taking 0 as power of 2, first condition is used num!=0 which is same as num
22. What are implicit and explicit conversions in C?

Implicit conversion: Some data type conversions from one type to another type are done automatically by C program. This is implicit conversion.

Examples

  • The value of right hand side is converted to type of left hand side operand.
  • e.g.
    float m = 3;/* value gets converted to 3.0f*/
  • The arguments of a function is converted to the types of parameters of the function, and return value is converted to return type of function.
  • float larger(float a,float b);
    larger(4,-12)
    The values 4 and -12 get converted to 4.0f and -12.0f

  • In an expression, shorts and chars are promoted to ints.
  • int a = 'a'+2;
    Here character literal 'a' is converted to integer - to its ASCII code which is 97
  • In an expression, if any operand is float, then all values are converted to float.
  • If in an expression one value is double and others are smaller then all are converted to double.
  • float pi = 22.0f/7;/*this becomes 22.0/7.0*/

Explicit conversion : When an expression is converted using typecast operator, it is explicit conversion. Typecast operator is data type within paranthesis written to the left of expression.

Examples of explicit conversion:

char *ptr = (char *) malloc(10);
float ans = (float)5/10;

malloc returns a void pointer. It is converted to char pointer in first example.
5, which is an integer, is converted to float and then divided by 10 in second example.

23. Write a function to divide two integers without using the division operator.

int divide(int a, int b)
{
     int count=0;
     while (a>=b)
     {
       a -=b;
       count++;
     }
     return count;
}
24. What are the differences between a macro and a constant?

Macros and const are used to define constants in C. A macro defined by #define gets expanded by the preprocessor.
e.g.

#define MAX 10
Compiler will have no knowledge about macros. If we do not define macros correctly, preprocessor does literal substitution and instead of compiler error, we get unexpected results.

Constants are defined using keyword const.
e.g.

const int NUM=20;
Constant definitions are seen by the compiler. And if there are any errors with consts, they are detected by the compiler.

So defining a constant using const is always safer than defining it with #define.

25. Write a C program to test whether in a given number atleast 3 out of the last 4 bits are set.

  1. To remove the other nibbles of the number, the number is bitwise ANDed with 0xf.
  2. Then you EXOR a number with 0xf (1111)
  3. If the number has atleast 3 bits set, then the result of AND is a number which has maximum one bit set.
  4. The set bit could be in 0th, 1st, 2nd or 3rd position.
  5. So if the result of AND is 1, 2, 4 or 8 or 0, the condition is true.
e.g. If the number is 12
1100
1100 ^ 0xf = 1100 ^ 1111 = 0011 = 3

So the number does not have at least 3 bits set.

If the number is 14 with 3rd bit, 2nd bit and first bit set

1110 ^ 1111 = 0001

The answer is 1. So 14 has at least 3 bits of 4 last bits set.

#include<stdio.h>
int main()
{
    int n;
    printf("Enter a number");
    scanf("%d",&n);
    n = n&0xf;
    n = n^0xf;
    if(n==0|| n==1 || n==2||n==4||n==8)
       printf("true");
    else
       printf("false");
    return 0;
}

26. How will you write a code to print Hello world without using semicolon?

int main()
{
   if (printf(“Hello World”)){}   
}
27. Write a program to print all the prime factors of a number

A prime factor of a number is a factor which is prime - a number divisible by only 1 and itself.

The long and easy method of finding prime factors will be to find factors from 1 to n-1 using modulo operator. And then testing if that number is prime.

But we know that the largest factor of any number is only n/2. And if we know that a number is a factor, and we divide n by i until n is no longer divisible by i, we have removed i and all its multiples from n. If we continue to do this, we will be removing multiples of numbers, then only factors we are left with are prime factors.

  1. Repeat from i=3 to n/2 in steps of 2 avoiding even numbers
  2. If n is divisible by i
    • while n is divisible by i
    • divide n by i
# include <stdio.h> 
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
	int m =n;int i; 
	m = n;
	i =2;
	while(i<=m/2)/*repeat till half of the number*/
	{
	    if(n%i==0)
	    {
             /*if i is a factor, keep dividing by i until its no longer divisible by i*/
		      while(n%i==0)
		             n = n/i;
		      /*i  is a prime factor. print it*/    
	          printf("%d    ",i);
 	    }
	   /*check only 2 and odd numbers*/
            if(i==2)
                 i++;
            else
                 i+=2;
  }
}

int main()
{
    int n;
    printf("n=");
    scanf("%d",&n);
    primeFactors(n);
    return 0;
}
28. Write a program to check if all the bits of a number are ones. e.g. 15, 7, 31 etc

If the number has all bits as 1, then it's next number will be having MSB set and all other bits 0.

For example, for the number 15,(which is 1111), next number 16 (10000) has all bits as 0 except for most significant bit. For 31 (11111), the next number is 100000.

When we bitwise AND the number and its next number - (&) num & (num+1), we should get 0.

#include<stdio.h>
int main()
{
   int num;
   printf("num:");
   scanf("%d",&num);
   if( num && (num&num+1)==0)
       printf("number  has all bits set");
   else
       printf("number does not have all bits set");
   return 0;
}
29. Write a function to print if the number is even or odd without using if statement

void even_odd(int n)
{
     n&1?printf("Odd"):printf("Even");
}

void even_odd2(int n)
{
    swithc(n%2)
   {
      case 1:printf("even");break;
      case 0:printf("odd");break;
    }
}
Another method would be using a ternary operator as
n&1?printf("%d is odd",n):printf("%d is even",n);
30. Write a program to print the pattern

    A
   ABA
  ABCBA
ABCDCBA

#include<stdio.h>
#include<string.h>
int main()
{
    char arr[] = "ABCD";
    int i,j;
    for(i=0;i<4;i++)
      {
        int num = strlen(arr)-i;
        int j;
        for(j=0;j<num;j++)/*print spaces*/
          printf(" ");
        for(j=0;j<i+1;j++)/*ascending*/
          printf("%c",arr[j]);
        for(j-=2;j>=0;j--)/*descending*/
          printf("%c",arr[j]);
        printf("\n");
      }
    return 0;
}
31. Write a program to find out if the computer is a little endian or big endian.

Little endian systems start storing the number from least significant byte. Big endian systems start storing number from most significant byte.

If the number is 10 which is 0x000A then Little endian system will store the number in the following way

 Address  1000  1001 1002  1003 
 Value       A     0     0     0 

But big endian systems store it as

 Address  1000  1001 1002 1003 
 Value       0     0     0     A 
Note that intel systems are Little Endian.

We can store a number 1 in an integer variable. And typecast its pointer ptr to character pointer. As a character pointer which increments in steps of 1 byte, we can find out whether the number 1 is stored in ptr or ptr+(size-1). If 1 is stored in ptr, the system is little endian. If it is stored in ptr+size-1, then the system is big-endian.

#include<stdio.h>
int main()
{
    int num=1;
    int sz = sizeof(num);
    char *ptr = (char*)#
    if(*ptr == 1)/* Stores the little end of the number first */
      printf("The system is little endian");
    else if(*(ptr+sz-1)==1)/* Stores the big end of the number first */
      printf("The system is big endian");
    return 0;
}
32. Write your own sqrt function to find square root of a number.

This algorithm uses successive approximation and uses binary search algorithm. Just like binary search algorithm, we set high and low and compare square of mid to n. And if mid squared is greater than n, we go to the left half by setting high = mid. If instead mid squared is less than n, we go to right half, by setting lo = mid. This process is continued until mid squared is equal to n (with a precision of 0.00001)

Also if the number is a perfect square the method checks integer multiplication of the square root by itself. e.g. if n is 16, the method returns 4.0 instead of 3.999997

#include<stdio.h>
double square_root(double value)
int main()
{
   int n;
   printf("Enter a number");
   scanf("%d",&n);
   double sr = square_root(n);
   printf("The square root of %d is %f\n",n,sr);
   return 0;
}
double square_root(double value)
{
     assert(value >= 1);
     double lo = 1.0;
     double hi = value;
     while( hi - lo > 0.00001)
     {
          double mid = lo + (hi - lo) / 2 ;
          int midint = mid;
          if(midint*midint==value)
                return (float)midint;
          if( mid * mid - value > 0.00001)    
          {
              hi = mid;
          } else {
              lo = mid;
          }
     }
    return lo;
 }
 
33. Write a function to count the number of set bits in a given number. e.g. 17 has 2 bits set. 15 has 4 bits set

  • If lsb is set then n&1 will be 1. If result is 1, we increment the count.
  • To test the next bit, we can shift the number to the right and then again bitwise AND the number with 1.
  • This process is continued number becomes 0 - by rotating all the bits all bits.

int num_set_bits(int n)
{
    int count = 0;
    while(n>0)
    {
        if (n&1==1)
            count++;
        n>>=1;
     }
     return count;
}

 
34. Write a program to print a n by n square divided into quadrants of stars, dots, dollars, and ohs. Take n as command line parameter

e.g. n as 8 produces
****....
****....
****....
****....
$$$$oooo
$$$$oooo
$$$$oooo
$$$$oooo
#include<stdio.h>
#include<stdlib.h>
void draw_quadrants(int num,char ch1,char ch2,char ch3, char ch4);
int main(int argc,char *argv[])
{

   char ch1='*',ch2='.',ch3='$',ch4='o';
   int n;
   if(argc<2)
     {
     printf("The syntax is drawsquares n");
     return 0;
     }
   n = atoi(argv[1]);/*n is first command line parameter*/
   draw_quadrants(n,ch1,ch2,ch3,ch4);
   return 0;
}

void draw_quadrants(int n,char ch1,char ch2,char ch3, char ch4)
{
    int i,j;
    for(i=1;i<=n/2;i++)
      {
          for(j=1;j<=n/2;j++)
              printf("%c",ch1);
          for(j=1;j<=n/2;j++)
             printf("%c",ch2);
          printf("\n");
      }
    for(i=1;i<=n/2;i++)
      {
          for(j=1;j<=n/2;j++)
              printf("%c",ch3);
          for(j=1;j<=n/2;j++)
              printf("%c",ch4);
           printf("\n");
      }
}
35. Write a program that prints 3 cycles of a cosine wave down the page.

cosine of an angle has a value between 0 and 1. So to plot this, we need to multiply the values by a factor say 20. Also to account for negative value, we must use an offset.

And do not forget to use the linker option while compiling this program.

gcc yourfile.c -lm
#include<stdio.h>
#include<math.h>
#define PI (22.0/7)
void draw_cosine();
int main()
{

    draw_cosine();
    return 0;
}
void draw_stars(int m)
{

   int i;
   if(m<0)
     for(i=0;i<20+m;i++)
       putchar(" ");
   else
     for(i=0;i<20;i++)
       putchar(" ");
   m = abs(m);
   while(m--)
     printf("*");
   printf("\n");
}
void draw_cosine()
{
    int i,j;
     for(i=0;i<3;i++)
       for(j=0;j<=360;j+=10)
       {
            float rad = j*PI/180;
            float y = cos(rad)*20;
            draw_stars(y);
        }
  }
 
36. If the number of bacteria in the container doubles itself everyday. Assuming that the container would be full on the 10th day with 13,312 bacteria, find the number of bacteria that was initially in the container on the first day.

#include<stdio.h>
#include<math.h>
int main()
{
int bact_count;
int num_day;
float initial;
printf("bact_count & num_day");
scanf("%d %d",&bact_count,&num_day);
initial = bact_count/pow(2, num_day);
printf("Initial number of bacteria %f",initial);
return 0;
}

37. Consider the following number 45*45=2025; 20+25=45.Write a program to generate number between 32 and 99 that satisfies the above property - that is the square of the number is equal to sum of first two and last two sub-numbers. .

#include<stdio.h>
int sumOfDigits(int num)
{
   int a = num%100;
   int b = num/100;
   return a+b;
}
int main()
{
  int i;
  for(i=31;i<=99;i++)
   {
     int square = i*i;
     int s = sumOfDigits(square);
     if(s==i)
        printf("%d   ",i);
   }
}

As we need a number whose square is four digit number, and as 30*30 is 900, we are starting from 31.

38. Write a program to find the sum of first 10 odd numbers.

#include<stdio.h>
int main()
{
   int s = 0;
   int i = 1;
   for(i=1;i<10*2;i+=2)
     s+=i;
   printf("%d",s);
   return 0;
}
39. Write a program to print the following pattern 1 22 333 4444 55555

#include<stdio.h>
int main()
{
    int i,j;
    for(i=1;i<=5;i++)
      {
       for(j=1;j<=i;j++)
          printf("%d",i);
       printf("\n");
     }
     return0;
}
40. Given two numbers, write a function to find if the first number is exact multiple of second number. Do not use loops.

If the first number a is exact multiple of second number b, then a would be divisible by b. And remainder when a is divided by b will be 0. So we can use modulo operator.
#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter two numbers");
    scanf("%d %d",&a,&b);
    if(a%b==0)
       printf("%d is a multiple of %d\n",a,b);
    else
     printf("%d is not a multiple of %d\n",a,b);  
    return 0;
}
41. Write a program to read 3 numbers and find out if all three are different.

#include<stdio.h>
int main()
{
   int a,b,c;
   printf("Enter three numbers:");
   scanf("%d %d %d",&a,&b,&c);
   if(a==b || a==c || b==c )
     printf("The numbers are repeated");
   else
     printf("They are all unique");
   return 0;
}
42. Write a function to read a set of numbers terminated by -1 and find the largest number. Do not use arrays

As we can't use arrays, we can't store the numbers. Let us initialize large with smallest integer INT_MIN. As and when we read a number, if the number is greater than large, we assign large to this new number.
#include<stdio.h>
#include<limits.h>
int largest()
{
   int large = INT_MIN;
   while(1)
   {
     int n;
     scanf("%d",&n);
     if(n==-1)
        break;
     if(n>large)
       large = n;
   } 
   return large;
}

int main()
{
   int l = largest();
   printf("The largest number entered is %d\n",l);
   return 0;
}
43. Write a program to print all factorial numbers less than or equal to the given number n

#include<stdio.h>
int factorial(int n)
{
   if(n<1)
     return 1;
   else
     return n*factorial(n-1);
}
int main()
{
   int a;int i=1;
   printf("Enter the number:");
   scanf("%d",&a);
   printf("Factorials are:");
   while(i<=a)
   {
       int f = factorial(i++);
       if(f<=a)
          printf("%d ",f);
       if(f>=a)
          break;
   }
   return 0;
}
     
44. Write a program to find the sum of the series 1+1/2+1/3+1/4+1/5....1/n. Value of n must be read from keyboard

#include<stdio.h>
float sumOfSeries(int n)
{
   float sum = 0;int i ;
   for(i=1;i<=n;i++)
       sum = sum + 1.0/i;
   return sum;
}
int main()
{
   int n;
   printf("n=");
   scanf("%d",&n);
   printf("Sum of series 1+1/2+1/3+...1/n for n=%d is %.2f\n",n,sumOfSeries(n));
   return 0;
}
45. Write a program to read 3 sides of a triangle and print its area and perimeter

#include<stdio.h>
#include<math.h>
int main()
{
   float a,b,c;
   double s,area;
   double perimeter;
   printf("Enter 3 sides of triangle:");
   scanf("%f %f %f",&a,&b,&c);
   s = (a+b+c)/2;
   area = sqrt(s*(s-a)*(s-b)*(s-c));
   perimeter = a+b+c;
   printf("Perimter is %f \nArea  is %.2lf\n",perimeter,area);
   return 0;
}
46. Write a program to read a point - x and y co-ordinates and determine which quadrant the point lies in.

#include<stdio.h>
int main()
{
   float x,y;
   printf("x =");
   scanf("%f",&x);
   printf("y =");
   scanf("%f",&y);
   if(x==0 && y==0)
      printf("the point is origin");
   else if(x==0)
      printf("the point is on Y axis");
   else if (y==0)
      printf("The point is on X axis");
   else if(x>0 && y>0)
        printf("The point is in first quadrant");
   else if(x>0 && y<0)
       printf("The point is in fourth quadrant");
   else if(x<0 && y<0)
       printf("The point is in  third quadrant");
   else  
        printf("The point is in second quadrant");
   return 0;
}
    
47. Write a program to print all factors of a given number.

#include<stdio.h>
void printFactors(int n)
{
   int i;
   printf("Factors of %d are:",n);
   for(i=1;i<=n/2;i++)
      if(n%i==0)
          printf("%d ",i);
  printf("%d\n",n);
}
int main()
{
   int n;
   printf("n=");
   scanf("%d",&n);
   printFactors(n);
   return 0;
}
48. Write a program to multiply a given number by 4 using bitwise operators

When a number is left shifted once, it is multiplied by 2. When it is left shifted twice, the number is multiplied by 4 and so on.

When the number is left shifted by i, it is multiplied by 2^i

In this program, we have to left shift the number twice to multiply it by 4.

#include<stdio.h>
int product(int n)
{
   return n<<2;
}
int main()
{
   int n;
   printf("n=");
   scanf("%d",&n);
   printf("%d multiplied by 4 is %d",n,product(n));
   return 0;
}
49. Write a program to implement power function for integer powers. The function must take x and y as parameters and return xy.

xy is x multiplied by itself y times.

And x-y is 1/xy

#include<stdio.h>
float power(int x,int y)
{
   int isNegativePower=0;
   int i;
   float product = 1;
   if(y<0)
   {
       isNegativePower = 1;
       y = -y;
   }
   for(i=1;i<=y;i++)
       product *=x;
   if(isNegativePower)
      product = 1 /product;
   return product;
}
int main()
{
   int x,y;
   printf("x =");
   scanf("%d",&x);
   printf("y =");
   scanf("%d",&y);
   printf("%d to the power of %d is %f\n",x,y,power(x,y));
   return 0;
}
50. Write a program to reverse the digits of a number

#include<stdio.h>
int reverse(int n)
{
   int s = 0;
   while(n)
   {
     int digit = n%10;
     s = s*10+digit;
     n /=10;
   }
   return s;

}
int main()
{
   int n;
   printf("n =");
   scanf("%d",&n); 
   printf("After reversing the digits of %d we get %d\n",n,reverse(n));
   return 0;
}
51. Write a function to calculate sum of numbers 1 to N using recursion

#include<stdio.h>

int sum(int n)
{
   if(n==1)
      return n;
   else 
     return n+sum(n-1);
}
int main()
{
  int n;
  printf("Enter a number");
  scanf("%d",&n); 
  printf("The sum of numbers from 1 to %d is %d\n",n,sum(n));
  return 0;
}
     
52. Write a program to read a number and print the number in octal and hexadecimal

No calculation is involved here. Format specifier %o prints the number in octal and format specifier %x prints the number in hexadecimal.

#include<stdio.h> 
int main()
{
  int n;
  printf("n=");
  scanf("%d",&n);
  printf("%d in octal is %o and in hexadecimal is %x",n,n,n);
  return 0;
}
53. What is main() function? How many main functions can be present in C program?

Main function is the starting point of execution of program. The program execution executes the main() function and program ends when main ends.

A C program should contain one main function.

main() function must return an integer which indicates the success of its execution - 0 to indicate success, non-zero to indicate error.

54. What are format specifiers?

Format specifiers are strings used to specify the type of values to be printed and how they should be printed.

  • %d is specifier for integer
  • %f is for float and double
  • %c is for characters etc.
e.g
printf("%d  %5d",m,n)

tells the system to print m and n as integers and also to print n with a width of 5.

Format specifiers also specify the type of values to be read in scanf.

e.g.
scanf("%d %f",&a,&b)
tells the system to read one integer and one float from console.

If a wrong format specifier is given, printf and scanf give garbage values.

55. Which are the shift operators in C? How are they used?

<< and >> are shift operators.

<< - left shift operator moves all the bits of a number to the left by given number of places.

e.g.

a = 10;
b = a<<2;

a is left shifted by 2 places.
a = 1010
a<<3 = 1010000 = 80

Left shifting a number is equivalent to multiplying the number by power of 2

10<<3 = 10 * 2^3

>> is right shift operator which moves the bits of a number to the right by given number of places.

a = 10;
b = a>>1;
which is 1010>>1 = 101 = 5

Right shifting a number is dividing a number by power of 2.

56. Explain bitwise operators in C.

C has the following bitwise operators.

  • | - bitwise OR
  • & - bitwise AND
  • ^ - bitwise EXOR
  • ~ - complement
These operators work on individual bits of the two operands.

e.g.
a = 10;
b = 2;
a & b = 1010 &0010 = 0010 = 2

a | b = 1010 | 0010 = 1010 = 10

a^b = 1010 ^ 0010 = 1000 = 8

~a = ~0010 = 1101 (if we consider only 4 bits)



Bitwise operators work only on int and char data types.

57. Which are assignment operators in C?

The assignment operators in C are

  1. =
  2. +=
  3. -=
  4. *=
  5. /=
  6. %=
  7. <<=
  8. >>=
  9. &=
  10. |=
  11. ^=
  12. These operators combine assignment with another operation.

    e.g. a+=b is same as a = a+b

    m<<=2 is same as m = m<<2

58. How do you define a boolean variable in C?

There is no boolean data type in C. But an integer value is used in logical expressions. And if value is 0, it is logical false. If the value is non-zero, it is true.

int isEven=0;
if (m%2==0)
     isEven=1;
We can even write the code as
 isOdd = 1;
if(m%2)
   isOdd = 0;
59. How do you specify width for value to printed for a) integers b)floats?

Format specifier can give width of the field along with %d for integers

e.g. %6d says that print integer with a width of 6 places.

For float we can specify the total width and width for decimal places.

printf("%9.2f",a)
says the system to print a with a total width of 9 and 2 decimal places.
printf("%.1f",b)

tells that print b with 1 decimal place.

60. What do the following format specifiers do?
%lf
%ld
%o
%x
%e
  • %lf is used as format specifier for double in scanf.
  • %ld is used to read a long integer value
  • %o is used to display an integer value in octal
  • %x is used to display an integer in hexadecimal
  • %e is used to display a float or a double value in exponential notation 1.2E3 = 1.2 * 10^3