What is program? What is programming language?
Program :-
A computer program is a sequence of instructions for performing a task designed to solve specific problems. A computer program is a list of instructions that tell a computer what to do. Everything a computer does is done by using a computer program. A computer program is written in a programming language.
Programming Language :-
A set of words, symbols and codes used to write programs is called programming language. With the help of programming language, a programmer tells a computer what to do. Some popular computer programming languages are C, C++, Java etc.
___________________________________________________________________________________
Explain different types of computer programming languages.
There are two main types of computer programming languages.
-> Low-level languages
-> High-level languages.
Low Level Programming Languages :-
These languages are near to computer hardware and far from human languages. Computer can understand these languages easily. Following are two low-level languages:
-> Machine Language
-> Assembly Language
Machine Language :-
A computer language in which instructions are written in binary form (0 and 1) is called machine language.
-> It is the only language that is directly understood by the computer.
-> Machine language is the native language of computer.
Advantages of Machine Languages:
-> Very fast program execution: Because the machine language is the native language of computer that computers directly understand and execute.
-> There is no need of a translator program, because computer can already understand and execute the machine language instructions directly without the need of translation.
Disadvantages of Machine Languages:
->Machine Language is difficult to understand
-> Machine Language is difficult to learn
-> Programs of Machine Language are difficult to modify
Machine Language requires deep knowledge of hardware
Programs of Machine Language are difficult to remove errors
Programs of Machine Language are Machine dependent Machine language is also known as first generation language.
Assembly Language :-
Assembly language is a low-level language.
In assembly language, symbols are used instead of binary code.
These symbols are easy to remember.
For example Add instruction is used to add two numbers.
Assembly language is also known as second generation language
Advantages of Assembly Langauge:
Assembly language programs are executed with fast speed
Assembly language programming is easier to learn, understand and modify than machine language
Disadvantages of Assembly Language:
Assembly language programs are machine dependent
Assembly language programming requires deep knowledge of hardware High Level Programming Languages
A type of language that is close to human languages is called high level language.
High-level languages are easy to understand.
Instructions of these languages are written in English like words e.g. Print, Display, Write etc.
Examples of High Level Programming Languages
COBOL
BASIC
PASCAL
C
C++
JAVA
Visual Basic
Advantages of High Level Programming Languages:
High Level Programming Languages are Easy to learn and understand
Programs written in High Level Programming Languages are Easy to modify
It is Easy to remove errors in the Programs written in High Level Programming Languages
Programs written in High Level Programming Languages are Machine independent
High Level Programming Languages have Better documentation Disadvantages of High Level Programming Languages
A disadvantage of High Level Programming Languages is slower program execution.
High Level Programming Languages provide programming facilities for performing Certain operations.
___________________________________________________________________________________
Explain history of c language.
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.
HISTORY of C:-
ALGOL:-
The root of all modern languages is ALGOL. ALGOL is introduced in the early 1960s. ALGOL was the first computer language to use a block structure. ALOGL was widely used in Europe. ALGOL language gave the concept of structured programming to the computer science community.
BCPL:-
In 1967, Martin Richards developed a language called BCPL. The full form of BCPL is Basic Combined Programming Language. BCPL was developed primarily for writing System software.
B :-
In 1970, Ken Thompson developed a language called B at Bell Laboratory. Language B has been developed using many features of BCPL.
C:-
C was evolved from ALGOL, BCPL and B. Dennis Ritchie has developed C Language at Bell Laboratory in 1972. C uses many concepts of ALGOL, BCPL and B languages and added the concept of data types and other powerful features. Unix operating system, which was also developed at Bell Laboratory, was coded almost entirely in C. Today, C is running under a variety of operating system and hardware platforms.
___________________________________________________________________________________
Explain C character set
The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run. However, a subset of characters is available that can be used on most personal, micro, mini and mainframe computers.
The characters in C are grouped into the following categories:
1. Letters :-
- Uppercase A...Z
- Lowercase a...z
2. Digits :-
- All decimal digits 0...9
3. Special characters :-
, Comma . Period
; Semicolon
: Colon
? Question Mark
‟ Apostrophe
” Quotation Mark
! Exclamation Mark
| Pipe
/ Slash
\ Backslash
~ Tilde
_ Under Score
$ Dollar Sign
% Percent Sign
& Ampersand
^ Caret
* Asterisk
- Minus Sign
+ Plus Sign
< Less Than Sign
> Greater Than Sign
( Left Parenthesis
) Right Parenthesis
[ Left Bracket
] Right Bracket
{ Left Brace
} Right Brace
# Number Sign
@ At the rate Sign
4. White spaces:-
Blank space
Horizontal tab
Carriage return
New line
Form feed
The compiler ignores white space unless they are a part of a string constant. White spaces may be used to separate words, but are prohibited (illegal) between the characters of keywords and identifiers.
___________________________________________________________________________________
Explain different types of C Tokens.
C TOKENS :-
In a paragraph of text, individual words and punctuation marks are called tokens. Similarly, in a program the smallest individual units are known as C tokens. C programs are written using these tokens and the syntax of the language. C has following six types of tokens:
The smallest individual elements or units in a program are called as Tokens. C has following tokens:
Identifiers
Keywords
Constants
Operators
Special characters
Strings
Identifiers :
Identifiers in c refer to the name of the variables, functions, arrays,etc. created by the programmer, using the combination of following characters.
Alphabets : A to Z (or) a to z
Digits : 0 to 9
Underscore : _
Keywords :
Keywords are the words whose meaning has been already explained by the compiler. That means at the time of designing a language, some words are reserved to do specific tasks. Such words are called as keywords (or) reserved words. All C compilers support 32 keywords.
Constants :
Constants define fixed values, that do not change during the execution of a program. C supports the following constants.
Integer constants
Character constants
Real or floating constants
String constants
Operators:
Operator is a symbol which performs particular operation. C supports a rich set of operators. C operators can be classified into No of categories. They include arithmetic operators, logical operators, bitwise operators, etc.
Special characters:
All characters other than alphabets and digits are treated as special characters.
Eg: * , % , $ , { ,etc.
___________________________________________________________________________________
Explain Keyword.
Every C word is classified as either a keyword. All keywords have fixed meanings and these meanings cannot be changed. Keywords serve as basic building blocks for program statements. All keywords must be written in lowercase. The following shows the C keywords:
int, float, double, char, unsigned, signed, short, long, if, else, switch, case, default, for, while, do, break, continue, void, return, auto, register, static, extern, struct, union, typedef, const, volatile, enum, goto, sizeof
___________________________________________________________________________________
What is identifier? Write rules for identifier.
Identifiers refer to the names of variables, functions and arrays. These are userdefined names and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted, although lowercase letters are commonly used. The underscore character is also permitted in identifiers. Underscore character is usually used as a link between two words in long identifiers. Some following rules we have to follow to declare an identifier:
Rules for Identifiers :-
First character must be an alphabet (or Underscore).
Must consist letters, digits or underscore.
Only first 31 characters are significant.
Cannot use a keyword.
Must not contain white space.
___________________________________________________________________________________
What is constant? Explain different types of constants.
Constants in C refer to fixed values that do not change during the execution of the program. C supports following types of constants:
Numeric Constant
Integer Constant
Real Constant
Character Constant
Single Character Constant
String Constant
___________________________________________________________________________________
Terminal :-
The terminal symbol is used to indicate the beginning and the end and the pause of the program logic flow. It is the first symbol and the last symbol in the program logic. We can also use this symbol for halting the program.
Input/Output :-
The input/output symbol is used to denote any function of an input/output device in the program. We can use the same symbol both for inputting the data into the program or we want the get some output from the program.
Process :-
A processing symbol is used in a flowchart to represent arithmetic and data movement instructions. Whatever the logic we want to create. We have to write all the logic to execute into the process symbol.
Decision :-

The Decision symbol is used in a flowchart to indicate a point at which a decision has to be made. We can also use the symbol to check any condition if we want to check like if condition.
Flow Lines :-

Flow lines with arrowheads are used to indicate the flow of the flowchart. We can use the flow line to describe our flow whether it is from top to bottom or bottom to top. Or left to right or right to left
Connectors :-
connectors are the one of the rare use symbol of the flowchart, which is used to connect the two pages but the same program. If any program is longer then the one page then the connector is used to describe the joint of the both the pages and the program.
___________________________________________________________________________________
Explain basic structure of a C program.
=> Here, a number is entered by user which is stored in n. The if statement checks if the remainder of that number when divided by 2 is zero or not. If the remainder is zero, the number is even which is printed on the screen. If the remainder is 1, the number is odd.
=> Note :- If there is only one statement inside if block, we don't need to enclose it with curly brackets { }.
____________________________________________________________________________________________
Multiple if with syntax and example.
When a number of conditions are checked, we may use more than one if statements as below:
____________________________________________________________________________________________
if...else if...else if...else ladder with syntax and example.
It is used when more than one condition is to be checked. A block of statement is enclosed inside if, else if and else part. Conditions are checked in each if and else if part. If the condition is true, the statements inside that block are executed. If none of the conditions are true, the statements inside else block are executed. A if ... else if ... else statement must have only one if block but can have as many else if block as required. Else part is optional and may be present or absent.
Syntax of if...else if...else statement :-
if (condition 1)
{
statements;
... ... ...
}
else if (condition 2)
{
statements;
... ... ...
}
... ... ...
... ... ...
else if (condition n)
{
statements;
... ... ...
}
else
{
statements;
... ... ...
}
Flowchart of if ... else if ... else statement :-
____________________________________________________________________________________________
nested if with syntax and example.
When a if statement is kept inside another if statement, it is called nested if statement. Nested if statements are used if there is a sub condition to be tested. The depth of nested if statements depends upon the number of conditions to be checked.
Syntax of nested if statement :-
if (condition 1)
{
statements;
if (sub condition 1)
{
statements;
}
statements;
}
else if (condition 2)
{
statements;
if (sub condition 2)
{
statements;
}
statements;
}
... ... ...
... ... ...
else
{
statements;
if (sub condition n)
{
statements;
}
statements;
}
Flowchart of nested if statement :-
____________________________________________________________________________________________
switch...case with syntax and example.
We have seen that when one of the many alternatives is to be selected, we can use an if statement to control the selection. However, the complexity of such a program increases dramatically when the number of alternatives increases. The program becomes difficult to read and follow. At times, it may confuse even the person who designed it. Fortunately, C has a built-in multi-way decision statement known as a switch. The switch statement tests the value of a given variable ( or expression ) against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below:
switch ( expression )
{
case value-1;
block-1
break;
case value-2;
block-2
break;
……….
……….
default:
default-block
break;
}
statement-x;
=> The expression is an integer expression or characters. Value-1, Value-2 ….. are constants or constant expressions ( evaluable to an integral constant ) and are known as case labels. Each of these values should be unique within a switch statement. block-1, block-2 ….. are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon (:).
=>When the switch is executed, the value of the expression is successfully compared against the values value-1, value-2,... If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.
=> The break statement at the end of each block signal the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.
=> The default is an optional case. When present, it will be executed if the value of the expression does not match with any of case values. If not present, no action takes place if all matches fail and the control goes to the statement-x.
=>The selection process of switch statement is illustrated in the flow chart shown in figure below:
Example :-
____________________________________________________________________________________________
ternary operator or conditional operator with syntax and example.
THE ? : OPERATOR
The C language has an unusual operator, useful for making two-way decisions. This operator is a combination of ? and :, and takes three operands. This operator is popularly known as the conditional operator. The general form of use of the conditional operator is as follows :
Conditional expression ? expression1 : expression2
The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated and its value is returned. For example, the segment
If (x<0)
Flag=0;
Else
Flag=1;
Can be written as
Flag=(x<0) ? 0:1;
The conditional operator may be nested for evaluating more complex assignment decisions.
It is better to use if statements when more than a single nesting of conditional operator is required.
____________________________________________________________________________________________
while loop with syntax and example.
In any programming language including C, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
How it Works :-
The below diagram depicts a loop execution,
sum = 0;
n = 1; /* Initialization */
while(n <= 10) /* Testing */
{
sum = sum + n;
n = n + 1; /* Incrementing */
}
printf(“Sum =%d\n”, sum);
=> The body of the loop is executed 10 times for n = 1, 2, 3,…10, each time adding the value of n, which is incremented inside the loop. The test condition may also be written as n < 11, the result would be the same. This is a typical example of counter-controlled loop. The variable n is called counter or control variable.
____________________________________________________________________________________________
for loop with syntax and example.
The for loop is another entry-controlled (Pre Tested) loop that provides a more concise (brief, short) loop control structure. The general from of the for loop is:
for ( Initialization ; Test-Condition ; Increment / Decrement )
{
body of the loop;
}
=> The execution of the for statement is as follows:
1. Initialization of the control variables is done first, using assignment statements such as a=1 or count = 0. The variables a and count are known as loopcontrol variables.
2. The value of the control variable is tested using the test-condition. The testcondition is a relational expression, such as a<=10 that determines when the loop will exit. If the condition is true, the body of the loop is executed, otherwise the loop is terminated and the execution continues with the statement that immediately follows the for loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is incremented using an assignment statement such as a=a+1 and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test-condition.
Consider the following segment of a program:
for (x = 1 ; x <= 10; x = x + 1)
{
printf(“\n%d”, x);
}
printf(“\nEnd of the Loop”);
=> This for loop is executed 10 times and prints the digits 1 to 10 on new line. The three sections enclosed within parentheses must be separated by semicolons. Note that there is no semicolon at the end of the increment / decrement section, x = x + 1.
=> The for statement allows for negative increments. For example, the loop discussed above can be written as follows:
for (x =10; x >= 1; x=x-1)
printf(“\n%d”,x);
printf(“\nEnd of the loop”);
=> This loop is also executed 10 times, but the output would be from 10 to 1 instead of 1 to 10. Note that braces are optional when the body of the loop contains only one statement. Since the conditional test is always performed at the beginning of the loop, the body of the loop may not be executed at all, if the condition fails at the start. For example:
for (x = 10; x < 10; x = x-1 )
printf(“%d”, x);
=> will never be executed because the test condition fails at the very beginning itself. Let us consider the problem of sum of integers. This problem can be coded using the for statement as follows:
sum = 0;
for (n = 1; n <= 10; n = n + 1)
{
sum = sum + n;
}
printf(“Sum = %d\n”, sum);
=> The body of the loop
sum = sum + n;
is executed 10 times for n=1,2,….10 each time incrementing the sum by the value of n.
=> One of the important points about the for loop is that all the three actions, namely initialization, testing, and incrementing, are placed in the for statement itself, thus making them visible to the programmers and users, in one place.
____________________________________________________________________________________________
do...while loop with syntax and example.
The while and for loop constructs make a test of condition before the loop is executed. Therefore, the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. This takes the form:
do
{
body of the loop;
}
while ( test-condition );
=> On reaching the do statement, the program processed to evaluate the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated (checked). If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes (transfers) to the statement that appears immediately after the while statement.
=> Since the test-condition is evaluated at the bottom of the loop, the do…while construct provides an exit-controlled (Post Tested) loop and therefore the body of the loop is always executed at least once. A simple example of a do….while loop is:
do
{
printf(“Input a number \n”);
scanf(“%d”, &number);
} while (number > 0 ) ;
=> This segment of a program reads a number from the keyboard until a zero or a negative number is entered, and assigned to the variable number. The test conditions may have compound relations as well. For instance, the statement
while ( number > 0 && number < 100 );
=> In the above example would cause the loop to be executed as long as the number keyed in lies between 0 and 100.
I = 1; /* Initializing */
sum = 0;
do
{
Loop sum = sum +I;
I = I + 2; /* Incrementing */
} while(sum < 40 || I < 10); /* Testing */
printf(“\n%d \t %d”, I, sum);
=> The loop will be executed as long as one of the two relations is true.
____________________________________________________________________________________________
What is infinite loop?
A loop becomes an infinite loop if a condition never becomes false.
____________________________________________________________________________________________
nested loop.
Nesting of loops, that is, one for statement within another for statement is allowed in C.
=> For example, two loops can be nested as follows:
for ( a = 1 ; a < 10 ; ++a)
{ //Outer loop
statements ;
for ( b = 1 ; b ! = 5; ++b)
{ // Inner loop
statements;
}
statements;
}
=> The nesting may continue up to any desired level. The loops should be properly indented so as to enable the reader to easily determine which statements are continued within each for statement.
=> The program to print the multiplication table can be written more concisely using nested for statements as follows:
for (row = 1; row <= ROWMAX ; ++row)
{
for (column = 1; column <= COLMAX ; ++column)
{
y = row * column ;
printf(“%4d”, y);
}
printf(“\n”);
}
=> The outer loop controls the rows while the inner loop controls the columns
____________________________________________________________________________________________
break jumping statement with example.
Break statement terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
=> When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.
____________________________________________________________________________________________
goto jumping statement with example.
Goto statement Transfers control to the labeled statement.
=> So far we have discussed ways of controlling the flow of execution based on certain specified conditions. Like many other languages, C supports the goto statement to branch unconditionally from one point to another in the program. Although it may not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use the of goto might be desirable.
=> The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label are shown below:
=> The label: can be anywhere in the program either before or after the goto label; statement. During running of a program when a statement like
goto begin;
is met, the flow of control will jump to the statement immediately following the label begin:. This happens unconditionally.
=> Note that a goto breaks the normal sequential execution of the program. If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as a backward jump.
=> On the other hand, if the label: is placed after the goto label; some statements will be skipped and the jump is known as a forward jump.
=> A goto is often used at the end of a program to direct the control to go to the input statement, to read further data. Consider the following example:
main( )
{
double x, y;
read:
scanf( “%f ”, &x );
if (x < 0) go to read;
y = sqrt(x);
printf(“%f %f \n”, x ,y);
go to read
=> This program is written to evaluate the square root of a series of numbers read from the terminal. The program uses two goto statements, one at the end, after printing the results to transfer the control back to the input statement and the other to skip any further computation when the number is negative.
=> Due to the unconditional goto statement at the end, the control is always transferred back to the input statement. In fact, this program puts the computer in a permanent loop known as an infinite loop. The computer goes round and round until we take some special steps to terminate the loop. Such infinite loops should be avoided. Example following illustrates how such infinite loops can be eliminated.
Example :-
Another use of the goto statement is to transfer the control out of a loop (or nested loops) when certain peculiar conditions are encountered. Example:
-------------
while (-----)
{
for (-----)
{
----------
if (-----) goto end_of_program;
----------
}
-----------
-----------
}
end_of_program:
=> We should try to avoid using goto as far as possible. But there is nothing wrong, if we use it to enhance the readability of the program or to improve the execution speed.
____________________________________________________________________________________________
What is array? How to declare an array? How to initialize an array?
An array is a collection of data items, all of the same type, accessed using a common name.
Example where arrays are used,
to store list of Employee or Student,
to store marks of students,
or to store list of numbers or characters etc.
Declaring an Array :-
Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array.
Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.
Like any other variable, arrays must be declared before they are used. General form of array declaration is,
data-type array-name[array-size];
Example of array declaration
int arr[10];
Initialization of an Array:-
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at runtime.
Compile time Array initialization
Compile time initialization of array elements is same as ordinary variable initialization. The general form of initialization of array is,
data-type array-name[size] = { list of values };
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
____________________________________________________________________________________________
Explain different types of arrays.
Arrays are Set of Elements having same data type or we can Say that Arrays are Collection of Elements having same name and same data type But Always Remember Arrays are Always Start From its index value and the index of array is start From 0 to n-1.
Suppose we wants to Access 5th Element of array then we will use 4th Element Because Arrays are Start From 0 and arrays are always stored in Continuous Memory Locations The Number of Elements and Types of array are Identified by Subscript of array Elements. The Various types of Array
those are provided by c as Follows:-
1. Single Dimensional Array
2. Two Dimensional Array
3. Three Dimensional array
4. Character Array or Strings.
1) Single Dimensional Array :-
A dimensional is used representing the elements of the array for example int a[5];
The [] is used for dimensional or the sub-script of the array that is generally used for declaring the elements of the array For Accessing the Element from the array we can use the Subscript of the Array like this a[3]=100
This will set the value of 4th element of array
So there is only the single bracket then it called the Single Dimensional Array
This is also called as the Single Dimensional Array
2) Two Dimensional Array or the Matrix :-
The Two Dimensional array is used for representing the elements of the array in the form of the rows and columns and these are used for representing the Matrix A Two Dimensional Array uses the two subscripts for declaring the elements of the Array Like this
int a[3][3];
So This is the Example of the Two Dimensional Array In this first 3 represents the total number of Rows and the Second Elements Represents the Total number of Columns The Total Number of elements are judge by Multiplying the Numbers of Rows * Number of Columns in The Array in the above array the Total Number of elements are 9
3) Multidimensional or the Three Dimensional Array :-
The Multidimensional Array are used for Representing the Total Number of Tables of Matrix A Three dimensional Array is used when we wants to make the two or more tables of the Matrix Elements for Declaring the Array Elements we can use the way like this
int a[3][3][3];
In this first 3 represents the total number of Tables and the second 3 represents the total number of rows in the each table and the third 3 represents the total number of Columns in the Tables
So this makes the 3 Tables having the three rows and the three columns
The Main and very important thing about the array that the elements are stored always in the Contiguous in the memory of the Computer
4) Character Array of String: -
Like an integer characters are also be in the Array The Array of Characters are called as the Strings They are Generally used for representing the Strings Always Remember that a String is Terminated with the \0 or Null Character There are the built in string Operation those are provided by the C Language in the String.h Header file Like
i) strLen For Getting the Length or Total Numbers of Characters in String
ii) strcat This is Used for Joining the two Strings or This function is used for Concatenating the two Strings.
iii) strRev This Function is used for obtaining the Reverse of the String
iv) strcmp This Function is used for Comparing the Two Strings and it gives us the Result as follows after comparing the Two Strings
___________________________________________________________________________________
What is structure? How to declare and initialize structure?
Structure is a group of variables of different data types represented by a single name. Let’s take an example to understand the need of a structure in C programming.
Let’s say we need to store the data of students like student name, age, address, id etc. One way of doing this would be creating a different variable for each attribute, however when you need to store the data of multiple students then in that case, you would need to create these several variables again for each student. This is such a big headache to store data in this way.
We can solve this problem easily by using structure. We can create a structure that has members for name, id, address and age and then we can create the variables of this structure for each student. This may sound confusing, do not worry we will understand this with the help of example.
How to create a structure in C Programming
We use struct keyword to create a structure in C. The struct keyword is a short form of structured data type.
struct struct_name {
DataType member1_name;
DataType member2_name;How to declare variable of a structure?
struct struct_name var_name;
or
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;
DataType member3_name;
…
};
Here struct_name can be anything of your choice. Members data type can be same or different. Once we have declared the structure we can use the struct name as a data type like int, float etc.
First we will see the syntax of creating struct variable, accessing struct members etc and then we will see a complete example.
How to declare variable of a structure?
struct struct_name var_name;
or
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
} var_name;
How to access data members of a structure using a struct variable?
var_name.member1_name;
var_name.member2_name;
…
How to assign values to structure members?
There are two ways to do this.
1) Using Dot(.) operator
var_name.memeber_name = value;
2) All members assigned in one statement
struct struct_name var_name =
{value for memeber1, value for memeber2 …so on for all the members}
___________________________________________________________________________________
Explain array within structure with example.
C permits use of arrays are structure members. Similarly, we can use singledimension or multi-dimensional arrays of type int or float or char or any type as member variables in a structure. Let’s see how to declare Arrays within Structures.
For example, the following structure declaration is valid.
struct{
int num;
float sub[3]; //Array within structure
}student[2]={0,{0,0,0}}; //Initialize Array within Structure
Accessing Arrays within Structures
Here, the member sub contains three elements, sub[0], sub[1] and sub[2]. Now, student[1].sub[2]; will refer to the marks obtained by the second student in the third subject.
Arrays within Structures Example
#include <stdio.h>
void main()
{
struct
{
int sub[3]; //Declaring Array within Structure
int total;
}student[3]; //Declaring Array of Structure
int a;
clrscr();
printf("Enter student marks :\n");
for(a=0;a<3;a++)
{
printf("\nStudent %d\n",a+1);
printf("Subject 1 : ");
scanf("%d",&student[a].sub[0]);
printf("Subject 2 : ");
scanf("%d",&student[a].sub[1]);
printf("Subject 3 : ");
scanf("%d",&student[a].sub[2]);
student[a].total=student[a].sub[0] + student[a].sub[1] + student[a].sub[2];
}
printf("\nTotal marks :\n");
printf("Student 1 : %d\n",student[0].total);
printf("Student 2 : %d\n",student[1].total);
printf("Student 3 : %d\n",student[2].total);
getch();
}
___________________________________________________________________________________
Explain array of structure with example.
Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type.
Let's take an example:
struct car
{
char make[20];
char model[30];
int year;
};
Here is how we can declare an array of structure car.
struct car arr_car[10];
{
char name[20];
int roll_no, i;
float marks;
};
int main()
{
struct student arr_student[MAX];
int i;
for(i = 0; i < MAX; i++ )
{
printf("\nEnter details of student %d\n\n", i+1);
printf("Enter name: ");
scanf("%s", arr_student[i].name);
printf("Enter roll no: ");
scanf("%d", &arr_student[i].roll_no);
printf("Enter marks: ");
scanf("%f", &arr_student[i].marks);
}
printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks);
}
// signal to operating system program ran fine
return 0;
}
___________________________________________________________________________________
Explain Nested structure.
When a structure is within another structure, it is called Nested structure. A structure variable can be a member of another structure and it is represented
as
struct student
{
int rollno;
struct marks
{
int m1, m2, m3;
}var1;
}var2;
It is possible to define structure outside & declare its variable inside other structure.
struct marks
{
int m1, m2, m3;
};
struct student
{
int rollno;
struct marks var1;
}var2;
___________________________________________________________________________________
What is union? Write difference between structure and union.
Union is derived data type contains collection of different data type or different elements. All definition declaration of union variable and accessing member is similar to structure, but instead of keyword struct the keyword union is used, the
main difference between union and structure is
Each member of structure occupy the memory location, but in the unions members share memory. Union is used for saving memory and concept is useful when it is not necessary to use all members of union at a time.
Where union offers a memory treated as variable of one type on one occasion where (struct), it read number of different variables stored at different place of memory.
Syntax of union:
union union_name
{
datatype member1;
datatype member2;
};
___________________________________________________________________________________
What is function? Explain different types of functions.
A function is a self-contained block of code that performs a particular task.
C functions can be classified into two categories namely library functions and user defined functions. The main distinction between these two categories is that library functions are not required to be written by us whereas a user defined function has to be developed by the user at the time of writing a program.
Whenever we develop our program we write main() function. This is a user defined function. Every program must have a main function to indicate where the program has to begin its execution.
The general form of the function is:
Return_type function_name (argument-list)
{
local variable declaration;
executable statements;
return (expression);
}
Argument list and argument declaration are optional, it depends on the calling function. Local variable declaration is required only when any local variable are used in the function. A function may or may not send back any value to the calling function. If it does, it does it through the return statement. While it is possible to pass to the called function, any number of values, the called function can return one value per call at the most. The return statement can take the following form
return (expression);
The above statement returns the value of the expression to the calling function.
The return statement is the mechanism for returning a value to the calling function.
This is also an optional statement and its absence indicates that no value is being returned to the calling function.
Each function has the following parts:
Function prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function maylater be used in the program.
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2,...);
The function prototype is not needed if the user-defined function is defined before the main() function.
Calling a function
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call
functionName(argument1, argument2, ...);
Function definition
Function definition contains the block of code to perform a specific task.
Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.
___________________________________________________________________________________
Explain different types of User Defined Functions.
Category of user defined functions:
Depending on the conditions like whether the arguments are passed to the called function and whether the called function is returning the value back to the calling function, the functions are categorized into following categories.
(i) Functions without arguments and without any return value.
In this the calling function is not passing any arguments to the called function and the called function is not returning back any value to the calling function.
Example:
#include<stdio.h>
void main ( )
{
void message();
printf ("I am in MGM College\n");
message ( );
}
void message ( )
{
printf ("I am in C class \n');
}
In the above program the function message() is called from main(). The function main() is not passing any value to the function message() and function message() is also not returning back any value to the function main().
(ii) Function without arguments and with Return value
In this method, We don’t pass any arguments to the function while defining, declaring or calling the function. This type of functions will return one value when we call the function from main() or any sub function. Data Type of the return value will depend upon the return type of function declaration. For instance, if the return type is int then return value will be int.
#include<stdio.h>
void main ()
{
int ans;
int multi();
ans = multi();
printf ("Result is %d", ans);
}
int multi ()
{
int x,y,z;
x=5;
y=6;
z = x*y;
return z;
}
In this program, We are going to calculate the multiplication of 2 integer values using the user defined function without arguments and return keyword.
(iii) Functions with arguments and without any return value.
In this, the calling function is passing one or more arguments to the called function and the called function is not returning back any values to the calling function.
#include<stdio.h>
void main ()
{
int a, b;
void add();
a = 5;
b = 6;
add(a,b);
}
void add (int x, int y)
{
int z;
z = x+y;
printf ("Result is %d \n", z);
}
In the above program the function main() passes two arguments a and b to the function add(). But the function add() does not return any value back to the function main().
Note :
In the above example add() is called function and main() is the calling function.
(iv) Functions with arguments and with return value.
In this the calling function is passing one or more arguments to the called function and the called function will return back one value to the calling function.
# include <stdio.h>
void main ( )
{
int a, b, c;
int add();
a = 5;
b = 6;
c = add (a, b);
printf ("In main %d\n",c);
}
add (int x, int y)
{
int z;
z = x+y;
printf ("Result in function %d\n",z);
return (z);
}
In the above program the function main() passes two arguments a and b to function add() and the values are received in the function add() through the variables x and y. The variable z is local to the function add(). The function add() returns the result back to the main() through the variable z and it is received at the function main() though the variable c.
Note:
In the above program, the arguments a and b are known as actual arguments and arguments x and y are known as formal arguments. The values of actual arguments are copied to formal arguments when the functions is called.
Note:
Wherever function is not returning any value back to the main function we have used the return type as void.
___________________________________________________________________________________
Explain call by value and call by reference.
Functions
We often write large programs and it is a good idea to split large progrmas into smaller procedures. These small procedure blocks are known as functions. Functions are often required to do repetitive jobs. We can define a function and call them from anywhere we need. This is a good choice for code reuse and code size optimization.
Arguments
Functions are generally written for a particular operation with one or more inputs. Like we write a function to check if the number is prime or not. Here we write a logic which is not dependent on any specific number but can be used for any positive integers. We reuse this logic by providing an input number. This input is called function argument.
Function call and return
Arguments are small set of variables, temporarily stored in current context of stack. Compiler passes these arguments to calling function by pushing the variables to the stack from right side to left side. Passing variables are similar to coping the variables to a temporary place. Stack grows as compiler pushes more arguments. Finally it pushes the return address and jumps to the function. Now function can do its operation and return from the context. Return statement causes microprocessor to pop the return address from the stack and jumps back to caller. Compiler further shrinks the stack and rewinds to caller context.
Call by value
In call by value mechanism, the called function creates a new set of variables in stack and copies the values of the arguments into them.
Example: Program showing the Call by Value mechanism.
Call by value source code
void swap(int x, int y)
{
int z;
z = x;
x = y;
y = z;
printf("Swapped values are a = %d and b = %d", x, y);
}
int main (int argc, char *argv[])
{
int a = 7, b = 4;
printf("Original values are a = %d and b = %d", a, b);
swap(a, b);
printf("The values after swap are a = %d and b = %d", a, b);
}
Output
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7
The values after swap are a = 7 and b = 4
This happens because when function swap() is invoked, the values of a and b gets copied onto x and y. The function actually swaps x and y while the values of the original variables a and b remain intact.
Call by value flow diagram
Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (a, b) can be split into some assembly steps like-
1. push value of b
2. push value of a
3. save return address
4. call function
swap(&a, &b);
printf("The values after swap are a = %d and b = %d", a, b);
}
Output
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7
The values after swap are a = 4 and b = 7
This happens because when function swap() is invoked, it creates a reference for the first incoming integer a in x and the second incoming integer b in y. Hence the values of the original variables are swapped.
Call by reference flow diagram
Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (&a, &b) can be split into some assembly steps like-
1. push address of b
2. push address of a
3. save return address
4. call function
Here one point to note is x and y are pointers. Address of a and b will be copied to x and y. Inside swap() values of pointers will be interchanged. Dereferencing "x" which is same as accessing "a" and the same is true for y. Dereferencing addresses at x and y is same as accessing a and b accordingly. Thus values of a and b will be interchanged after the return of swap().
What is the difference between Call by Value and Call by Reference?
When using Call by Value, you are sending the value of a variable as parameter to a function, whereas Call by Reference sends the address of the variable. Also, under Call by Value, the value in the parameter is not affected by whatever operation that takes place, while in the case of Call by Reference, values can be affected by the process within the function.
___________________________________________________________________________________
Explain recursion with an example.
Recursive function is that function which calls itself inside its body. In computer science recursion is very necessary for solving a problem which has the recursive nature.
Take for example we want to calculate the factorial of a positive integer. In mathematics
Factorial (n) = 1 * 2 * 3 .. n; Factorial (n) = n * Factorial (n -1);
Here the problem of factorial of an integer has a problem domain of factorial (n-
1) inside it. To solve this recursive nature of this problem we can we can call the function itself inside the function body of factorial calculation. Code:
unsigned int factorial(unsigned int n )
{
if ( n <= 1 )
{
return 1;
}
else
{
return n * factorial(n - 1);/*Call itself*/
}
}
Advantages and Limitation:
One major advantage of recursion is that it reduces the code complexity. It reduces loop statements and makes code easy to understand.
However it has a major limitation regarding the stack usage. Every call inside the function takes extra stack frames. When inner call goes further inside, call stack grows accordingly.
___________________________________________________________________________________
Explain different storage classes.
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Local Variable (automatic)
The variables declared inside the function are automatic or local variables. The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed.
int main()
{
int n; // n is a local variable to main() function
... .. ...
}
void func()
{
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits.
Global Variable (external)
Variables that are declared outside of all functions are known as external variables. External or global variables are accessible to any function.
Example : External Variable
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}
Output
n = 7
Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the compiler will complain. To solve this problem, keyword extern is used infile2 to indicate that the external variable is declared in another file.
Register Variable
The register keyword is used to declare register variables. Register variables were supposed to be faster than local variables. However, modern compilers are very good at code optimization and there is a rare chance that using register variables will make your program faster. Unless you are working on embedded system where you know how to optimize code for the given application, there is no use of register variables.
Static Variable
A static variable is declared by using keyword static. For example;
static int i;
The value of a static variable persists until the end of the program.
Example : Static Variable
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
__c += 5;
}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is
increased by 5.
During the second function call, variable c is not initialized to 0 again. It's
because c is a static variable. So, 5 is displayed on the screen.
_________________________________________________________________________________
Explain passing an array to a User Defined Function (UDF) with example
To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.
functionName(arrayname); //passing array
There is following way to declare function that has array as argument.
return_type function(dataType [])
C language passing array to a function example
#include<stdio.h>
int minarray(int arr[],int size)
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}//end of for
return min;
}//end of function
void main()
{
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
min=minarray(numbers,6);//passing array with size
printf("minimum number is %d \n",min);
}
Pass Entire array
Here entire array can be passed as a argument to function .
Function gets complete access to the original array .
While passing entire array Address of first element is passed to function , any changes made inside function , directly affects the Original value .
Function Passing method : “Pass by Address“
_________________________________________________________________________________
Explain passing a structure to a User Defined Function (UDF) with example.
You can pass a structure as a function argument in the same way as you pass any other variable or pointer.
A structure can be passed to any function from main function or from any sub function.
Structure should be declared outside the main function. So, this structure will be visible to all the functions in a C program.
Example:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void main( )
{
void printBook( struct Books book );
struct Books Book1; /* Declare Book1 of type Book */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Y. Kanetkar");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 14235;
printBook( Book1 );
getch();
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
_________________________________________________________________________________
What are header files and what are its uses in C programming?
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.
_________________________________________________________________________________
Explain following library functions:Strcpy, strcmp, ceil, pow, sqrt, clock, time, initgraph, circle, getchar, puts, isdigit, toupper, abs, atol, malloc, realloc
char *strcpy(char *dest, const char *src)
Copies the string pointed to, by src to dest.
int strcmp(const char *str1, const char *str2)
Compares the string pointed to, by str1 to the string pointed to by str2.
double ceil(double x)
Returns the smallest integer value greater than or equal to x.
double pow(double x, double y)
Returns x raised to the power of y.
double sqrt(double x)
Returns the square root of x.
clock_t clock(void)
Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program).
time_t time(time_t *timer)
Calculates the current calender time and encodes it into time_t format.
struct tm *localtime(const time_t *timer)
The value of timer is broken up into the structure tm and expressed in the local
time zone.
void far initgraph(int far *graphdriver, int far *graphmode, char far
*pathtodriver);
Initializes the graphics system
void far circle(int x, int y, int radius);
circle draws a circle
int getchar(void)
Gets a character (an unsigned char) from stdin.
int puts(const char *str)
Writes a string to stdout up to but not including the null character. A newline
character is appended to the output.
int isdigit(int c)
This function checks whether the passed character is decimal digit.
int toupper(int c)
This function converts lowercase letters to uppercase.
int abs(int x)
Returns the absolute value of x.
long int atol(const char *str)
Converts the string pointed to, by the argument str to a long integer (type long
int).
void *malloc(size_t size)
Allocates the requested memory and returns a pointer to it.
void *realloc(void *ptr, size_t size)
Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
__________________________________________________________________________________
What is pointer? How can we declare and initialize it?
A Pointer in C language is a variable which holds the address of another variable of same data type.
Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides power and flexibility to the language.
Declaration of Pointer variable
General syntax of pointer declaration is,
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing.
Here are a few examples:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of a variable of the same data type. In C language address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of the variable associated with it.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variables always point to variables of same datatype.
Using the pointer or Dereferencing of Pointer
Once a pointer has been assigned the address of a variable, to access the value of the variable, pointer is dereferenced, using the indirection operator or dereferencing operator *.
#include <stdio.h>
void main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
printf("%d", *p); //this will print the value of 'a'
printf("%d", *&a); //this will also print the value of 'a'
printf("%u", &a); //this will print the address of 'a'
printf("%u", p); //this will also print the address of 'a'
printf("%u", &p); //this will print the address of 'p'
getch();
}
Points to remember while using pointers:
1. While declaring / initializing the pointer variable, * indicates that the variable is a pointer.
2. The address of any variable is given by preceding the variable name with Ampersand &.
3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value. It means that a is going to contain the address of a variable storing integer value.
4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can be read as 'value at'.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
Advantages of using pointers in C programming
1. Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.
2. It makes you able to access any memory location in the computer's memory.
3. Pointers are more efficient in handling arrays and data tables.
4. Pointers can be used to return multiple values from a function via function arguments.
5. Pointers allow passing a function as argument to other functions.
6. The use of pointer arrays to character strings results in saving of data storage space in memory.
7. Pointers allow C to support dynamic memory management.
8. Pointers provide an efficient way for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees.
9. Pointers increase the execution speed and thus reduce the program execution time.
___________________________________________________________________________________
Explain pointer to an array with example.
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e. address of the first element of the array is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:
Here variable arr will give the base address, which is a constant pointer pointing to the first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e. 1000. In short, arr has two purposes - it is the name of the array and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element
to another.
Example of Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements. Let’s have an example,
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
getch();
}
In the above program, the pointer *p will print all the values stored in the array one by
one.
___________________________________________________________________________________
Explain pointer to structure with example.
You can define pointers to structures in very similar way as you define pointer to any other variable as follows:
struct Book *pointer_name;
Now you can store the address of a structure variable in the above defined pointer variabe. To find the address of a structure variable, place the & operator before the structure variable's name as follows:
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use
the -> operator as follows:
Pointer_name->title;
Let us write the complete program for pointer to structure:
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct Book
{
int book_id;
char title[50];
};
void main( )
{
struct Book Book1; /* Declare Book1 of type Book */
struct Book *ptr; /* Declare pointer of type Book */
ptr = &Book1; //assign address of Book1 to pointer ptr
Book1.book_id = 1521;
strcpy( Book1.title, "C Programming");
printf( "Book book_id : %d\n", ptr->book_id);
printf( "Book title : %s\n", ptr->title);
getch();
}
___________________________________________________________________________________
Explain passing pointer to a function with example.
We are passing a pointer to a function. When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.
Example: Swapping two numbers using Pointer
#include <stdio.h>
void main()
{
void swap(int *a, int *b);
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
getch();
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10
___________________________________________________________________________________
Explain Array of pointer with an example.
We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length.
char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now let’s see same array without using pointer
char name[3][20] = {
"Adam",
"chris",
"Deniel"
};
In the second approach memory wastage is more, hence it is preferred to use pointer in such cases.
When we say memory wastage, it doesn't means that the strings will start occupying less space, no, characters will take the same space, but when we define array of characters, a contiguous memory space is located equal to the maximum size of the array, which is a wastage, which can be avoided if we use pointers instead.
___________________________________________________________________________________
6 Explain pointer to pointer with example.
In C, pointer to pointer concept, a pointer refers to the address of another pointer.
In c language, a pointer can point to the address of another pointer which points to the address of a variable. Let's understand it by the diagram given below:
Let's see the syntax of pointer to pointer.
int **p2;
pointer to pointer example
Let's see an example where one pointer points to the address of another pointer.
As you can see in the above figure, p2 contains the address of p (fff2) and p contains
the address of number variable (fff4).
#include<stdio.h>
void main()
{
int number=50;
int *p; //pointer to int
int **p2; //pointer to pointer
p=&number; //stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",*p);
getch();
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
___________________________________________________________________________________
Write difference between static memory allocation and dynamic memory allocation.
-----------------------------------------------------------------------------------------------------------------------------
Static Memory Allocation | Dynamic Memory Allocation
-----------------------------------------------------------------------------------------------------------------------------
memory is allocated at compile time. | memory is allocated at run time.
-----------------------------------------------------------------------------------------------------------------------------
memory can't be increased while | memory can be increased while executing
executing program. | program.
-----------------------------------------------------------------------------------------------------------------------------
used in array. | used in pointer (linked list).
-----------------------------------------------------------------------------------------------------------------------------
Memory locations are fixed at compile | Memory locations are not fixed means
time. | changed during run time.
-----------------------------------------------------------------------------------------------------------------------------
Static allocation memory is never freed. | Dynamic allocation memory is freed when
| the compound statement is exited.
-----------------------------------------------------------------------------------------------------------------------------
This allocation wastes memory | This allocation saves memory.
-----------------------------------------------------------------------------------------------------------------------------
___________________________________________________________________________________
What is FILE? Explain different file modes.
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. FILE is a ready-made structure.
=> Different file modes are given below:
=========================================================================
File Mode Description
=========================================================================
r opens a text file in reading mode
-----------------------------------------------------------------------------------------------------------------------------
w opens or create a text file in writing mode.
-----------------------------------------------------------------------------------------------------------------------------
a opens a text file in append mode
-----------------------------------------------------------------------------------------------------------------------------
r+ opens a text file in both reading and writing mode
-----------------------------------------------------------------------------------------------------------------------------
w+ opens a text file in both reading and writing mode
-----------------------------------------------------------------------------------------------------------------------------
a+ opens a text file in both reading and writing mode
=========================================================================
___________________________________________________________________________________
Explain different file handling functions.
Different file handling functions are as below:
=========================================================================
Function Description
=========================================================================
fopen() create a new file or open a existing file
-----------------------------------------------------------------------------------------------------------------------------
fclose() closes a file
-----------------------------------------------------------------------------------------------------------------------------
getc() reads a character from a file
-----------------------------------------------------------------------------------------------------------------------------
putc() writes a character to a file
-----------------------------------------------------------------------------------------------------------------------------
getw() reads an integer from a file
-----------------------------------------------------------------------------------------------------------------------------
putw() writes an integer to a file
-----------------------------------------------------------------------------------------------------------------------------
fscanf() reads a set of data from a file
-----------------------------------------------------------------------------------------------------------------------------
fprintf() writes a set of data to a file
-----------------------------------------------------------------------------------------------------------------------------
fwrite() writes structure variable to a file
-----------------------------------------------------------------------------------------------------------------------------
fread() reads structure variable from a file
=========================================================================
___________________________________________________________________________________
What is command line argument? Explain with an example.
Command line argument is a parameter supplied to the program when it is invoked. Command line argument is an important concept in C programming. It is mostly used when you need to control your program from outside. Command line arguments are passed to the main() method.
Syntax:
void main(int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.
Example for Command Line Argument
#include <stdio.h>
#include <conio.h>
void main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
getch();
}
Remember that argv[0] holds the name of the program and argv[1] points to the first command line argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.



No comments:
Post a Comment