Home NOTESB.TECH FIRST YEAR NOTES Notes: COMPUTER SYSTEM AND PROGRAMMING IN C (RCS201 )

Notes: COMPUTER SYSTEM AND PROGRAMMING IN C (RCS201 )

by uptu
0 comment

COMPUTER SYSTEM AND PROGRAMMING (CCP) Notes

How to Boot the system


Switch on the computer and boot it with Windows OS. When system gets booted, desktop will get displayed on the monitor screen. Identify the Desktop Icons, Start Button, Quick Launch Toolbar and System Tray.


While booting firstly computer checks all its peripherals, if they are functioning properly or not. If any unit is found faulty, an error message appears on the screen and booting stops. On the other hand if all the units are found OK then booting continues. Computer reads the operating system from the disk loads it into main memory and displays further functioning and Graphical User Interface of the Windows Operating System.

Working on MS-DOS Environment

banner

1. MD (Make Directory:This command is used to make a new directory or folder.

C:\> MD <directory or folder name> Press Enter Key

**Note: By default in MS-DOS current directory is C derive. Symbol C :\> is called Command Prompt.

2. CD (Change Directory): This command is used to change the current directory or folder.

C :\> CD <directory name> Press Enter Key

C:\directory name>. Now we are inside the new directory, from C drive to new

directory / existing directory
3. RD (Remove Directory) :This command is used to remove a directory. The directory to be removed should be empty i.e. there must be no file inside that directory. C :\> RD
<directory name> Press Enter Key

4. CD.: CD followed by two dots. This command is used to come out of the current directory/folder.

C:\directory1\directory2> CD.. Press Enter Key

Result: C:\directory1>. Now we are out of the directory2.

5. DIR:This command is used to view all the directories.

C :\> dir press enter key

6. File creation: Copy Con:copy con myfile.txt <press enter> When typing the above you will return down one line to a blank line. Create the file line by line. Once you are ready to create the file press enter to get to a blank line and then press and hold CTRL and press Z then let go of both buttons. This will return a
^Z. Once this has been entered press enter to save and exit the file. edit myfile.txt <press enter>. By this command we can open the editor of
MS-DOS

7. COPY command:It is used to copy the content of one file to another file.

C :\> copy <source file> <target file> Press Enter Key

8. TYPE:This command is used to view the contents of a existing file on command prompt.

C:\ <current directory> TYPE <file name> Press Enter Key

9. EDIT:This command is used to open the editor of MS-DOS. In this we can create a new text file and save it in some directory or can open the exiting file to
view its contents.

C :\> edit Press Enter Key, A text editor will be opened.

10. DEL:This command is used to delete an existing file from a directory or drive.

C:\<Current Directory> DEL <file name> Press Enter Key.

11. CLS:It allows the user to clear the complete content of the screen, leaving only the MS-DOS prompt.

12. TIME:It allows the user to view and edit the time of the computer system.

13. DATE:It allows the user to view and edit the current date to an alternate date.

14. VER:This command is used to view the version of the MS-DOS Operating System.

Working on Windows OS Environment

1. Working with desktop icons:


Right click the mouse on some blank portion of the desktop. A shortcut menu appears on the monitor. Select “Arrange Icon By” option from this menu. When you do so another popup menu appears, select “Name “option. This will arrange icons by name. Similarly “By Type” etc.

2. Familiarity with multitasking features of Windows:

(i) Double click the mouse on the time that get displayed in system tray.

(ii) Double click the mouse on My Computer Icon on desktop.

(iii) Select “Start” button and then select any option from start menu like: All programs, Accessories, MS Office etc.

3. Operating upon Program Windows:
Move the window, Decrease the width of window, Increase the length of the window, Maximize the window, Minimize the window and restore.

4. Working with Notepad Program:

Click mouse on Start button → Select All Programs → Accessories

→ Notepad from nested popup menus. Notepad window appears. Go to Menu Bar, select File → New File

→ Save it as .txt extension→ Write some text on the notepad editor. From Edit menu perform Cut, Copy & Paste operations.

5. Working on MS –Word:


The user interface of MS Word includes Document window, Ruler, Title bar, Menu Bar, Standard tool bar (with short cut options), Formatting Toolbar (For
text designing & formatting).

(i) Creating, Saving and Closing the document: Select Start button → all programs → Ms Office →

MS Word. Then select File → Press New document Pane. a blank editor will open , Select save as option from File Menu , give the file name as .doc
extension. Write something on text. Press Ctrl + S (or F2) key to save the typed text.

 

(ii) Select Edit Menu at menu bar and perform select all, cut, copy, paste options.

 


(iii) Select Insert menu → Go to symbol sub menu. Select Insert menu again & select object sub menu. In that select Microsoft Equation option and
work on some mathematical operations and symbols.


(iv) Click Save in the Save As dialog box to save the document and close the Save As dialog box. Select file or folder to be used to save the word
file.


(v) Select Format Menu in menu bar and change the Font, Size of Font & its Type. Paragraph Editing, Bullets & Numbering, Borders & Shading
etc.

(vi) Work on Table Menu to draw the table of some fixed rows and columns.

6. Short Cut keys for MS Word application:


Short cut keys are those through which we can quickly perform various functions of MS-Word with keyboard, without using mouse to select options from Menu Bar.

 

Ctrl + N – Open a new document.

Ctrl + O – Open an existing document.

Ctrl + P – Print the active document.

Ctrl + S (or F2 key) — Save the document file.

Ctrl + X – Move the selected text

Ctrl + C —- Copy the selected text

Ctrl + V — Paste the selected text

Ctrl + A — Select the whole text of a document file.

Questions & Answers

Q1. What are the various functions of an Operating System?

Ans: Process Management, Memory Management, CPU Scheduling, I/O Management, Network Management.

Q2.What is the working of Loader System Utility?

Ans: This is an OS utility that copies programs from a storage device to RAM(Main Memory) , where they can be executed. Types of loaders are like Absolute
loader, bootstrap loader.

Q3.What is the difference between low level language and high level language?

Ans: Low level language is machine language in form of 0 and 1 /Assembly language in Mnemonics which can be understand by computer hardware. It is very
difficult to understand by the user. Each type of CPU has its own machine language depending on the hardware
.

High level language is those which are used by programmers to create computer instructions, coding the programs and to develop the software’s. These are closer to human languages and are combination of natural language like English & some mathematical expressions and Language Syntax and rules.These are easier to understand, write and maintain as compared to low level languages. Example: Ada, Pascal, FORTRAN, C, C++, Java, C #, COBOL.

Q4, What are the real time operating systems?

Ans: These are multitasking OS that aims to execute on given time constraints and limitations. They are quicker and predictable towards response to events.
e.g. Vx Works, OpenCom RTOS, OS-9, MenuetOS , MQX, Embedded Linux, Thread X .

Q5. What do you mean by internal and external commands of MS-DOS?

Ans: Internal commands are stored in the system memory. These are the command frequently used by user. Example: cd, Copy, md , rd, Time, Ver. , Del , Type,Echo, Rename, Cls, Path, Erase etc. External commands are those that require large requirements and/or not commonly used. Many of the external commands are located in the Windows\System 32 directories.

Example: Append, Attrib, Chkdsk, Deltree, Dosshell, Msbackup, Ping, Net, Telnet, Xcopy, Defrag,Doskey, Format, Fast help etc.

Q6.What is Arithmetic Logic Unit in CPU?

Ans: ALU performs two types of operations—Arithmetic & logic. Arithmetic operations are like addition, subtraction, division trigonometrically functions
(Sine, Cosine, etc.), square roots.Logical operations involve Boolean Logic like: AND, OR, NOT.

 

Q7.What is the BIOS program in CPU?

Ans: In computer system the ROM(Read only memory) contains a specialized program called the BIOS that performs loading of OS from the hard disk drive to RAM whenever the computer is turned on or reset.

Q8.What are the Embedded Systems and Firmware’s?

Ans : Embedded system are designed to be operated on small devices with low memory like PDA’s , Washing Machines, Digital speedometer , Fuel Meter in vehicles. They require limited resources. They are designed in the form of small chips attached on device. Example: Windows CE, FreeBSD, Minix 3 are some embedded OS. In the embedded computers , which frequently don’t have the HDD(Hard disk) , all of the software required to perform the task may be stored in ROM. Software that is stored in ROM is often called Firmware.

Q9. What is the Compiler?

Ans: Compiler is program that converts a code written in high level language like C, Java to low level machine code. It also checks and points the errors in a program. Compiler resides in the main memor during compilation of a code. It has a separate editor in which user types the program.

Q10.Why UNIX is said to be Multi-user and Multitasking Operating System?

Ans: In UNIX same computer resources like hard disk, memory etc. can be used /accessed by many users Simultaneously. Each user is given a terminal i.e. a keyboard and a monitor. In UNIX main computer is called sever /console. Also the UNIX has the capability to carry out more than one task/job at the same time.

Example: We can keep typing a program, while can execute some other command given earlier like copying a file, displaying directory structure or
printing a document.

Introduction to C Programming

 The environment where compiler, editor, debugging tools, linking facilities, tracing and testing tools are available is called Integrated Development
Environment (IDE).Example: Turbo C (TC), Borland C, Microsoft C/ C++, ANSI C, Turbo C++

Creation/Editing a C program


1. By default C compiler is installed in partition C of hard disk drive. Open Turbo C either by typing TC on system prompts, Or by clicking short cut
of TC on the desktop, or through bin directory inside Turbo C folder. The C editor will be opened.


2. Select “File” option from the main menu, a sub menu will appear on editor window. By pressing ALT + F keys or F10.Select either “saves option”. For
a new file to be created select “New” option from the sub menu. Save a new program file as filename’s extension /filename.cpp. In TC compiler .c
extension is not necessary (i.e. default extension of a C program is .c).Type the program in that file.

Compilation & Linking of a Program


1. Select “Compile” option from the main menu bar of C editor. A sub menu is displayed. During compilation Turbo C checks all the syntax errors. If no error then compilation proceeds and translated program is stored in another file
with the same file name with .obj extension (this is object file).


2. In linking all other program files and functions are put together. For example: If a programmer uses library function pow(), then the object code of this function should be brought from math.h library of system and linked to the main() program.

 

Executing the program


Select “run” option from main menu bar. If no error, then program is executed successfully. In this the executable object code (exe file) is loaded in
main memory

Some Short Cut Keys:

F2: To Save the program in a file.

Alt + F9: Compile the program

Ctrl + F9: Run or Execute the program

F7: Trace the execution and control flow of the program

Introductory Guidelines on C Programming

Ø Every C program requires a main () function. One program can have only one main () function.

Ø The execution of a function begins at the opening brace of the function and ends at closing brace.

Ø In general C programs are written in lowercase letters. However Symbolic names and output strings are written in uppercase.

Ø Every program statement in C language must end with a semicolon (;) called termination operator.

Ø All variables must be declared for their data type before they are used in the program.

Ø C is a free form language and therefore a proper form of indentation of C statements and comments must be used.

ØIf file is saved as a .C extension then inclusion of header files is optional in TURBO C compiler. But if file is saved as .cpp extension then inclusion of header file is necessary. Else compiler gives prototype mismatch error. This is so because definitions of prototypes of library functions are available in header files.

Questions and Ansewers

Q1: What are the C keywords?

Ans: The C keywords are reserved words by compiler. All the keywords have been assigned fixed meaning. extern, static, auto, typedef, struct, union, enum, register, volatile, void, const, signed, unsigned, short, long, char, int, float, double, if, else, while, do, for, switch, break, continue, default,
return, goto, sizeof … etc.

Q2: What is an operator? Explain Arithmetic and logical operators?

Ans: An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C language program to operate on data and variables.

(i) Arithmetic Operators

All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operators operate on a single operand, where operand can be a constant, a variable or a valid C expression. Binary operators operate on two operands.

(ii) Unary Operators:
+a (unary plus), -a (unary minus), ++a (pre increment) , !a(logical NOT).

(iii)Binary Operators
a+b (binary addition), a-b(binary subtraction),a*b(multiplication), a/b(division), a%b (Modulus division)

(iv)Logical Operators:

C has the following logical operators; they compare or evaluate logical and relational expressions. The output evaluated is either a true value or false value of an expression. Represented as 0 (false) , 1(True).

a|| b is Logical OR, a&&b is Logical AND , !a is Logical NOT

Q3: What is the difference between a constant and a variable?

Ans- The major difference is that the value of a constant cannot be changed, while the value of a variable can. You can assign different values to a variable whenever it’s necessary in your C program.

Q4: Why do you need a statement block?

Ans- Many C keywords can only control one statement. A statement block provides a way to put more than one statement together and put the statement block under the control of a C keyword. Then, the statement block is treated as a single statement.

Q5: What are the different data types?

Ans: In
computer programming
, a data type is a classification identifying one of various types of data, such as
floating-point
,
integer
, or
Boolean that determines the possible values for that type; the operations that can be done on that type; and the way the values of that type are stored.

Integer
: In more common parlance, whole number; a number that has no fractional part.

Floating-point: A number with a decimal point. For example, 3 is an integer, but 3.5 is a floating-point number. Another representation of floating point constant is 3.5 x 10-3 . Here 3.5 is a mantissa and 10-3 is exponent.

Character
(
text
):
Readable text

Q6: What are the differences between signed and unsigned data types?

Ans:  The qualifier signed or unsigned may be applied to char or any integer. Unsigned numbers are always positive or zero. So, for instance, if chars are 8 bits, unsigned char variables have values between 0 and 255, while signed chars have values between -128 and 127 (in a two’s complement machine.) Whether plain chars are signed or unsigned is machine-dependent, but printable characters are always positive.

Q7: What is the difference between “=” and “= =”?

Ans: = operator in C language is used to assign the value of right-hand side value/variable/expression to the left hand side variable .e.g: a = 4; here constant 4 at R.H.S is called r-value and identifier a at the L.H.S is called   l-value 
 = = Operator in C/C++ language is used to check the value of left hand variable/expression with the right hand Variable/expression. Whether the two values are equal or not. It returns true if these are equal else it will return false.
 e.g.      (2==3) : It means whether 2  is equal to 3 or not which is false so output is 0.
            (3==3) : It mean 3 is equal to 3 ,which is true so output is 1
 

Q8: What is the output of the following C code?

main ()

{

printf (“%d %c” , ‘A’ , ‘A’);

}

Ans:
65 A , (DUE TO %d ASCII value of A will be printed, and for %c character A.)

Q9: What do you mean by type conversion?

Ans : Type conversion or type casting is the method of changing the entity of one data type to another. data type. It is of two types implicit and explicit type casting.

Example: (i) Implicit type casting:
int a=5;

float c, b = 6.5;

c= b/a;


Here firstly a will be implicitly type cast into a float value i.e. 5.0, so division of 6.5 and 5.0 will yield the floating point value i.e. c will contain float value.

(ii) Explicit type casting:
( data_type) var_name

e.g: int a=5, b = 6 ; float c;

c= (float)b/a;

Q10: What is the output of arithmetic statement, S = 1/3 * a /4 – 6/ 2 + 2 / 3 * 6 / g ?Given that ( a = 4 , g = 3 , assume s to be an int type).**HINT: apply the concept of type casting.

Ans : S = – 3

Guidelines on C Operators

Ø A combination of constants, variables, and operators is called an expression in the C language. An expression is used to denote different computations.

Ø The arithmetic operators include +, -, *, /, and %.

Ø The C compiler treats a statement block as a single statement, although the statement block may contain more.

Ø The opening brace ({) and closing brace (}) are used to mark the start and end of a function definition in C language.

Ø A function body contains variable declarations and statements. Usually, a function should accomplish just one task.

Ø The arithmetic assignment operators, +=, -=, *=, /=, and %=, which are the combinations of the arithmetic operators with the assignment operator.

Ø The unary minus operator (-), which returns the negation of a numeric value.

Ø The two versions of the increment operator, ++. You know that in ++x, the ++ operator is called the pre increment Operator; and in x++, ++ is the post-increment operator.

Ø The two versions of decrement operator, –. You have learned that, for example, in –x, the — operator is the Pre-decrement operator, while in x–, — is called the post-decrement operator.

Ø The six relational operators in C: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater Than or equal to), and <= (less than or equal to).

 Guidelines on if – else , switch case statements and logical expressions

