BCA – I Sem.
BCA Examination, Dec 2017
Programming Principles and Algorithm
(BCA-102)
Solved Questions
Q1 What is C Language? Define the History of C Language.Answer : C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. Although C was designed for implementing system software, it is also widely used for developing portable application software. C is one of the most widely used programming languages of all time and there are very few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which began as an extension to C.
C History
Developed between 1969 and 1973 along with Unix Due mostly to Dennis Ritchie
Designed for systems programming 1)Operating systems
2)Utility programs 3)Compilers 4)Filters
Original machine (DEC PDP-11) was very small
1)24K bytes of memory, 12K used for operating system 2)Written when computers were big, capital equipment 3)Group would get one, develop new language, OS
Q2 What are the Characteristics of C ? Define the C program structure. Answer: Characteristics of C
1)Small size
2)Extensive use of function calls 3)Loose typing -- unlike PASCAL 4)Structured language
5) Low level (BitWise) programming readily available
6)Pointer implementation - extensive use of pointers for memory, array, structures and functions.
C Program Structure
A C program basically has the following form: 1)Preprocessor Commands
2)Type definitions
3)Function prototypes -- declare function types and variables passed to function. 4) Variables
5)Functions
We must have a main() function.
Q3 What does static variable mean? Answer : There are 3 main uses for the static.
1. If you declare within a function: It retains the value between function calls
2. If it is declared for a function name: By default function is extern..so it will be visible from other files if the function declaration is as static..it is invisible for the outer files
3. Static for global variables: By default we can use the global variables from outside files If it is static global..that variable is limited to with in the file.
#include int t = 10; main(){ int x = 0; void funct1(); funct1();
printf("After first call \n"); funct1();
printf("After second call \n"); funct1();
printf("After third call \n"); } void funct1() { static int y = 0; int z = 10; printf("value of y %d z %d",y,z);
y=y+10; }
value of y 0 z 10 After first call value of y 10 z 10 After second call value of y 20 z 10 After third call
Q4 Define Pre processor in C ?
Answer: The preprocessor is used to modify your program according to the preprocessor directives in your source code.
Preprocessor directives (such as #define) give the preprocessor specific instructions on how to modify your source code. The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code.
This preprocessed version has all of its macros and constant symbols replaced by their corresponding code and value assignments. If your source code contains any conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.
The preprocessor contains many features that are powerful to use, such as creating macros, performing conditional compilation, inserting predefined environment variables into your code, and turning compiler features on and off.
Q5 What are Variables in C Language? Do Variables need to be initialized?
Answer: Variables can be stored in several places in memory, depending on their lifetime. Variables that are defined outside any function (whether of global or file static scope), and variables that are defined inside a function as static variables, exist for the lifetime of the program's execution. These variables are stored in the "data segment." The data segment is a fixed-size area in memory set aside for these variables. The data segment is subdivided into two parts, one for initialized variables and another for uninitialized variables. Variables that are defined inside a function as auto variables (that are not defined with the keyword static) come into existence when the program begins executing the block of code (delimited by curly braces {}) containing them, and they cease to exist when the program leaves that block of code.
Variables that are the arguments to functions exist only during the call to that function. These variables are stored on the "stack". The stack is an area of memory that starts out small and grows automatically up to some predefined limit. In DOS and other systems without virtual memory, the limit is set either when the program is compiled or when it begins executing. In UNIX and other systems with virtual memory, the limit is set by the system, and it is usually so large that it can be ignored by the programmer.
The third and final area doesn't actually store variables but can be used to store data pointed to by variables. Pointer variables that are assigned to the result of a call to the malloc() function contain the address of a dynamically allocated area of memory. This memory is in an area called the "heap." The heap is another area that starts out small and grows, but it grows only when the programmer explicitly calls malloc() or other memory allocation functions, such as calloc(). The heap can share a memory segment with either the data segment or the stack, or it can have its own segment. It all depends on the compiler options and
operating system. The heap, like the stack, has a limit on how much it can grow, and the same rules apply as to how that limit is determined.
Do Variables need to be initialized?
No. All variables should be given a value before they are used, and a good compiler will help you find variables that are used before they are set to a value. Variables need not be initialized, however. Variables defined outside a function or defined inside a function with the static keyword are already initialized to 0 for you if you do not explicitly initialize them.
Automatic variables are variables defined inside a function or block of code without the static keyword. These variables have undefined values if you don't explicitly initialize them. If you don't initialize an automatic variable, you must make sure you assign to it before using the value.
Q6 What is a token?
Answer : A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.
Q7 What is variable initialization and why is it important?
Answer : This refers to the process wherein a variable is assigned an initial value before it is used in the program. Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.
Q8 Compare and contrast compilers from interpreters.
Answer : Compilers and interpreters often deal with how program codes are executed. Interpreters execute program codes one line at a time, while compilers take the program as a whole and convert it into object code, before executing it. The key difference here is that in the case of interpreters, a program may
encounter syntax errors in the middle of execution, and will stop from there. On the other hand, compilers check the syntax of the entire program and will only proceed to execution when no syntax errors are found. Q9 What are header files and what are its uses in C programming?
Answer : Header files are also known as library files. They contain two essential things: the definitions and prototypes of functions being used in a program. Simply put, commands that you use in C programming are actually functions that are defined from within each header files. Each header file contains a set of functions.
For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.
Q10 What are variables and it what way is it different from constants?
Answer : Variables and constants may at first look similar in a sense that both are identifiers made up of one character or more characters (letters, numbers and a few allowable symbols). Both will also hold a particular value. Values held by a variable can be altered throughout the program, and can be used in most operations and computations. Constants are given values at one time only, placed at the beginning of a program. This value is not altered in the program. For example, you can assigned a constant named PI and give it a value 3.1415 . You can then use it as PI in the program, instead of having to write 3.1415 each time you need it. Q11 Why is it that not all header files are declared in every C program?
Answer : The choice of declaring a header file at the top of each C program would depend on what commands/functions you will be using in that program. Since each header file contains different function definitions and prototype, you would be using only those header files that would contain the functions you will need. Declaring all header files in every program would only increase the overall file size and load of the program, and is not considered a good programming style.
Q12 When is the “void” keyword used in a function?
Answer : When declaring functions, you will decide whether that function would be returning a value or not. If that function will not return a value, such as when the purpose of a function is to display some outputs on the screen, then “void” is to be placed at the leftmost part of the function header. When a return value is expected after the function execution, the data type of the return value is placed instead of “void”. Q13 What are compound statements?
Answer : Compound statements are made up of two or more program statements that are executed together. This usually occurs while handling conditions wherein a series of statements are executed when a TRUE or FALSE is evaluated. Compound statements can also be executed within a loop. Curly brackets { } are placed before and after compound statements.
Q 14 What is the significance of an algorithm to C programming?
Answer : Before a program can be written, an algorithm has to be created first. An algorithm provides a step by step procedure on how a solution can be derived. It also acts as a blueprint on how a program will start and end, including what process and computations are involved.
Q15 What are comments and how do you insert it in a C program?
Answer : Comments are a great way to put some remarks or description in a program. It can serves as a reminder on what the program is all about, or a description on why a certain code or function was placed there in the first place. Comments begin with /* and ended by */ characters. Comments can be a single line, or can even span several lines. It can be placed anywhere in the program.
Q16 What is debugging? Is it possible to create your own header files?
Answer : Debugging is the process of identifying errors within a program. During program compilation, errors that are found will stop the program from executing completely. At this state, the programmer would look into the possible portions where the error occurred. Debugging ensures the removal of errors, and plays an important role in ensuring that the expected program output is met.
Yes, it is possible to create a customized header file. Just include in it the function prototypes that you want to use in your program, and use the #include directive followed by the name of your header file.
Q17 What are logical errors and how does it differ from syntax errors?
Answer : Program that contains logical errors tend to pass the compilation process, but the resulting output may not be the expected one. This happens when a wrong formula was inserted into the code, or a wrong sequence of commands was performed. Syntax errors, on the other hand, deal with incorrect commands that are misspelled or not recognized by the compiler.
Q18 What are the different types of control structures in programming?
Answer : There are 3 main control structures in programming: Sequence, Selection and Repetition. Sequential control follows a top to bottom flow in executing a program, such that step 1 is first perform, followed by step 2, all the way until the last step is performed. Selection deals with conditional statements, which mean codes are executed depending on the evaluation of conditions as being TRUE or FALSE. This also means that not all codes may be executed, and there are alternative flows within. Repetitions are also known as loop structures, and will repeat one or two program statements set by a counter.
Q19 Describe the order of precedence with regards to operators in C.
Answer : Order of precedence determines which operation must first take place in an operation statement or conditional statement. On the top most level of precedence are the unary operators !, +, – and &. It is followed by the regular mathematical operators (*, / and modulus % first, followed by + and -). Next in line are the relational operators <, <=, >= and >. This is then followed by the two equality operators == and !=. The logical operators && and || are next evaluated. On the last level is the assignment operator =.
Q20 Why is C language being considered a middle level language?
Answer : This is because C language is rich in features that make it behave like a high level language while at the same time can interact with hardware using low level methods. The use of a well structured approach to programming, coupled with English-like words used in functions, makes it act as a high level language. On the other hand, C can directly access memory structures similar to assembly language routines. Q21 What are the different file extensions involved when programming in C?
Answer : Source codes in C are saved with .C file extension. Header files or library files have the .H file extension. Every time a program source code is successfully compiled, it creates an .OBJ object file, and an executable .EXE file.
Q22 What is the difference between the expression “++a” and “a++”?
Answer : In the first expression, the increment would happen first on variable a, and the resulting value will be the one to be used. This is also known as a prefix increment. In the second expression, the current value of variable a would the one to be used in an operation, before the value of a itself is incremented. This is also known as postfix increment.
Q23 What is a program flowchart and how does it help in writing a program?
Answer : A flowchart provides a visual representation of the step by step procedure towards solving a given problem. Flowcharts are made of symbols, with each symbol in the form of different shapes. Each shape may represent a particular entity within the entire program structure, such as a process, a condition, or even an input/output phase.
Q24 What is a newline escape sequence?
Answer : A newline escape sequence is represented by the \n character. This is used to insert a new line when displaying data in the output screen. More spaces can be added by inserting more \n characters. For example, \n\n would insert two spaces. A newline escape sequence can be placed before the actual output expression or after.
Q25 What is the difference between functions getch() and getche()?
Answer : Both functions will accept a character input value from the user. When using getch(), the key that was pressed will not appear on the screen, and is automatically captured and assigned to a variable. When using getche(), the key that was pressed by the user will appear on the screen, while at the same time being assigned to a variable.
Q26 What are Character Set in C Language? Answer :
Character:- It denotes any alphabet, digit or special symbol used to represent information.
Use:- These characters can be combined to form variables. C uses constants, variables, operators, keywords and expressions as building blocks to form a basic C program.
Character set:- The character set is the fundamental raw material of any language and they are used to represent information. Like natural languages, computer language will also have well defined character set, which is useful to build the programs.
The characters in C are grouped into the following two categories: 1. Source character set
a. Alphabets b. Digits
d. White Spaces 2. Execution character set
a. Escape Sequence Source character set
ALPHABETS
Uppercase letters A-Z Lowercase letters a-z
DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 SPECIAL CHARACTERS
~ tilde % percent sign | vertical bar @ at symbol + plus sign < less than
_ underscore - minus sign > greater
than ^ caret # number sign = equal to
& ampersand $ dollar sign / slash ( left parenthesis * asterisk \ back slash
) right parenthesis ′ apostrophe : colon [ left bracket " quotation mark ; semicolon
] right bracket ! exclamation mark , comma { left flower brace ? Question mark . dot operator
} right flower brace WHITESPACE CHARACTERS
\b blank space \t horizontal tab \v vertical tab \r carriage return \f form feed \n new line
\\ Back slash \’ Single quote \" Double quote \? Question mark \0 Null \a Alarm (bell)
Execution Character Set
Certain ASCII characters are unprintable, which means they are not displayed on the screen or printer. Those characters perform other functions aside from displaying text. Examples are backspacing, moving to a newline, or ringing a bell.
They are used in output statements. Escape sequence usually consists of a backslash and a letter or a
These are employed at the time of execution of the program. Execution characters set are always represented by a backslash (\) followed by a character. Note that each one of character constants represents one
character, although they consist of two characters. These characters combinations are called as escape sequence.
Backslash character constants
Character ASCII value Escape Sequence Result Null 000 \0 Null Alarm (bell) 007 \a Beep Sound
Back space 008 \b Moves previous position Horizontal tab 009 \t Moves next horizontal tab New line 010 \n Moves next Line
Vertical tab 011 \v Moves next vertical tab
Form feed 012 \f Moves initial position of next page Carriage return 013 \r Moves beginning of the line
Double quote 034 \" Present Double quotes Single quote 039 \' Present Apostrophe Question mark 063 \? Present Question Mark Back slash 092 \\ Present back slash Octal number \000
Hexadecimal number \x
Q 27 Define Keywords in C language.
Answer : C programs are constructed from a set of reserved words which provide control and from libraries
which perform special functions. The basic instructions are built up using a reserved set of words, such as main, for, if, while, default, double, extern, for, and int, etc., C demands that they are used only for giving commands or making statements. You cannot use default, for example, as the name of a variable. An attempt to do so will result in a compilation error.
Keywords have standard, predefined meanings in C. These keywords can be used only for their intended purpose; they cannot be used as programmer-defined identifiers. Keywords are an essential part of a
language definition. They implement specific features of the language. Every C word is classified as either a keyword or an identifier. A keyword is a sequence of characters that the C compiler readily accepts and recognizes while being used in a program. Note that the keywords are all lowercase. Since uppercase and lowercase characters are not equivalent, it is possible to utilize an uppercase keyword as an identifier.
The keywords are also called ‘Reserved words’.
Keywords are the words whose meaning has already been explained to the C compiler and their meanings cannot be changed.
Keywords serve as basic building blocks for program statements. Keywords can be used only for their intended purpose.
Keywords cannot be used as user-defined variables. All keywords must be written in lowercase.
32 keywords available in C.
Data types Qualifiers User-defined Storage classes Loop Others int signed typedef auto for const char unsigned enum extern while volatile float short register do sizeof double long static
Decision Jump Derived function if goto struct void else continue union return switch break case default
Restrictions apply to keywords
Keywords are the words whose meaning has already been explained to the C compiler and their meanings cannot be changed.
Keywords can be used only for their intended purpose. Keywords cannot be used as user-defined variables. All keywords must be written in lowercase.
int Specifies the integer type of value a variable will hold char Specifies the character type of value a variable will hold
float Specifies the single-precision floating-point of value a variable will hold double Specifies the double-precision floating-point type of value a variable will Qualifier Keywords
signed Specifies a variable can hold positive and negative integer type of data unsigned Specifies a variable can hold only the positive integer type of data short Specifies a variable can hold fairly small integer type of data long Specifies a variable can hold fairly large integer type of data Loop Control Structure Keywords
For Loop is used when the number of passes is known in advance While Loop is used when the number of passes is not known in advance Do Loop is used to handle menu-driven programs
User-defined type Keywords
typedef Used to define a new name for an existing data type
Enum Gives an opportunity to invent own data type and define what values the variable of this data type can take
Jumping Control Keywords
Break Used to force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop
continue Used to take the control to the beginning of the loop bypassing the statements inside the loop Goto Used to take the control to required place in the program
Storage Class Keywords
Storage Classes Storage Default initial value Scope Life
auto Memory An unpredictable value Local Till the control remains within the block
register CPU registers Garbage value Local Till the control remains within the block
static Memory Zero Local Value of the variable persists between different function calls
extern Memory Zero Global Till the program’s execution doesn’t come to an end
Q 28 Define Data types in C Language.
Answer : Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we use in our program. These datatypes have different storage capacities.
C language supports 2 different type of data types,
Primary data types
These are fundamental data types in C namely integer(int), floating(float), character(char) and void.
Derived data types
Derived data types are like array, function, stucture, union and pointer.
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647 unsigned long int 4 0 to 4,294,967,295
Floating type
Floating types are used to store real numbers. Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
Float 4 3.4E-38 to 3.4E+38 double 8 1.7E-308 to 1.7E+308 long double 10 3.4E-4932 to 1.1E+4932
Character type
Character types are used to store characters value. Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
void type
void type means no value. This is usually used to specify the type of functions.
Q 29 What is C Identifiers? Define the rules for writing an identifier.
Answer : Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique. They are created to give unique name to a entity to identify it during the execution of the program. For example:
int money;
double accountBalance;
Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a keyword.
Rules for writing an identifier
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2. The first letter of an identifier should be either a letter or an underscore. However, it is discouraged to start an identifier name with an underscore.
3. There is no rule on length of an identifier. However, the first 31 characters of identifiers are discriminated by the compiler.
Q 30 Define Operators in C language.
Answer C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to perform certain mathematical or logical manipulations. Operators are used in program to manipulate data and variables.
C operators can be classified into following types, Arithmetic operators Relation operators Logical operators Bitwise operators Assignment operators Conditional operators Special operators Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators.
Operator Description
+ adds two operands
- subtract second operands from first * multiply two operand
/ divide numerator by denominator % remainder of division
++ Increment operator - increases integer value by one -- Decrement operator - decreases integer value by one
Relation operators
The following table shows all relation operators supported by C.
Operator Description
== Check if two operand are equal != Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right < Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand <= Check if operand on left is smaller than or equal to right operand
Logical operators
C language supports following 3 logical operators. Suppose a=1 and b=0,
Operator Description Example
&& Logical AND (a && b) is false || Logical OR (a || b) is true ! Logical NOT (!a) is false
Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits from right to left. Bitwise operators are not applied to float or double.
Operator Description
& Bitwise AND | Bitwise OR
^ Bitwise exclusive OR << left shift
>> right shift
Now lets see truth table for bitwise &, | and ^ a b a & b a | b a ^ b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the right operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the same precedence.
Assignment Operators
Assignment operators supported by C language are as follows.
Operator Description Example
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b -= subtracts right operand from the left operand and assign the result to left
operand
a-=b is same as a=a-b *= mutiply left operand with the right operand and assign the result to left
operand
a*=b is same as a=a*b /= divides left operand with the right operand and assign the result to left operand a/=b is same as a=a/b %= calculate modulus using two operands and assign the result to left operand a%=b is same as
a=a%b
Conditional operator
The conditional operator in C is called by two more names 1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language, but using conditional operator, we turn if condition statement into more simple line of code conveying the same thing.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3
Explanation-
The question mark "?" in the syntax represents the if part.
The first expression (expression 1) is use to check true or false condition only.
If that condition (expression 1) is true then the expression on the left side of " : " i.e expression 2 is executed.
If that condition (expression 1) is false then the expression on the right side of " : " i.e expression 3 is executed.
Special operator
Operator Description Example
sizeof Returns the size of an variable sizeof(x) return size of the variable x & Returns the address of an variable &x ; return address of the variable x * Pointer to a variable *x ; will be pointer to a variable x
Q31 What is gets() function?
Answer :The gets() function allows a full line data entry from the user. When the user presses the enter key to end the input, the entire line of characters is stored to a string variable. Note that the enter key is not included in the variable, but instead a null terminator \0 is placed after the last character.
Q32 What is the use of a semicolon (;) at the end of every program statement?
Answer : It has to do with the parsing process and compilation of the code. A semicolon acts as a delimiter, so that the compiler knows where each statement ends, and can proceed to divide the statement into smaller elements for syntax checking.
Q33 What is the difference between printf() and scanf()? Answer: printf():
When printf() is used in a progam,that means whatever statement we want to print on the shell will be written inside the double codes i.e printf(“hello”).
If we write printf(“Hello\n”) then \n means when Hello is printed on the shell then cursor will move to the very next line of the shell.
Another eg is if we have already assigned a value to a variable i.e int a=7,and we want to printf the value of a using printf(),we will write as printf(“value of a=%d”,a); Here %d means assigning the very next integer.And it will print as “value of a=7″ on the shell.And there is no need to give the address.
printf() returns the number of bytes written succesfully. scanf():
If we want that the user will enter some value then we use scanf().For eg scanf(“%d”,&a),here address is given in the scanf() so that some address is allocated to the integer.
scanf() does not return anything.
Q 34 What is the difference between getchar() and putchar()? Answer: getchar() reads a character from stdin.
putchar(int input) prints a character to stdout.
Q35 What does the format %10.2 mean when included in a printf statement?
Answer : This format is used for two things: to set the number of spaces allotted for the output number and to set the number of decimal places. The number before the decimal point is for the allotted space, in this case it would allot 10 spaces for the output number. If the number of space occupied by the output number is less than 10, addition space characters will be inserted before the actual output number. The number after the decimal point sets the number of decimal places, in this case, it’s 2 decimal spaces.
Q36 What is if statement?
Answer : This is the most simple form of the branching statements.
It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
NOTE: Expression will be assumed to be true if its evaulated values is non-zero. if statements take the following form:
Example if (expression) statement; or if (expression) { Block of statements; } or if (expression) { Block of statements; } else { Block of statements; } or if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; }
Q 37 : What are statements in C Language?
Answer :The statements which are used to execute only specific block of statements in a series of blocks are called case control statements.
There are 4 types of case control statements in C language. They are, 1. switch
2. break 3. continue 4. goto
1. switch case statement in C:
Switch case statements are used to execute only specific case statements based on the switch expression.
Below is the syntax for switch case statement. switch (expression)
{
case label1: statements; break; case label2: statements; break; case label3: statements; break; default: statements; break; }
Example program for switch..case statement in C:
C 1 2 3 4 5 6 7 8 9 10 #include <stdio.h> int main () { int value = 3; switch(value) { case 1: printf(“Value is 1 \n” ); break;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 case 2: printf(“Value is 2 \n” ); break; case 3: printf(“Value is 3 \n” ); break; case 4: printf(“Value is 4 \n” ); break; default :
printf(“Value is other than 1,2,3,4 \n” ); } return 0; } Output: Value is 3 2. break statement in C:
Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent execution.
Syntax: break;
Example program for break statement in C:
C #include <stdio.h> int main() { int i; 1 2 3 4 #include <stdio.h> int main() { int i;
5 6 7 8 9 10 11 12 13 14 15 for(i=0;i<10;i++) { if(i==5) {
printf("\nComing out of for loop when i = 5"); break; } printf("%d ",i); } } Output: 0 1 2 3 4
Coming out of for loop when i = 5
3. Continue statement in C:
Continue statement is used to continue the next iteration of for loop, while loop and do-while loops. So, the remaining statements are skipped within the loop for that particular iteration.
Syntax : continue;
Example program for continue statement in C:
C #include <stdio.h> int main() { int i; 1 2 3 #include <stdio.h> int main() {
4 5 6 7 8 9 10 11 12 13 14 15 int i; for(i=0;i<10;i++) { if(i==5 || i==6) {
printf("\nSkipping %d from display using " \ "continue statement \n",i);
continue; } printf("%d ",i); } } Output: 0 1 2 3 4
Skipping 5 from display using continue statement Skipping 6 from display using continue statement 7 8 9
4. goto statement in C:
goto statements is used to transfer the normal flow of a program to the specified label in the program. Below is the syntax for goto statement in C.
{ ……. go to label; ……. ……. LABEL: statements; }
Example program for goto statement in C: C #include <stdio.h> int main() { int i; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5) {
printf("\nWe are using goto statement when i = 5"); goto HAI;
}
printf("%d ",i); }
HAI : printf("\nNow, we are inside label name \"hai\" \n"); }
Output:
0 1 2 3 4
We are using goto statement when i = 5 Now, we are inside label name “hai”
Q 38 What is the equivalent code of the following statement in WHILE LOOP format? [c]
for (a=1; a<=100; a++) printf ("%d\n", a * a); [/c] Answer:[c] a=1; while (a<=100) { printf ("%d\n", a * a); a++; } [/c] Q 39 What is typecasting?
Answer : Typecasting is a way to convert a variable/constant from one type to another type. Q40 What will be output of following c code?
#include<stdio.h> externint x; int main(){ do{ do{ printf("%o",x); } while(!-2); } while(0); return 0; } int x=8; Answer : Output: 10 Explanation:
Here variable x is extern type. So it will search the definition of variable x. which is present at the end of the code. So value of variable x =8
There are two do-while loops in the above code. AS we know do-while executes at least one time even that condition is false. So program control will reach at printf statement at it will print octal number 10 which is equal to decimal number 8.
Note: %o is used to print the number in octal format. In inner do- while loop while condition is ! -2 = 0
In C zero means false. Hence program control will come out of the inner do-while loop. In outer do-while loop while condition is 0. That is again false. So program control will also come out of the outer do-while loop.
Q41 What will be output of following c code? #include<stdio.h> int main(){ int i=2,j=2; while(i+1?--i:j++) printf("%d",i); return 0; } Answer: Output: 1 Explanation:
Consider the while loop condition: i + 1 ? -- i : ++j In first iteration:
i + 1 = 3 (True)
So ternary operator will return -–i i.e. 1
In c 1 means true so while condition is true. Hence printf statement will print 1 In second iteration:
i+ 1 = 2 (True)
So ternary operator will return -–i i.e. 0
In c zero means false so while condition is false. Hence program control will come out of the while loop. Q 42 What will be output of following c code?
#include<stdio.h> int main(){ int x=011,i; for(i=0;i<x;i+=3){ printf("Start "); continue; printf("End"); } return 0; }
Answer : Output: Start Start Start Explantion:
011 is octal number. Its equivalent decimal value is 9. So, x = 9
First iteration: i = 0
i < x i.e. 0 < 9 i.e. if loop condition is true. Hence printf statement will print: Start
Due to continue keyword program control will come at the beginning of the for loop and value of variable i will be:
i += 3 i = i + 3 = 3 Second iteration: i = 3
i < x i.e. 3 < 9 i.e. if loop condition is true. Hence printf statement will print: Start
Due to continue keyword program control will come at the beginning of the for loop and value of variable i will be:
i += 3 i = i + 3 = 6 Third iteration: i = 3
i < x i.e. 6 < 9 i.e. if loop condition is true. Hence printf statement will print: Start
Due to continue keyword program control will come at the beginning of the for loop and value of variable i will be:
i += 3 i = i + 3 = 9 fourth iteration: i = 6
i < x i.e. 9 < 9 i.e. if loop condition is false.
Hence program control will come out of the for loop. Q 43 What will be output of following c code?
#include<stdio.h> int main(){ int i,j; i=j=2,3; while(--i&&j++) printf("%d %d",i,j); return 0; }
Answer
Output: 13 Explanation:
Initial value of variable i = 2
j = 2
Consider the while condition : --i && j++ In first iteration:
--i && j++
= 1 && 2 //In c any non-zero number represents true. = 1 (True)
So while loop condition is true. Hence printf function will print value of i = 1 and j = 3 (Due to post increment operator)
In second iteration: --i && j++
= 0 && 3 //In c zero represents false = 0 //False
So while loop condition is false. Hence program control will come out of the for loop.
Q 44 What will be output of following c code?
#include<stdio.h>
staticint i; for(++i;++i;++i) { printf("%d ",i); if(i==4) break; } return 0; } Answer: Output: 24 Explanation:
Default value of static int variable in c is zero. So, initial value of variable i = 0 First iteration:
For loop starts value: ++i i.e. i = 0 + 1 = 1
For loop condition: ++i i.e. i = 1 + 1 = 2 i.e. loop condition is true. Hence printf statement will print 2 Loop incrimination: ++I i.e. i = 2 + 1 =3
Second iteration:
For loop condition: ++i i.e. i = 3 + 1 = 4 i.e. loop condition is true. Hence printf statement will print 4. Since is equal to for so if condition is also true. But due to break keyword program control will come out of the for loop.
Q45 What will be output of following c code? #include<stdio.h>
int main(){ int i=1;
printf("%d ",i); if(i!=1) break; } return 0; } Answer: Output: -1 Explanation:
Initial value of variable i is 1. First iteration:
For loop initial value: i = 0
For loop condition: i = -1 . Since -1 is non- zero number. So loop condition true. Hence printf function will print value of variable i i.e. -1
Since variable i is not equal to 1. So, if condition is true. Due to break keyword program control will come out of the for loop.
Q46 What will be output of following c code? #include<stdio.h> int main(){ for(;;) { printf("%d ",10); } return 0; } Answer:
Output: Infinite loop Explanation:
In for loop each part is optional.
Q 47 What will be output of following c code? #include<stdio.h> int r(); int main(){ for(r();r();r()) { printf("%d ",r()); }
return 0; }
int r(){
intstatic num=7; return num--; } Answer: Output: 5 2 Explanation: First iteration:
Loop initial value: r() = 7 Loop condition: r() = 6
Since condition is true so printf function will print r() i.e. 5 Loop incrimination: r() = 4
Second iteration: Loop condition: r() = 3
Since condition is true so printf function will print r() i.e. 2 Loop incrimination: r() = 1
Third iteration:
Loop condition: r() = 0
Since condition is false so program control will come out of the for loop.
Q48 What will be output of following c code? #include<stdio.h> #define p(a,b) a##b #define call(x) #x int main(){ do{ int i=15,j=3; printf("%d",p(i-+,+j)); } while(*(call(625)+3)); return 0; } Answer:
Output: 11 First iteration: p(i-+,+j) =i-++j // a##b =i - ++j =15 – 4 = 11
While condition is : *(call(625)+ 3) = *(“625” + 3)
Note: # preprocessor operator convert the operand into the string. =*(It will return the memory address of character ‘\0’)
= ‘\0’
= 0 //ASCII value of character null character
Since loop condition is false so program control will come out of the for loop.
Q 49 : What will be output of following c code? #include<stdio.h> int main(){ int i; for(i=0;i<=5;i++); printf("%d",i) return 0; } Answer: Output: 6 Explanation:
It possible for loop without any body.
Q 50 What will be output of following c code? #include<stdio.h>
int i=40; externint i; int main(){
do{ printf("%d",i++); } while(5,4,3,2,1,0); return 0; } Answer : Output: 40 Explanation:
Initial value of variable i is 40 First iteration:
printf function will print i++ i.e. 40 do - while condition is : (5,4,3,2,1,0)
Here comma is behaving as operator and it will return 0. So while condition is false hence program control will come out of the for loop.