Tuesday, 18 March 2014

Tricky Questions or Puzzles in C

1) WTAHT will be the output of the following Printf function.
  printf("%d",printf("%d",printf("%d",printf("%s","ILOVECPROGRAM"))));

Ans-ILOVECPROGRAM1321

The above printf line gives output like this because printf returns the number of character successfully written in the output.So the inner printf("%s","ILOVECPROGRAM") writes 13 characters to the output so the outer printf function will print 13 and as 13 is of 2 characters so the next outer printf function will print 2 and then next outer printf will print 1 as 2 is one character.So is the output 1321

2-Write code snippets to swap two variables in five different ways.
Answer:
a.      /* swapping using three variables*/ (Takes extra memory space)
Int a=5, b=10, c;
c=a;
a=b;
b=c;

b.      /* using arithmetic operators */
a=a+b;
b=a-b;
a=a-b;

c.       /* using bit-wise operators */
a=a^b;
b=b^a;
a=a^b;

Line
Operation
Value of a
Value of b

1
-
5
10
Initial values
2
a=a^b
15
10

3
b=a^a
15
5

4
a=a^b
10
5
values after swapping


d.      /* one line statement using bit-wise operators */ (most efficient)
a^=b^=a^=b;

The order of evaluation is from right to left. This is same as in approach (c) but the three statements are compounded into one statement.

e.       /* one line statement using arithmetic & assignment operators */
a=(a+b) - (b=a);
In the above axample, parenthesis operator enjoys the highest priority & the order of evaluation is from left to right. Hence (a+b) is evaluated first and replaced with 15. Then (b=a) is evaluated and the value of a is assigned to b, which is 5. Finally a is replaced with 15-5, i.e. 10. Now the two numbers are swapped.

3-  Find the maximum & minimum of two numbers in a single line without using any condition & loop.

Answer:
void main ()
{
int a=15, b=10;
printf (“ max = %d, min = %d”, ((a+b) + abs(a-b)) /2, ((a+b) – abs (a-b)) /2);
}
4.  How to print number from 1 to 100 without using conditional operators.

Answer:
void main ()
{
int  i=0;
while (100 – i++)
printf (“ %d”, i);
}
  1.     #include <stdio.h>
  2.     printf("%.0f", 2.89);
a. 2.890000
b. 2.89
c. 2
d.3 
 Answer
Answer:d
5-#include<stdio.h>
int main(){
    int i,j,k;
    for(i=0,j=2,k=1;i<=4;i++){
         printf("%d ",i+j+k);
    }
return 0;        
}

Output: 3 4 5 6 7

Sunday, 16 March 2014

c-loops

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
Loop Architecture
C programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Loop TypeDescription
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while loopLike a while statement, except that it tests the condition at the end of the loop body
nested loopsYou can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements. Click the following links to check their detail.
Control StatementDescription
break statementTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
goto statementTransfers control to the labeled statement. Though it is not advised to use goto statement in your program.

C - Decision Making

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages:
Decision making statements in C
C programming language assumes any non-zero and non-null values as true, and if it is either zero ornull, then it is assumed as false value.
C programming language provides following types of decision making statements. Click the following links to check their detail.
StatementDescription
if statementAn if statement consists of a boolean expression followed by one or more statements.
if...else statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
nested if statementsYou can use one if or else if statement inside another if or else if statement(s).
switch statementswitch statement allows a variable to be tested for equality against a list of values.
nested switch statementsYou can use one switch statement inside another switchstatement(s).

C - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators

    Arithmetic Operators

    Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:
    OperatorDescriptionExample
    +Adds two operandsA + B will give 30
    -Subtracts second operand from the firstA - B will give -10
    *Multiplies both operandsA * B will give 200
    /Divides numerator by de-numeratorB / A will give 2
    %Modulus Operator and remainder of after an integer divisionB % A will give 0
    ++Increments operator increases integer value by oneA++ will give 11
    --Decrements operator decreases integer value by oneA-- will give 9

    Relational Operators

    Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:
    OperatorDescriptionExample
    ==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
    !=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
    >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
    <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
    >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
    <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

    Logical Operators

    Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:
    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true

    Bitwise Operators

    Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011
    Assume if A = 60; and B = 13; now in binary format they will be as follows:
    A = 0011 1100
    B = 0000 1101
    -----------------
    A&B = 0000 1100
    A|B = 0011 1101
    A^B = 0011 0001
    ~A  = 1100 0011
  • The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:
    OperatorDescriptionExample
    &Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12, which is 0000 1100
    |Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61, which is 0011 1101
    ^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49, which is 0011 0001
    ~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -61, which is 1100 0011 in 2's complement form.
    <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

    Assignment Operators

    There are following assignment operators supported by C language:
    OperatorDescriptionExample
    =Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
    +=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
    -=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
    *=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
    /=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
    %=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
    <<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
    ^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
    |=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

    Misc Operators ↦ sizeof & ternary

    There are few other important operators including sizeof and ? : supported by C Language.
    OperatorDescriptionExample
    sizeof()Returns the size of an variable.sizeof(a), where a is integer, will return 4.
    &Returns the address of an variable.&a; will give actual address of the variable.
    *Pointer to a variable.*a; will pointer to a variable.
    ? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

    Operators Precedence in C

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
    For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
    Category Operator Associativity 
    Postfix () [] -> . ++ - -  Left to right 
    Unary + - ! ~ ++ - - (type)* & sizeof Right to left 
    Multiplicative  * / % Left to right 
    Additive  + - Left to right 
    Shift  << >> Left to right 
    Relational  < <= > >= Left to right 
    Equality  == != Left to right 
    Bitwise AND Left to right 
    Bitwise XOR Left to right 
    Bitwise OR Left to right 
    Logical AND && Left to right 
    Logical OR || Left to right 
    Conditional ?: Right to left 
    Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
    Comma Left to right 

C - Constants and Literals

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:
212         /* Legal */
215u        /* Legal */
0xFeeL      /* Legal */
078         /* Illegal: 8 is not an octal digit */
032UU       /* Illegal: cannot repeat a suffix */
Following are other examples of various type of Integer literals:
85         /* decimal */
0213       /* octal */
0x4b       /* hexadecimal */
30         /* int */
30u        /* unsigned int */
30l        /* long */
30ul       /* unsigned long */

Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals:
3.14159       /* Legal */
314159E-5L    /* Legal */
510E          /* Illegal: incomplete exponent */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or fraction */

Character constants

Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of chartype.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
There are certain characters in C when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:
Escape sequenceMeaning
\\\ character
\'' character
\"" character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\oooOctal number of one to three digits
\xhh . . .Hexadecimal number of one or more digits

String literals

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

Defining Constants

There are two simple ways in C to define constants:
  1. Using #define preprocessor.
  2. Using const keyword.

The #define Preprocessor

Following is the form to use #define preprocessor to define a constant:
#define identifier value

The const Keyword

You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
exm-const int  LENGTH = 10;