Ø Be aware of dangling else statements.

Ø Be aware of any side effects in the control expression such as if(x++) Use braces to encapsulate the statements in the if and else clauses.

Ø Check the use of = operator in place of the equal operator ==.

Ø Do not give any spaces between the two symbols of relation operators = =,

!=, >= and <=.

Ø Writing! =, >=and <=operators like =!, => and =< is an error.

Ø Remember to use two ampersands (&&) and two bars (||) for logical operators. Use of single operators will result in logical errors.

Ø Do not use the equal operator to compare two floating- point values. They are seldom exactly equal.

Ø Do not forget to use a break statement when the cases in a switch statement are exclusive.

Ø It is an error to use a variable as the value in a case label of a switch statement. (Only integral constants are allowed.)

Ø Do not use the same constant in two case labels in a switch statement.

Ø Avoid using operands that have side effects in a logical binary expression such as (x– && ++y). The second operand may not be evaluated at all.

Ø Try to use simple logical expressions.

Questions & Answers

Q1. Differentiate between if-else-if ladder & switch?

Ans: The if statement is used to select among two alternatives. It uses a Boolean expression to decide which alternative should be executed. The switch
statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

Q2. What is the function of “break” keyword?

Ans: The ‘break’ command will stop a loop from going any further. The ‘continue’ command will not stop a loop, but a ‘break ‘ command will.

