Cater you with knowledge7.

BT0067 C Programming and Data Structures Paper-2


  1. Differentiate string type and character type constants.

Individual character constants are represented by single-quotes, e.g. 'A', and have type int (in C++ char). The difference is that "A" represents a pointer to the first element of a null-terminated array, whereas 'A' directly represents the code value (65 if ASCII is used). The same backslash-escapes are supported as for strings, except that (of course) " can validly be used as a character without being escaped, whereas ' must now be escaped. A character constant cannot be empty (i.e. '' is invalid syntax), although a string may be (it still has the null terminating character). Multi-character constants (e.g. 'xy') are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult.

In C, string literals (constants) are surrounded by double quotes ("), e.g. "Hello world!" and are compiled to an array of the specified char values with an additional null terminating character (0-valued) code to mark the end of the string.String literals may not contain embedded newlines; this proscription somewhat simplifies parsing of the language. To include a newline in a string, the backslash escape \n may be used, as below.

2. Write an algorithm to find the bus fare based on distance traveled as per the following rates:

a. Rs.5.00 for first 2 kms.

b. Rs.2.50 for every additional 2 kms.

Draw a flowchart to find the fare.
3. Explain different iterative statements.

A C Program is made up of statements. Statement is a part of your program that can be executed. In other words every statement in your program alone or in combination specifies an action to performed by your program. C provides variety of statements to help you attain any function with maximum flexibility and efficency. One of the reason for popularity of C is because of the extreme power provided to programmer in C due to it rich and diverse set of statements define in C. For becoming a top notch programmer you must have clear understanding of the C statments and the situations where staments in C are applicable.

1. Types Of Statements
Staments in C are categorized into following types- 1. Selection/Conditional Statement - They decide the flow of statements on based on evaluation of results of conditons. if - else and switch statements come under this category. 2. Iteration Statements - These are used to run a particluar block statments repeatedly or in other words form a loop. for, while and do-while statements come under this category. 3. Jump Statements - The are used to make the flow of your statments from one point to another. break, continue, goto and return come under this category. 4. Label Statements - These are used as targets/waypoints for jump and selection statements. case (discussed with switch) and label (discussed with goto) come under this category 5. Expression Statements - Any valid expression makes an expression statement. 6. Block Statement - A group of staments which are binded together to form a logic are called block statemetns. Block statement begins with a { and ends with a }. Below we discuss each types of statements in detail with all thier variant forms.
Block Statements
2. if - else Statement if - else statement is a selection statement. It selects one piece of code for execution among two on basis of a outcome of a conditonal logic. The piece of code being refer here can be a s tament, a block statement or even a empty statement depending upon the logic of your program.
Conditon here evaluates to true or false ie. zero or non-zero in c respectively.It can be any valid data type which can be interpreted by C compiler as 1 or 0. If the code evaluates to be true the one assosiated with if is executed otherwise one associated with else is executed. Hence the if - else statment helps the programmer in controlling the flow of statements in his program. The important thing to note is code of if and else block are inversely related in logic ie. either code of if block or code of else block will be executed never both.
Also in a professionally written code if the variable alone is able to control the condtion using a comparison is considered a bad style. For example say i an integer variable can attain any value then this value can be directly interpreted as zero or non-zero and is sufficient to control the loop. In this case conditons like (i == 0) or (i != 0) are considered bad programming style and should be avoided.
Here is a code showing the if - else statement in action –
One property of if -else statement is that they can be nested. This means that if statement can be target of another if statement.
C89 specifies that compiler must support 15 levels of nesting and C -99 increase that number to 127 but in reality most compilers allow a large number of nesting much much greater than defined in C.
In a nested else statement is assosiate with nearest if statement. This association can be change by used of code block. Also you should use proper indenting in your program to make sure you remove any visual ambiguity/
Another popular variant of if-else statement is if-else ladder in this we create a series of generally one level deep. It has a special property that when any one of the condition statement is found to be true only statement associate with the if having that condition true is executed and all other statements in the ladder are by-passed. If none of the conditions evaluate to be true then the final statement associated with else is executed if present. Also it is recommended to use standard identation pattern.
Another option to if-else statement is ternary operator ? (Question Mark) discussed under Expressions.

3. switch Statement
switch is a selection statement provided by C. It has a buil in multiple - branch structure and work similar to if else ladder generally. The input value to to the switch statemetnt construct is a int or char variable. Note that no float or any other data is allowed. This input variable is compared against a group of integer constant. All the statments in and after the case in which thier is a match is executed until a break statement is encountered or end of switch is reached. We are also allowed to give a default case which will be executed if no other statement match is found. Also use of standard indenting is recommended.
    4. for Statement
for statement is one of the iteration statement provided by C. It is the most popular of all iteration statments because it provides unmatched flexiblity and power to the program.
Loops generated by for statement is are also called entry controlled or close ended because the condition for iteration of loop is check at the starting of the loop and loop will not execute even once if the conditon will to satisfy even once.
for statement declaration as shown above can be divided into 3 parts -
1. Intialization - In this we intialize the loop control value to a starting value. Also C99 like C++ permits the declaration of loop control variable whose scope is only the for block.
2. Condition - In this evaluate the condition for the iteration of the loop and loop repeat only when this is true.
3. Increment - In this we determine how the value of loop control value changes with each iteration of the loop. It can be increment, decrement or any mathematical expression.
Also statement in above form can be a single statement, block statement or a blank statement.

There are many variations or mutant forms of for loop which can be created enhancing the general for loops flexibility and power.
Multiple loop control variable - In this form more than 1 loop control variable is used to control the execution of loop. The multiple statements are combined together using comma operator. The possible use is shown in the following source code in which we generate numbers from 0 to 50 using two loop control Missing Parts - In a for statement declaration any or all of the three parts of the statement are optional and can be replaced by blank statements. Its show in the code be#include <stdio.h>
3.Infinite loop - In this a non - ending infinte loop is formed by removing all three parts of the for statement. This loop can only be stopped if a break statement is encountered inside the body of the loop. Infinite loop find use in many algorithms such as game programming engin#include <stdio.h>
  1. No Body Loop - In this variation the body of the loop does not exist. It maybe used in special circumstances such as in which body of loop is not needed. For example the code below shows a loop which moves the input string pointer to a character in the same string removing the unwanted intial white spaces.
Many new variations can be obtained by combining variations above. For loop is most widely use loop statement and its should be clear now why it is so.
5. while Statement
while is an iteration statement available in C. It is used to create loops. While produce entry controlled loops ie. loops in which condition check is performed at starting.
Above condition is any valid expression which evaluates to zero or non - zero and statement can be a single statement, block statement or empty statement. Also if you want to run loop forever you can write condition 1 and if you want it to never run you can write condition 0. While like for can be made without any bodies for specific purposes. Also unlike for the increment has to been inside the statement block and initalization outside the while statement block.

6. do - while Statment
do - while is also iteration statement provided by C. It is similar to while but has many diffrent properties. It is an exit controlled loop which means that condition for next loop iteration is checked at bottom of the loop. This makes sure that the do-while loop will run atleast once.Curly brackets are not required if statment is blank or single but they are recommended in every case to avoid confusion. Conditional as usual is vaild expression statement which evaluates to zero or non-zero. The loop will continue to run till the conditions evaluates to non - zero. As in while increment part should be contained inside loop and intialization should be outside loop. One the most important use of do-while is menus where you want menu to run atleast once and also until user chooses a valid choice.
7. return Statement
return is a jump statement in c. It is used to return from the executing function to the function which called this executing function. If encounter in main the program exits and return to the operating system or the source from which it was called from.
Return statement also has a special property that it can return a value with it to the calling function if the fuunction is declared non - void. Void functions are the one which are explicitly declared not to return a value and hence a return statement with value when encountered in such a function leads to an error by compiler. Also a function declared non-void should always return a value of the respective type. Some compiler allow a relaxation which could lead to severe problems, they return garbage value if a return statement containing the value is not found in the function. You should always make sure such a situation never happens.
8. goto Statement
goto statement is a jump staments and is perhaps the most controversial feature in C. Goto in unstructured language such as basic was indispensable and the soul of the programming lanugage but in a structured language they are critcized beyond limit. The critics say that due to other jump statements in c goto is not all required and more over it destoys the structure of your program and make it unreadable. But on other hand goto statement of C provides some very powerfull programming options in very compicated situation. This tutorial will take an neutral stand in such an argument and neither recommend nor discourage use of goto.
Goto is used for jumping from one point to another point in your function. You can not jump from one function to another. Jump points or way points for goto are marked by label statements. Label statement can be anywhere in the function above or below the goto statement. Special situation in which goto find use is deeply nested loops or if - else ladders.
9. break Statement
break statment is a jump statment in C and is generally used for breaking from a loop or breaking from a case as discussed in switch stament. Break statement when encountered within a loop immediately terminates the loop by passing condition check and execution transfer to the first statment after the loop. In case of switch it terminates the flow of control from one case to another.Also one important thing to remember about break is that it terminates only the innermost switch or loop construct in case of nested switch and loop variations.
10. continue Statement
continue is a jump statement provided by C. It is analogus to break statement. Unlike break which breaks the loop, continue stament forces the next execution of loop bypassing any code in between.For for staments it causes the conditional check and increment of loop variable, for while and do-while it passes the control to the conditon check jumping all the statements in between. Continue plays an important role in efficiently applying certain algorithms.
4. What is a macro? Explain with examples.
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls. You may define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords. This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it. An object-like macro is a simple identifier which will be replaced by a code fragment. It is called object-like because it looks like a data object in code that uses it. They are most commonly used to give symbolic names to numeric constants. You create macros with the `#define' directive. `#define' is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list. For example,
    #define BUFFER_SIZE 1024
defines a macro named BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after this `#define' directive there comes a C statement of the form
    foo = (char *) malloc (BUFFER_SIZE);
then the C preprocessor will recognize and expand the macro BUFFER_SIZE. The C compiler will see the same tokens as it would if you had written
    foo = (char *) malloc (1024);
You can also define macros whose use looks like a function call. These are called function-like macros. To define a function-like macro, you use the same `#define' directive, but you put a pair of parentheses immediately after the macro name. For example,
    #define lang_init()  c_init()
         ==> c_init()
A function-like macro is only expanded if its name appears with a pair of parentheses after it. If you write just the name, it is left alone. This can be useful when you have a function and a macro of the same name, and you wish to use the function sometimes.

5. What is a function? Explain with examples.
A function in C language is a block of code that performs a specific task. It has a name and it is reusable i.e. it can be executed from as many different parts in a C Program as required. It also optionally returns a value to the calling programEvery function has a unique name. This name is used to call function from “main()” function. A function can be called from within another function. A function is independent and it can perform its task without intervention from or interfering with other parts of the program. A function performs a specific task. A task is a distinct job that your program must perform as a part of its overall operation, such as adding two or more integer, sorting an array into numerical order, or calculating a cube root etc. A function returns a value to the calling program. This is optional and depends upon the task your function is going to accomplish. Suppose you want to just show few lines through function then it is not necessary to return a value. But if you are calculating area of rectangle and wanted to use result somewhere in program then you have to send back (return) value to the calling function.
    1. Structure of a Function

A general form of a C function looks like this:
<return type> FunctionName (Argument1, Argument2, Argument3……)

An example of function.

int sum (int x, int y)
int result;
result = x + y;
return (result);

6. Discuss bitwise operators.

There are three major bitwise operators that can be used to combine two numbers: AND, OR, and XOR. When I say that an operator is bitwise, it means that the operation is actually applied separately to each bit of the two values being combined. For example, if x = y AND z, that means that bit 0 of x is actually bit 0 of y ANDed with bit 0 of z. Make sense? Let's look at each operator in turn and see how they work. Once we've been through all of that, we'll be in a position to come up with some practical applications of each.
The AND Operator
There are two kinds of AND operators in the C language: the logical AND, and the bitwise AND. The former is represented by the && operator, and the latter uses the & operator. You've probably seen the first one numerous times, as it's often used in if statements. Here's an example of the logical AND in action:
if ((x == 5) && (y == 7))
In this case, you would expect that the function will only be called if x is 5 and y is 7. The bitwise AND works very much the same way, except that it works with two bits instead of two expressions. The bitwise AND operation returns 1 if and only if both of its operands are equal to 1. In other words, we have the following truth table for the bitwise AND:
0 AND 0 = 0

0 AND 1 = 0
x AND 0 = 0
1 AND 0 = 0
x AND 1 = x
1 AND 1 = 1

The first column shows the result of a bitwise AND when combining explicitly defined bits. But it's the second column that's interesting. It says that if you AND any bit with 0, the result is 0; and if you AND any bit with 1, the result is the original bit. This little piece of information will be the key to making the bitwise AND work for us later, so keep it in mind. To finish up, let's see an example of combining two words using the bitwise AND operator:
 0110 1011 1000 0101
& 0001 1111 1011 1001
 0000 1011 1000 0001
Do you see why we get the result we do? There is a 1 in the result only in the positions where the corresponding bits in both operands are also equal to 1. That's all there is to the bitwise AND operation. Let's move on.
    1. The OR Operator

Just as with the AND operation, there are two different types of OR in the C language. The logical OR uses the || operator, and the bitwise OR uses the | operator. A use of the logical OR might look something like this:
if ((x == 5) || (y == 7))
In this example, the function will be called if x is 5, if y is 7, or both. The only way the function is not called is if both of the conditions are false. The bitwise OR is very similar, in that it returns 0 if and only if both of its operands are 0. To illustrate this, we have the following truth table:
0 OR 0 = 0

0 OR 1 = 1
x OR 0 = x
1 OR 0 = 1
x OR 1 = 1
1 OR 1 = 1

Once again, the second column is the interesting one. Note that whenever you OR a bit with 0, the result is the original bit, and whenever you OR a bit with 1, the result will always be 1. This will be the key to using OR effectively a little later on. For now, let's just look at an example of using the bitwise OR operation on two words:
 0110 1011 1000 0101
| 0001 1111 1011 1001
 0111 1111 1011 1101
Here you can see that the result contains a 0 only when the corresponding bits in both of the operands are also 0. Now we've got just one more combinational operator to look at, and that's XOR.
    1. The XOR Operator

The XOR is a little strange because there is no logical equivalent for it in C, even though many languages include one. The XOR operation is symbolized by the ^ character in C. The term XOR stands for "exclusive OR," and means "one or the other, but not both." In other words, XOR returns 1 if and only if exactly one of its operands is 1. If both operands are 0, or both are 1, then XOR returns 0. To see this, take a look at the truth table for XOR:
0 XOR 0 = 0

0 XOR 1 = 1
x XOR 0 = x
1 XOR 0 = 1
x XOR 1 = ~x
1 XOR 1 = 0

The truth table here is interesting. Note from the first column that anything XORed with itself returns 0. This fact will lead to an interesting application of XOR later on. In the second column, we see that any bit XORed with 0 yields the original bit, and any bit XORed with 1 yields the complement of the original bit. This is something you may not have seen before: the bitwise NOT. It is a unary operator, meaning that it only takes one operand, like a negative sign. A bitwise NOT simply inverts all the bits in its operand, meaning that all 0s are changed to 1s, and vice versa. Now, let's take a look at an example of using XOR on two words:
 0110 1011 1000 0101
^ 0001 1111 1011 1001
 0111 0100 0011 1100
So there you have it, the last of the combinational operators, plus the only unary bitwise operator, the NOT. Before we can look at any applications of these, there is one other class of bitwise operator I need to show you, called shifts. Don't worry, this will go pretty quickly, and then we can get on to the interesting stuff.

7. Write an algorithm to find all numbers which are divisible by 3 but not divisible by 6 and draw a flowchart.

1) Get the minimum number
2) get the maximum number
3) start at the minimum number
4) is it divisible by three but not by six?
If yes, jump to step 5
If no, increment by 1 and repeat step 4