Q3. What is the function of “continue” keyword ?

Ans: The ‘continue’ command will start the loop over at the top (or bottom) of the loop, bypassing other instructions that may be in the loop. The ‘continue’  command will not stop a loop, but a ‘break ‘ command will.

Q4. What do you mean by nested if else construct?

Ans: By using else If, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped. The statements of the final Else will be executed if none of the conditions are true.

Q5. What will be the output of the following segment when executed?

int x=10, y=20

if((x<y)||(x+5) >10)

printf(“%d”,x);

else

printf(“%d”,y);

Ans. Output- 20

Q6. What will be the value of x when the following segment is executed?

int x=10, y=15;

x=(x<y) ? (y+x) : (y-x) ;

Ans. Output – 25

Q7. Find the error, if any, in the following statements:

(a) if(x>=10) then

printf(“\n”);

(b) if x>=10

printf(“ok”);

(c) if(x=10)

printf(“good” );

Ans. (a) then is not used in C with if .It is not a C keyword. (b)Parentheses required in if condition i.e if (x > = 10) (c) No error

Q8. How can you print “Hello World” without using a semicolon in a C program?

Ans: /* Code segment*/
void main()

{ if (printf(“Hello World”))

{ } // Null body

}
In above program body of if block is a Null statement. Syntax of if requires a statement to be present, but the logic of the program does not require
it. Hence, null statement is placed

Q9.What is the dangling else problem?

Ans: When a program contains more number of if clauses than else clauses, then their exists a potential ambiguity regarding with which if clause does not match with else clause. This ambiguity is called Dangling else problem.

Guidelines on Switch- Case Statements

ØAn important task of a program is to instruct the computer to jump to a different portion of the code according to the specified branch conditions.

ØThe switch statement helps you to keep your program more readable when there are more than just a couple

ØDecisions to be made in your code.

ØThe case and default keywords, followed by a colon (:) and an integral value, are used in the switch statement as labels.

ØThe break statement can be used to exit the switch construct or a loop (usually, an infinite loop).

ØThe continue statement is used to let you stay within a loop while skipping over some statements.

ØThe goto statement enables the computer to jump to some other spot in your computer. Using this statement is not recommended because it may cause your
program to be unreliable and hard to debug.

Questions & Answers

Q1.What will be output when you will execute following c code?

#include
<stdio.h>

void
main(){

int
const X=0;

switch
(5/4/3){

case
X: printf(“Clinton”);

break
;

case
X+1: printf(“Gandhi”);

break
;

case
X+2: printf(“Gates”);

break
;

default
: printf(“Brown”);

}

}

Ans: Clinton will be printed

Q2. What will happen if we don’t use break inside switch case construct?