5) output the current number
6) increment the number by six
7)is it greater than or equal to our maximum number?
if yes, end the program
if no, jump to step 5

8. Differentiate switch statement and nested if statement.
At the code phase, the "switch" statement is used when you need to "select" between one or more decisions according to a "completely defined control signal". The "If, else" statement is much more appropriate for logic and boolean comparisons rather than equality.

At the compilation phase, the "if" statement is converted to some sort of "load, compare, and jump" instructions, while the "switch" statement is converted to a hash table, thus it should be faster than the "if, else" statement for long list of comparisons, since it will point and jump directly to the part of code to get executed.

Nested if-else statements are used in the program's logic where there isn't only one condition to evaluate. A switch statement, on the other hand, evaluates only one variable and starts to work there. You can think of a switch statement as a simplified (and stripped-down) version of an if-else block.

switch(x) {
case 1: // do this
case 2: // do this
case 3: // do this
// etc

The nested if-else statement's power comes from the fact that it is able to evaluate more than one condition at once, and/or use lots of different conditions in one logical structure.

if(x == 0) {
// do this
} else if(y == 1) {
// do this
} else if(x == 1 && y == 0) {
// do this

If you're going to evaluate only one variable in the condition statement, you're better off going with a switch statement, since it looks a lot neater than nested ifs. However, like in the case above, there are times where the only structure you could use is an if-else block, so you don't have much of a choice.

9. What is an array? Explain with examples.
The C language provides a capability that enables the user to define a set of ordered data items known as an array.Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades, we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number.
In C we can define variable called grades, which represents not a single value of grade but a entire set of grades. Each element of the set can then be referenced by means of a number called as index number or subscript.
/* Program to count the no of positive and negative numbers*/
#include< stdio.h >
void main( )
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the array\n”);
printf(“Enter the elements of the array\n”);
for I=0;I < n;I++)
for(I=0;I < n;I++)
if(a[I] < 0)
printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);