Ans: The break statement when used in a switch takes the control outside the switch. The control falls through all the cases unless the break statement is
given.

Q3. What is the purpose of goto? Is it a good programming practice?

Ans: Statement found in many computer programming languages. It is a combination of the English words go and to. When executed it causes an unconditional transfer of control (a “jump”) to another statement. The jumped-to statement is specified using some kind of label, which may be an identifier or a line number depending on the language. At the machine code level a goto is a form of branch or jump statement.

Q4. What must expression of switch statement be selection?

Ans: The switch statement evaluates an expression, which must have an integral result. Based on that result, a branch is taken to one of the case statements, or to the default statement if present and none of the case statements match.

Q5. Can we use continue statement within the body of switch statement like break?

Ans: No,a continue can appear only in or as a loop body. A switch statement is a branching statement is a branching statement and not a looping statement

Q6. Is it mandatory to have a case label or default labeled statements within a switch body?

Ans: No, it is not mandatory. A switch body can be a Null statement also.

e.g: switch (integral expression) { } // Null body

Q7. Can case labeled or default labeled statements exist without switch expression

Ans : No. Placing case labeled or default labeled statements outside the switch body leads to following error :- Case/Default outside of switch” compilation error.

Guidelines on Loops & Iterations

 Ø Looping can be used to perform the same set of statements over and over until specified conditions are met.

Ø Looping makes your program concise.

Ø There are three statements, for, while, and do-while, that are used for looping In C.

Ø There are three expression fields in the for statement. The second field contains the expression used as the Specified condition(s).

Ø The for statement does not end with a semicolon.

Ø The empty for (;;) statement can be used to form an infinite loop.

Ø Multiple expressions, separated by commas, can be used in the for statement.

Ø There is only one expression field in the while statement, and the expression is used as the specified condition.

Ø The while statement does not end with a semicolon.

Ø The while (1) statement can create an infinite loop.

Ø The do-while statement places its expression at the bottom of the loop.

Ø The do-while statement does end with a semicolon.

Ø The inner loop must finish first before the outer loop resumes its iteration in nested loops.

Questions & Answers

Q1. How does a for loop work?

Ans: There are three expression fields in the for statement. The first field contains an initializer that is evaluated first and only once before the iteration. The second field keeps the conditional expression that Must be tested before the statements controlled by the for statement are executed. If the conditional expression returns a nonzero value, which means the specified condition is met, one iteration of the for loop is carried out. After each iteration, the expression in the third field is evaluated, and then the expression in the second field is re-evaluated. The process (that is, looping) is repeated until the conditional expression returns 0.

Q2. What is the difference between the while and do-while statements?

Ans: The main difference is that in the while statement, the conditional expression is evaluated at the top of the loop, while in the do-while statement, the conditional expression is evaluated at the bottom of the loop. Therefore, the statements controlled by the do-while statement is executed at least once.

Q3. If any expression returns zero then condition will false and if it returns any non-zero number then condition will true. For example:

void
main()

{ int x=3,y=2; clrscr();

while(x+y-1)

{

printf(“%d “,x–+y); } getch(); }

Output: 5 4 3 2

Q4. In while loop whether condition expression is mandatory or not?

Ans: Yes it is mandatory, else it will give compilation error .For Example:

void
main()

{ clrscr();

while()

{ printf(“Hello world”); }

getch();

}

Output:
Compilation error

Q5.Can a single break statement be used to terminate a nested loop?

Ans: No, a single break statement can’t be used to terminate a nested loop. A break statement can only terminate the execution of the nearest enclosing loop.

Q6.What are the exit controlled loops?

Ans: In the exit controlled loops condition is checked after the execution of body of the loop.e.g: do-while loop. In this even if the condition is initially false, the body of the loop will be executed once. Example:

void main()

{

int i=2;

do

{ printf(“Condition is false , but this will be printed”) ; }

while(i<1) ;

Q8. Can the while statement end with a semicolon?

Ans: By definition, the while statement does not end with a semicolon. However, it’s legal in C to put a Semicolon right after the while statement like this: while (expression); which means there is a null Statement controlled by the while statement. Remember that the result will be quite different from what you expect if you accidentally put a semicolon at the end of the while statement.

 

Q9.For every use of a for loop, we can implement an equivalent while loop. So when should we prefer to use these in different programs?

Ans: A while loop is preferred over a for loop when the number of iterations to be performed is not known in advance. The termination of
the while loop is based on the occurrence of some particular condition, i.e specific sentinel value.Whereas the for loop is preferred when no. of iterations to performed are known beforehand

Q10. Which construct in provides the functionality to terminate the current iteration of the nearest enclosing loop?

Ans: The continue statement can be used. For example:

void main ()

{

int i , j ;

for ( i=1 ; i<3 ; i++)

for ( j=1 ; j < 4 ; j++ )

{ if ( j==2) continue ;

printf (“%d %d ” , i ,j ) ;

}

}

Ans: OUTPUT: 1 1 , 1 3 , 2 1 , 3 3

Q11 What will be the output of the following programs?

void main()

{ int i ;

for( i=5 ; ++i ; i- =3)

printf(“ %d “, i);

return 0 ;

}

Output: 6 4 2

Q12 What will be the output of the following programs?

#include<stdio.h>

#include<conio..h>

void main()

{

int c=5;

do

{ printf( “Hello”) ;

c++;

} while (c<5)

return 0; }
Output: Hello

Guidelines On Modular Programming Functions

Ø It is a syntax error if the types in the declaration and function definition do not match.

Ø It is a syntax error if the numbers of actual parameters in the function call do not match the number in the declaration statement.

Ø Using void as return type when the function is expected to return a value is an error.

Ø Variables in the parameter list must be individually declared for their types, we cannot use multiple declarations (like we do with local or global
variables).

Ø A return statement is required if the return type is anything other than void.

Ø A function without a return statement cannot return a value, when the parameters are passed by value.

Ø A function that returns a value can be used in expressions like any other c variable.

Ø When the value will be converted to the type of the variable receiving it.

Ø A return statement can occur anywhere within the body of a function.

Ø A function can have more than one return statement.

Ø A global variable used in a function will retain its values for future use.

Ø A local variable defined inside function. It is destroyed when the function is exited.

Ø A local variable declared static retains its value even after the function is exited.

Ø Static variable are initialized at compile time and therefore they are initialized only once.

Ø Use parameter passing by values as far as possible to avoid inadvertent changes to variables of calling function in the called function.

Ø Avoid the use of names that hide names in outer scope.

Ø A function is typically characterized by its name, type and parameters.

Ø It is a good practice to name a function on the lines of its functionality.

Ø A function can return multiple values.

Ø In case of ‘pass by reference’ function call the addresses of the variables are passed.

Ø Make sure that the parameters of a function are declared as pointer type for implementing pass by reference technique.

Questions & Answers

Q1: What are the advantages of the functions?

Ans: Debugging is easier. It is easier to understand the logic involved in the program. Testing is easier. Recursive call is possible. Irrelevant details in the user
point of view are hidden in functions. Functions are helpful in generalizing the program.

Q2. What is a static function?

Ans: A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.

Q3: What is the purpose of main ( ) function?

Ans: In our c program, every program starts with main () because it tells the c compiler where the program starts its execution. It always returns an integer value. It is a well defined user defined function.

Q4: What is an argument? Differentiate between formal arguments and actual arguments?

Ans: An argument is an entity used to pass the data from calling function to the called function. Formal arguments are the arguments available in the function definition. They are preceded by their own data types. Actual arguments are available in the function call.

Q5: What is meant by malloc() function?

Ans: Malloc function will allocate memory for pointers. Whenever you define a pointer it will just allocate 4 bytes to store the address of pointer and no memory for variable storage. Using malloc you can assign memory so that we can store variables and access through pointer.

e.g:- int *p;

*p=5; /* It will generate error as no memory allocated for pointer */


int *p;

p = (int*) malloc(4); /* allocates 4 bytes */

*p = 5; / * Now it works fine */


Q6: In the function printf(“The integer %d is the same as the hex %x”, 12, 12), what is the relationship between the format specifiers and the expressions?

Ans. The two format specifiers, %d and %x, specify the formats of numeric values contained in the expression section. Here the first numeric value of 12 is going to be printed out in integer format, while the second 12 (in the expression section) will be displayed in the hex format. Generally speaking, the number of format specifies in the format section should match the number of expressions in the expression section.

Q7. Can a function have more than one return statement?

Ans: Yes, a function can have more than one return statements but only one value will be returned by the function.

Q8. What is the meaning of keyword void before the name of a function?

Ans: Keyword void means that the function should not return any value.

Q9. What is the advantage of call by reference method of parameter passing in functions?

Ans: Using call by reference method a function can return more than one values at a time to the calling function.

Q10. What are the local variables with respect to a function?

Ans:The local variables are defined within the body of the function or the block. The variable defined is local to that function or block only. Other
functions can access these variables. The compiler shows errors in case other functions try to access the variables.

e.g: value ( int k , int m)

{

int r, t ; // Here r and t are local variables, defined within the body of function }

Guidelines On Pointers

ØA pointer is a derived data type in C. It is built from one of the fundamental data types of C. Pointer contains memory address as their values.

ØThe computer’s memory is a sequential collection of cells which have certain address. Whenever we declare a variable , the system allocates memory to
it a location number.e.g : int a =156 represented as:

156

2002

2002 is address location of a variable a whose value is 156. Declaration of a pointer

variable can be done as :int a = 24 ;

int * p ; // p is the pointer to integer variable a with some address

p = &a // p holds the address of a or p points to location of a

Similarly we can have pointer to float variable , character variable etc.

e.g : – float * fptr , char * cptr.

Ø * is called indirection operator(Value at address operator) or (dereferencing operator)

Ø & is called ampersand(Address of operator)

Ø %u is a specifier used to print the address of the variable.it stands for unsigned integer value as address is an unsigned integer itself.

Example for use of indirection operator

void main ()

{ int x , y ;

int * iptr ;

x = 10 ;

iptr = &x ;

y = * ptr ;

printf (“Value of x is %d \n \n ”, x) ;

printf (“%d is stored at address %u \n \n ”, x , &x) ;

printf (“%d is stored at address %u \n \n ”, *(&x) , &x) ;

printf (“%d is stored at address %u \n \n ”, *ptr , &ptr ) ;

}

In this code : *(&x) is known as “dereferencing ”

Double pointers/ Pointers to pointers:

void main ()

{

int a , * iptr , ** ptr2 ;

a = 20 ; iptr = &a ;

ptr2 = &iptr ;

printf (“%d ” , **ptr2) ; // Accessing value of var. a using pointer to pointer.

}


Above code will give value of a = 20 as a output. Here ptr2 holds the address of iptr which further holds the address of variable a.
Again **ptr2 is equivalent to *(&iptr), i.e. dereferencing of iptr.

 

 Arithmetic operations on pointers

Valid Operations


(i) Two pointer variables can be subtracted from each other. This will result in the difference in terms of number of bytes between two address
locations. e.g : ptr1 – ptr2 , where ptr1 and ptr2 are pointers.

(ii) A pointer variable can be incremented as well as decremented also. E.g :- ptr1++ , ptr –.

(iii) A constant can be added or subtracted to the pointer variable.


(iv) A pointer can be compared with the same type or with zero. A comparison of pointers is meaningful only when they point to the elements of the same
array.

 

Illegal pointer operations

 

(i) Addition of two pointers is not allowed.

(ii) Only integers can be added to pointers. It is not valid to add a float or a double value to a pointer.

(iii) Multiplication and division can’t be performed.

(iv) Bitwise operations can’t be performed.

(v) A pointer of one type can’t be assigned to pointer of another type (except void *) without explicit typecasting.

(vi) A pointer variable can’t be assigned a non-address value (except zero).

Points to remember

 

(i) The value of a variable can’t be assigned to a pointer variable

(ii) A pointer variable contains garbage until it is initialized. Therefore we must not use a pointer variable before it is assigned, the address of a
variable.

(iii) If we want a called function to change the value of a variable in the calling function, we pass the address of that variable to the called function.

(iv) it is erroneous to assign a numeric constant to a pointer variable.

(v) When an array is passed as an argument to a function, a pointer is actually passed. So such arrays must be declared with proper size, except the first,
which is optional.

(vi) A pointer to a function can be defined, which is used as an argument in another function.

Questions & Answers

Q1. What is a pointer type?


Ans: A pointer type is one of the derived data type because it is derived from the basic data types of C language like int , float , char etc.

Q2. What will the output of following piece of code be ?

void main()

{

int *a ; float *b , char *c ;

printf (“%d %d %d ” , sizeof (a) , sizeof(b), sizeof (c) ) ;

}


Ans : The output of above code is dependent on execution environment and the compiler used. If code is run on Borland TC 3.0 compiler for DOS, it
outputs 2 2 2. On Microsoft VC++ 6.0 compiler it outputs 4 4 4 . All the pointers are of 2 bytes or 4 bytes irrespective of whether they are pointer of
int , float , char , double etc.

Q3. Why does following piece of code does not compile successfully?

void main ()

{ int *ptr = 10 ;

printf ( “The value pointed to by pointer is %d ” , *ptr ) ;

}


Ans : The mentioned d piece of code gives compilation error i.e. illegal initialization of pointer. This is because pointer variable ptr is assigned a constant value which is wrong. Pointers can only hold the address.

Q4. In the expression *ptr ++ , which entity gets incremented: pointer or the value to which pointer points?


Ans: Dereference operator * and ++ are unary operator and unary operators are right to left associative. The expression *ptr ++ is interpreted as * (ptr ++). So here value of the pointer is incremented.

Q5. What is a NULL pointer? Is it same as un-initialized pointer?


Ans : The NULL pointer does not points to any object i.e. it doesn’t holds the address of any variable. No , the Null pointer is not same as un-intialized pointer. Un-initialized pointer may point any where.


e.g: declaration int *ptr = 0 ; and int *ptr = NULL , create a NULL pointer, named ptr
. Whereas declaration int * ptr creates an unintialized pointer.

Q6. What is void pointer?


Ans: Basically void is basic data type in C. void means nothing or empty. It is not possible to create an object of type void.e.g : void a ; is illegal declaration. So an object of type void can’t be created but it is possible to create a pointer to void . such a pointer is called void pointer withtype void*.

Note : (i) A pointer to any object can be assigned to void pointer. For example :

int a = 10 ;

int * iptr = &a ;

void * vptr = iptr ;

similarly if : float f = 5.6 ;

float * fptr = &f ;

void * vptr = fptr ; is lso valid

(ii) A void pointer can’t be dereferenced. (iii) Pointer arithmetic is not allowed on void pointers.

Guidelines On Arrays

Ø An array is a collection of variables that are of the same data type.

Ø In C, the index of an array starts at 0.

ØYou can initialize each individual element of an array after the declaration of the array, or you can place all initial values into a data block surrounded by { and } during the declaration of an array.

Ø The memory storage taken by an array is determined by the product of the size of the data type and the dimensions of the array.

ØA pointer is said to refer to an array when the address of the first element in the array is assigned to the pointer. The address of the first element in an array is also called the start address of the array.

ØTo assign the start address of an array to a pointer, you can either put the combination of the address-of operator (&) and the first element name of the array, or simply use the array name, on the right side of an assignment operator (=).

Ø A character array is considered a character string in C if the last element in the array contains a null character (\0).

ØThe null character (\0) marks the end of a string. C functions, such as printf(), will stop processing the string when the null character is encountered.

Ø C supports multidimensional arrays, too. A pair of brackets (the array subscript operator—[ ] indicates a dimension.

Ø The compiler can automatically calculate the memory space needed by an upsized array.

 

Questions and Answers

 1. Why do you need to use arrays?

Ans. In many cases, you need to declare a set of variables that are of the same data type. Instead of Declaring each variable separately, you can declare all variables collectively in the format of an array. Each variable, as an element of the array, can be accessed either through the array element reference using subscript or through a pointer that references the array.

2.What is the minimum index in an array?

Ans. In C, the minimum index of a one-dimensional array is 0, which marks the first element of the array. For instance, given an integer array, int array_int[8];

The first element of the array is array_int[0]. Likewise, for a multidimensional array, the minimum index of each dimension starts at 0.

3. How do you reference an array by using a pointer?

Ans. You can use a pointer to reference an array by assigning the start address of an array to the pointer. For Example, given a pointer variable ptr_ch and a character array array_ch, you can use one of the following Statements to reference the array by the pointer:

ptr_ch = array_ch;

ptr_ch = &array_ch [0];

4.What can the null character do?

Ans. The null character (\0) in C can be used to mark the end of a string. For instance, the printf() function Puts the next character on the screen when the null character is encountered. Also, the null character always returns FALSE in a logical test.

5. What happens when an array with a specified size is assigned

            a. With values fewer than the specified size: and

            b. With values more than the specified size

Ans. a) Wastage of memory .Free memory locations are assigned a garbage value or 0 in case of integer array

b). Access to the memory locations that does not belong to the array. This illegal memory access may be fatal

and may even crash the program.

6. Are the expression arr and &arr same, if arr is an array of type int , float , char etc. ?


Ans : No , both are different and have a different meaning . First arr means base address of array (address of first element of an array). Secondly
&arr yields a pointer to an array of given type.

7. What is the result of sizeof operator when applied to an array of certain size?

Ans : sizeof operator when applied to an array give sthe total number of bytes occupied by array elements.

         e.g: int arr [10] = { 1, 23 , 16 , 8 , 11 , 5 } ;

          printf (“%d” , sizeof (arr)) ; This will give output as 10 x 2 = 20 bytes.

8. What is a dynamic array?

Ans : Dynamic array is that whose size can be changed at run time according to the users requirement. This can be performed using library functions calloc
() and malloc () available in <stdlib.h> header file

 9. How are 2- D arrays stored in C language?

Ans : 2-D arrays are stored in a Row major form in C language.2-D arrays can be visualized as a single dimensional array whose each element is a single
dimensional array.

10. it mandatory to specify the row and column size in a 2-D array?

Ans : If initialization list is not present then row size and column size are mandatory. But if initialization list is given Then the row size specifier can
be skipped, but it is mandatory to specify the column size

.

Character Arrays and String Handling

 

Ø An string is a character array with a null character (‘\0’) as the terminator at the last element.

Ø A string constant is a series of characters enclosed by double quotes.

Ø The C compiler automatically appends a null character to the array that has been initialized by a string constant.

Ø You cannot assign a string constant to a de referenced char pointer.

Ø The strlen() function can be used to measure the length of a string. This function does not count the null character in the last element.

Ø You can copy a string from one array to another by calling the C function strcpy().

ØThe gets () function can be used to read a series of characters. This function stops reading when the newline character or end-of-file (EOF) is encountered.A null character is attached to the array that stores the characters automatically after the reading.

ØThe puts() function sends all characters, except the null character, in a string to the stdout, and appends a newline character to the output.

Ø You can read the different data items with the scanf() function by using various format specifiers

Ø To use library functions of strings header file string.h must be included in the program

Questions and Answers

Q1. What is the use of strcmp() function ?

Ans: The function strcmp()is widely used in sorting of lists of names. Synatx is strcmp(str1,str2), where str1 and str2 are the name of the two strings .The function compares lexicographically (directory style) str1 with str2. It returns -1, 0 , 1 respectively if str1< str2, str1= = str2 , str1> str2.

Q2. What is the working of int isalnum(int c) , int isalpha(int c) and int isdigit(int c) library functions?

Ans: (i) int isalnum(int c): This returns true if c is a digit or alphabet, false otherwise.

(ii)int isalpha(int c) : This returns true if c is a letter , false otherwise.

(iii) int isdigit(int c) : This returns true if c is a digit character, false otherwise.

Q3. What is the difference between the following charcter array declarations?

(i) char str2[10] = “ JAVA” ; (ii) char name [] = “JAVA”.

Ans: (i) In this initialization value of str2 i.e. JAVA will occupy first 4 blocks of memory followed by null char ‘\0. Each block is size of
1bytes. So actual length will be 4 + 1= 5 bytes. The rest of the 5 bytes will be unused. So memory space is wasted.


(ii) In this the size of the string is only 5 and all the memory space is fully utilized. Character array name will be
automatically assigned the maximum size of 5 bytes.

Q4. Distinguish between the following array initializations:

(i) char ch = ‘A’ ; (ii) char kh [] = “A” ; (iii) char str [] = “ ” ;

Ans: (i) char ch = ‘A’ ; // A variable ch has value ‘A’ , size = 1 byte

(ii) char kh [] = “A” ; // A string has one character in it , size = 2bytes

(iii) char str [] = “ ” ; // An empty string , size = 1 byte.

 

Q5. What is the use of getchar() function ?

Ans: This function reads a single character at a time , i.e. gives access to a single character which may be manipulated. For example, the character can be
changed by a new character, a lower case letter may be changed to upper case letter and vice versa, a character can be removed from the string.

Q6.How strings can be represented with pointers?

Ans: Pointer to single string may be declared in the same way as the pointer to a 1-D array. e.g:

char name [] = “C is a middle level language” ;

char * ptrname ;

ptr name = name; // Base address of array name is passed to the pointer variable

ptrname.

Guidelines on Structures

 ØStructure is a collection of heterogeneous data i.e. different type of data elements, which are accessed separately. This is a user defined data type.

Østruct keyword is used to declare a new structure with some valid identifier name. This indicates that the name is of type struct(a user defined data type.)

Ø Declaration of a structure is done as follows:

struct userdefined_name

{

data_type member1; // data_type can be int , float, char , double etc.

data_type member2; // member is data like name, roll_no, salary, age, sex etc.

…………………….

…………………….

data_type membern;

} ;

Example: // Declaration and initialization of a structure Health_data

struct Health_data

{

char name [15] ;

int age_years ;

int height_cm ;

float weight_kg ;

} ;

struct Health_data S1 = { “John Ghezzi”, 20 , 175 , 72.40};

struct Health_data S1 = { “Charlie”, 27 , 163 , 58.0};

struct Health_data S1 = { “Mathew D’Souza, 45 , 182 , 82.5};


In above initialization S1 , S2 and S3 are variables or instances of structure Health_data, which represent three different objects of this structure.

** This is the direct initialization of structure variables.

 

ØAccessing structure member elements using dot operator also known as member access operator. General syntax is var.member. In
this method we give the printf() function within

The main() for structures as follows :

printf(“Name of S1 = %s\n”, S1.name) ;

printf(“Age of S1 = %d\n”, S1.age_years) ;

printf(“Height of S2 = %d\n”, S2.height_cm) ;

printf(“Weight of S3 = %f\n”, S3.weight_kg)

 

** Note : In a similar way member elements of an structure can be read through the keyboard

using scanf() function within the main(). For example:

scanf(“%s %d %d %f”, &S1.name,&S1.age_years, &S1.Height_cm,&S1.Weight_kg) ;

 

** Structure elements can be accessed using pointers also in two ways as follows:

(i) struct data

{

char name [15] ;

————–

————–

} ; struct data *ptr1; // ptr1 is pointer variable to structure named data.

Elements can be accessed as: (* pointer_name) . member = value ; // using dot operator

OR

pointer_name -> member = value ; // using arrow operator

 

Questions and Answers

Q1. Which operator is used to access the member variables of a structure?

Ans:To access the member variables of a structure dot operator or member access operator is used.

Q2. How are structure elements stored in the memory?

Ans Structure elements which are of different data types like int, float , char , double etc. are stored successively in memory are stored.

Q3. What is the use of arrow operator(->) in the structures?

Ans: With the help of arrow operators structure elements can be accessed using pointer variable which refers to the define structure.

 

Q4. Differentiate between array and structure.

Ans: (i) Arrays are used to store the data of same type (i.e. Heterogeneous data), whereas structures are used to Store the Heterogeneous data.

(i) As compared to structures, Arrays are less useful where increases amount of data largely.

Q5. What is the difference between Union & Structure?

Ans: (i) Union contains number of data members like structures but it holds only one object at a time.

(ii) In the structure each member has its own memory location whereas, member of unions have same memory locations.

(iii) Union accommodates one member at a time in a single area of storage.

(iv) Union requires bytes that are equal to the number of bytes required for the largest I members.e.g: if union contains char, integer and long then the no.of bytes reserved in t the memory for union is 4 bytes.

Q6. Why structure is known as user defined data type?

Ans: Structures are considered as a user defined data type because name of the struct type is user dependent , which has several elmenets with some real world information like name , age, salary, employee ID etc of basic data types (like int , float , char) or derived data type like (arrays,
pointers).

Guidelines on Dynamic Memory Allocation, Stack & Link List

Ø Dynamic memory allocation deals with allocation & de-allocation of memoru space at the time of execution of a program. This technique is
used where number of data nd information is not known beforehand and it may increase or decrease in future depending on certain situations. For Example


Let a company launches new model of a car and starts the booking. The number of customers interested in booking the car is not known apriori. So here
structures, arrays can be allocated memory at run time rather than at compile time.

Ø The memory allocated by system to a program is divided into three portions (i) Memory for functions (ii) Memory for data (iii) Free memory called heap which may be required during execution of the program.

ØSome library functions used in dynamic memory allocation have their prototype definition in header file <stdlib.h>.
These functions are as follows:-

 

(i )malloc(): This stands for memory allocation This function allocates a block of memory of the size of its argument in bytes. It returns a void
pointer to the first byte of the memory block

Synatx: void * malloc (size) ;

e.g: int *ptri;

ptri= (int*) malloc (n *sizeof(int)) ;

The function malloc allocates n*sizeof(int) bytes of memory and returns the value of pointer ptri.

Return value of malloc is the value of ptri which is the address of the first byte of the memory block.

Let n=2 , then total bytes occupied are 2 x 2=4 bytes. This is how an array can be allocated memory at run time

**In case allocation is not possible due to lack of sufficient memory , ther return value

will be NULL pointer

.For example Code can be:

if (ptri= = NULL)

printf (“Error in memory allocation”) ;

exit(1) ;

Similarly for character array: char * ptrch;

ptrch= (char*) malloc (n *sizeof(char)) ;

 

In the same way we can create n structures dynamically as follows:

struct book

{

cahr name[15] ;

int pages ;

}

struct book*ptrb ;

ptrb = (struct book*) malloc(n*sizeof(struct book)) ;

 

(ii) calloc( ): This stands for calculated allocation.This function is used to allocate an array of memory blocks

and initializes each block member to 0. It returns a void pointer to the first byte of the first block

of the memory. As compared to malloc function calloc has two arguments.

 

Syntax: void* calloc (n , size_mem) ; // Here n is no.of blocks; size_m is size of each block

 

(iii) realloc( ) :This function reallocates a memory block of size smaller or bigger than the size of the block

earlier allocated by malloc().

Syntax: void* realloc (void *ptr , new_size) ;

e.g: float *ptrf = (float *) malloc ( 5 * sizeof(float) ) ; // allocates 5 x 4= 20 bytes of an array

ptrf = (float *) realloc ( ptrf, 3 * sizeof(float) ) ; // resized array of 3x 4=12 bytes.

 

(iv) free( ) : This function is used to de-alloacte thememory allocated by the functions malloc() , calloc()

and realloc().The whole allocated memory block is released.

Syntax: void free (void *ptr ) ;

 

 LINK LISTS

Ø The major application of dynamic memory allocation lies in creation of link lists.

Ø The objects in the link lists are linked together not like as arrays sequentially one after another, rather objects can be stored randomly in memory ,
but each element in the list keeps the address of the next element in the list , or address of both the neighbours, i.e : the previous as well as the
next in the list.

Ø Each location is called a node of link list .Each node has two fields “data and address”. If the node contains only one memory address, it is
called a singly linked list. But if it contains address of just previous & next node then it is known as a doubly linked list.

Ø Each node of a link list is created using structures where data member of a structure node is pointer to that structure.

Creation of a Singly Link List:

Struct List

{

char name [20] ;

int number;

struct List *nextnode ;

} ; struct List *First ; // First is a pointer of the type struct List.

 

Now the structure object pointed to by First must be allocated memory so as to store the data items. This is Implemented using malloc()as given below:

 

First = (struct List*) malloc (sizeof (struct List)) ;

typedef struct List Node ;

 

First = (Node*) malloc (sizeof(Node)) ;

The data items in this node may be initialized, as well as, a memory block may be createdfor the next node.

 

First -> name = “Dennis Ritchie”;

First -> number = 80 ;

First -> Next = (Node* malloc) (sizeof (Node)) ;

 

Points to remember :

 

(i) Pointers of any type may be assigned to void pointer; however, on dereferencing, type casting is needed and programmers don’t remember this.

(ii) In singly link list the pointer value of next of last node must be NULL.

(iii) Programmers forget to put statement for freeing the memory after deletion of a node. This leads to memory leak(unavailable memory).

 

STACK: This is another linear data structure which is created dynamically with the help of 1-D Arrays.

Ø A stack can have any abstract data type as an element, but is characterized by only three fundamental operations: push, pop .

 

Ø push operation adds a new item to the top of the stack,or initializing the stack if it is empty, but if the stack is full and does not contain more space to accept the given item it is considered as an Overflow state (It means that the stack is overloaded or no more space for new item

 

Øpop operation removes an item from the top of the stack , A pop either reveals previously concealed items, or results in an empty stack, but if the stack is empty then it goes into underflow state (It means no items are present in stack to be removed).

Guidelines on Macros & C Pre processors

 

Ø Macros are the identifiers that represent statements or expressions. To associate meaningful identifiers with constants, keywords, and statements or
expressions, #define directive is used.

Ø  If we define a macro i. e SQUARE(x) x*x. Here the macro determines the square of the given number.

Ø Macro Declaration: #define name text

For example : DEFINEMA.C

#include<stdio.h>

#include <conio.h>

#define SQUARE(x) x*x

void main()


{

0int i = 2;

int j= SQUARE(i);

printf(“The value of j is: %d\n”, j);

getch();

return 0;

}

 

output:

DEFINEMA.EXE

 

Ø the #define directive is typically used to associate meaningful identifiers with constants, keywords, and commonly used statements or expressions. Identifiers that represent constants are sometimes called “symbolic constants” or “manifest constants.

Ø Identifiers that represent statements or expressions are called “macros.” In this preprocessor documentation, only the term “macro” is used.

Ø Because macros do not generate actual function calls, you can sometimes make programs run faster by replacing function calls with macros.

MACROS AND C-PREPROCESSORS

 1. What is Macro template?

Ans. Macro template is defining the macro at the beginning of a program using ‘#’directive. For example

#define CUBE (X ) ( X * X* X) .
2. What are the types of Macro?

Ans. (a) Object type Macro (b) Function types Macro.

3. What is undef directive?

Ans. This cause the specified identifier to be no longer defined as a macro name. For example:

.# undef PI

4.What is the difference between #include<stdio.h> and #include”stdio.”h.


Ans. These are source file inclusion directives, the first way of inclusion searches the prespecified list of directories for the source file within < >.The second way the source file is first searched in the current working directory, if the search fails then prespecified list of directories are searched .If still the search fails,then compiler gives an error unable to include file.

 

Guidelines on File Handling in C

 

Ø A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind.

Ø There are two kinds of files that programmers deal with text files and binary files.

Ø A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward
direction.

Ø For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.

Ø A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent.

 

Ø Opening a file: The general format of the function used for opening a file is

FILE *fp;

fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. fopen() contain the file name and mode (the purpose of opening the file).

r is used to open the file for read only.

w is used to open the file for writing only.

a is used to open the file for appending data to it.

 

Ø Closing a File -A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. The input output library supports the function to close a file.

Syntax to close file

fclose(filepointer);

Example:

#include<stdio.h>


#include <conio.h>

void main(void)

{

FILE *myfile;

char c;

myfile = fopen(“firstfile.txt”, “r”);

 

if (myfile == NULL)

printf(“File doesn’t exist\n”);

else {

do {

c = getc(myfile);

putchar(c); } while (c != EOF); }

 

fclose(myfile);

}

 

Ø File operation functions in C:

Function Name Operation
fopen() Creates a new file. Opens an existing file.
fclose Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file

 

FILE HANDLING

 

1. What is EOF?

Ans. It is a symbolic constant which stands for end of file.This is an integer with value -1,it tells when a file pointer *fp reaches to the end of file.

 

2. Can we access the file using its name?

Ans. No. The file can only be accessed using the file pointer.

 

 

3. What types of errors may occur in file handling?

Ans. (a) Omission of File Pointer.

(b) Opening a File which does not exist.

(c) Reading a File which is in write mode.

(d) Writing into a file which is in read mode.

 

4. What is a stream?

Ans. Stream is a continuous series of bytes that flows into or out of a program. Input and Output from physical devices or from disk devices are handled
with streams.

 

 

 

Standard stream Description Associated file/device
Stdin Standard Input Keyboard
Stdout Standard Output Screen
Stderr Standard Error Screen
Stdprn Standard Printer LPTI:port

 

 

5. Can I make the stream stdout be printed somewhere other than the screen?

Ans. Yes, the stream stdout can be printed other than the screen by redirecting it which meanschanging the target file or source file of an open stream.

 

You may also like

Unified Platform for Technical Universities (UPTU) Notes is a one-stop destination of all academic need. its a Global community of scholars to facilitate the sharing of knowledge and resources and sparking discourses on the various bodies of knowledge.

Edtior's Picks

Latest Articles

@2022 – All Right Reserved. Designed and Developed by Softweblink.

JEE Advanced 2022: Provisional answer keys out