10. Differentiate iteration and recursion
In Iteration, we specifically run a loop, such that, the second run of the loop makes use of the computation/result from the first run, the third run (or iteration) makes use of the result from the second run and so on. Hence, in Iteration, the n th run of the loop makes use of the result from the n-1 th run.
   Consider the following example for calculating the summation, which we will denote as sum(n), meaning n + n-1 + n-2 + n-3 + ... + 2 + 1 + 0. Hence, sum(5) = 5+4+3+2+1+0 = 15.

 #  When a recursive call is made, the method/process copies or clones itself, making new copy of:

                       * the code
                       * the local variables (with their initial values),
                       * the parameters

         # Each copy of the code includes a marker indicating the current position. When a recursive call is made, the marker in the old copy of the code is just after the call; the marker in the "cloned" copy is at the beginning of the method.
         # When the method returns, that clone goes away, but the previous ones are still there, and know what to execute next because their current position in the code was saved

Now this involves a great overhead in terms of space and as well as in time also as each function call takes extra time.

2. Iteration : there is no recursive call involved that saves a lot of time and space too as no extra space is needed to store each copy generated in recursion.

 Iterative codes usually refers to codes that contain explicit iteration processes, that is, loops.

 A loop must have some sort of stopping criterion. Usually it is of one of two type:

  1. predetermined number of iterations through the loop;
  2. an error tolerance that is achieved.

Popular Posts


Blog Archive

Scroll To Top