best notes in c language for b

128
Notes Of C Language By Cj-SofTech Opp Punjabi Univ. Patiala

Transcript of best notes in c language for b

Page 1: best notes in c language for b

Notes

Of

C

Language By

Cj-SofTech

Opp Punjabi Univ.

Patiala

Page 2: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

2

C Language Programs

S.no Name of the Program

Simple programs(1 to 15)

1. WAP print “hello”.

2. Write a program to add two numbers. (without scanf()).

3. Write a program to add, multiply, divide, subtract two numbers. (Without scanf()).

4. WAP to find out simple interest. (Without scanf()).

5. WAP to enter 5 subjects’ marks and calculate total marks and percentage.

(With scanf()).

6. Write a program to give name of item, cost, qty and calculate total bill.

7. Write a program to input marks and calculate total marks and the percentage.

8. Write a program to input the length and breadth of rectangle to calculate its area.

9. Write a program to calculate d=(b*b)-4*a*c/quadratic equation.

10. Write a program to convert centigrade to Fahrenheit.

11. Write a program to input five ages and find the average.

12. Write a program to swap two numbers without third number.

13. Write a program to swap two numbers with third number.

14. Write a program to input radius and find the area of circle.

15. Write a program to print int,float values using format specifiers.

Conditional Statements

Simple If(16-21)

16. Write a program to find the smallest from two numbers.

17. Write a program to input age of a person and find whether he/she is eligible for voting or not.

18. WAP to Input marks in three subjects calculate total marks and percentage if per>=50 then print pass else fail.

19. Write a program to input a number and find whether it is –ve or +ve.

20. Write a program to find whether a given number is odd or even.

21. Write a program to find whether the year is leap or not.

Nested If (22-27)

22. Write a program to find greatest from three integers.

23. Input age of a person conditions are

if age<12 then child if age between 12 to 25 then young if age between 25to 50 then adult if age >=50 old.

24. WAP to calculate the division of a student after getting valid marks for

three subjects with the conditions that percentage>60 is First division, percentage<60&>40 is second division, percentage<40 is third division.

25. Input basic pay and calculate total pay (basicpay+bonus) conditions are Pay<1000 then bonus 10% if pay between 1000 to 3000 then bonus 9% if

pay between 3000 to 5000 then bonus 8% if pay>=5000 then bonus 7% .

26. Input two nos and a choice if choice is ‘a’ add it if choice is ‘s’ subtract it

Page 3: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

3

and if choice is ‘d’ divide it otherwise give message wrong key pressed.

Looping programs

While loop (28-30)

27 Write a program to print name ten times.

28. Write a program to print series from 1 to 10.

29. Write a program to print sum of first five natural numbers.

30. Write a program to count odd numbers from 1 to 100.

do while (31-33)

31. Write a program to print series 2,4,8/3,9,27

32. Write a program to print the series up to n-2..

33. WAP to count even numbers between two numbers given.

For loop(34-36)

34. Write a program to print 9 99

999 9999

35 Write a program to print 10 101

1002 10003

36.

Write a program to print

1 12 123

1234

Important Looping Programs(37-43)

37. WAP to find whether a given number is Palindrome or not.

38. Write a program to print fibbonacci series.

39. Write a program to print table of a given number.

40. Write a program to print the sum of even numbers up to n.

41. Write a program to print the sum of squares of even numbers up to n.

42. Write a program to print the factorial of a given number.

43. Write a program to check whether a given number is prime or not.

More Problems of Loops and Nested Loop (44-51)

44. Write a program to print the series of prime numbers up to n.

45. Write a program to print prime numbers between two numbers.

46. WAP to print Armstrong numbers upto 1000.

47. Write a program to enter number in octal and convert it into decimal.

48. Write a program to enter a number in decimal and change it into octal.

49. Write a program to change from binary to decimal.

50. Write a program to decimal to binary.

51. WAP to print table of given number entered by the user AND also check for prime number.

Strings(52-56 )

52. Write a program to change the string from upper to lower case.

Page 4: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

4

53. Write a program to reverse the given string.

54. Write a program to concatenate two strings.

55. Write a program to find whether a given string is palindrome or not.

56. Write a program to count a specific character in a word.

57. WAP to find length of a string.

58. WAP to find number of vowels, whitespaces in a string.

Arrays

Single Dimensional arrays(57-65

59. Write a program find biggest and smallest element in array.

60. Write to merge two arrays with same size.

61. Write a program to insert an element in an array at a specific location.

62. Write a program to sort an array.

63. Write a program to input name and age of a person and print name once and age three times.

64. Write a program to search a given element from an array.

65. Write a program to count the number of occurrences of a given number in

an array.

Multidimensional arrays(66-72)

66. Input the value of 3*3 matrices and display it input days of a week and display it.

67. Write a program to add two matrices.

68. Write a program to subtract two matrices.

69. Write a program for matrix multiplication.

70. Write a program to find the sum of diagonal elements of a matrix.

71. Write a program to find the transpose of a given matrix.

72. WAP to find a specific word from string.

Structures and Unions(73-76)

73. Write a program to input the name and roll no of ten students and print it using structures

74. Write a program to input the name and roll no of ten students and print it using Unions

75. WAP to enter two matrices (2*2) using structures and add them.

76. WAP to enter name, age, father name, city of a student and print using

structures

Functions(77-89)

ADD TWO NUMBERS USING FUNCTIONS 77 Without arguments without return

Page 5: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

5

78 With arguments without return 79 Without arguments with return

80 With arguments with return

AVERAGE OF FOUR NUMBERS USING FUNCTIONS

81 Without arguments without return 82 With arguments without return

83 Without arguments with return 84 With arguments with return

85. WAP to add, subtract, multiply, Divide using Functions.

86. Input basicpay ,ta, da and calculate total pay with return with argument .

87. Write a program to pass array as an argument to a function.

88. WAP to find the factorial of a given number using recursion.

89 WAP to find the sum of the digits of a given number using recursion.

Pointers(90-92)

90. Write a program to find largest among n numbers using pointers and arrays.

91. Write a program to swap two numbers using pointers.

92 Multidimensional arrays and pointers and WAP to add two matrices , passed as arguments (as ref) using pointers.

File Handling programs(93-97)

93 Write a program to input the name and store it in a file.

94 WAP to copy the contents of one file into another.

95 Two files contains sorted lists of integers. WAP to produce a third file

which holds a single sorted, merged list of these two lists.

96 Write a program to read from and write into a file.

97 WAP that will generate a data file containing the list of customers and their corresponding phone numbers. Use a structure variable to store the

name and telephone of each customer. Create a data file using a sample list.

OTHER IMPORTANT PROGRAMS

98 Input 3 digits no print sum of its digits.

99 Input 3 digits no print reverse of it.

100 Print

1 12

123 1234

12345

Page 6: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

6

Chapter 1 INTRODUCTION TO PROGRAMING LANGUAGES

Programming Languages Programming languages are the languages used to make programs that can

be executed by the computer using compiler or interpreter. We can create programs, application software, web sites etc with the help of these

programming languages. Programming language can be categorized as below.

• Low Level Language.

• Assembly Language. • High Level Language.

Low Level Language (Machine Language) Machine Language is a language that a computer can understand, but it is

very difficult for the human beings to understand. Programs written in machine language consist of machine instructions. Machine language

consists of strings of binary numbers (0, 1). Each microprocessor can have different machine language.

Advantages: 1. Machine language instructions are directly executed, so there

is no compilation or translation needed, that’s why it is fast in execution.

2. Machine language uses computer memory very well. Disadvantages:

1. Machine language is a machine dependent.

2. It is very difficult to remember the codes. 3. Modification is difficult in machine language program.

4. High programming skills are required to develop programs in machine language.

Assembly Language In 1950s operation codes [opcodes] were developed. Assembler is used to

convert these codes into to machine language. Like it is difficult to remember any code like(01010001 for add) instead of this binary code in

assembly language we use ADD to add contents of two registers.

Advantages: 1. Assembly language programs are easier to use than machine

language. 2. Error detection is possible and easy.

3. Modification is simple in assembly language program. 4. Less efforts are required as compared to machine language in

writing the program.

Assembly language program

Assembler Machine language program

Page 7: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

7

Disadvantages:

1. These languages are fully machine dependent language. 2. Good programming skills are required to develop a program in

assembly language. HIGH-LEVEL LANGUAGE (HLL)

High level languages are very powerful and these are similar to English language. C, C++, Java, Visual Basic etc are the examples of HLL.

Advantages: 1. HLL are easy to learn and understand.

2. It is very easy to write the program. 3. Mostly the syntax of all high level languages are similar.

4. Knowledge of hardware is not essential to write program.

5. Program written in HLL are easy to modify. Disadvantages:

1. Compiler or interpreter is required to convert HLL into low level language.

2. Due to conversion these are slower in speed. 3. Specific hardware and

software are required for some high level language. Compiler And Interpreter

Compiler and interpreter both are used to convert the high-level language program into the object code.

Interpreter:- Interpreter convert the program of High level language into Low level language line by line.

Compiler: - Compiler converts the whole program at a time from High level Language into Low level language.

Features of a good programming language Every programming language has some speciality in it, which make a

language suceesful. These specialities help languages to be popular in the computer world. These specialities are also known as features, which are as

follows:- 1) Easy to use:- A good programming language must be simple &

easy to learn. The concept should be simple & easy to learn. The concept should be clear & can be easily grasped. The simple languages

are easy to develop & to implement.

High level language program

Compiler / interpreter

Machine language program

Source code

Interpreter Object code

Source code

Compiler Object code

Page 8: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

8

2) Extensibility:- A good programming language should be

extended to sub-program. It increases the readability of the language. 3) Efficiency:- Programs written in a good language should be

efficient. That is, program should take less space & time to run efficiently.

4) Better documentation :- A good programing language should be easily understood by programmer. Coding should be precise and

logics should be upto mark. 5) Flexibility:- A good programming should have a mechanism to

control the computers CPU, memory & registers. 6) Fewer errors:- A good programming language should have

compilers & interpreters which can automatically detect syntax errors. So these can be easily corrected by the programmer.

COMMON LANGUAGES

1) BASIC ( BEGINNERS ALL PURPOSE SYMBOLIC INSTRUCTION

CODE):- All purpose symbolic instruction ) It is designed in 1964 by John George Kemeny and Thoman kurtic. It is easy for beginners,

provide error messasges, no need to understand hardware. Its based on fortran-2nd + ALGOL.

2) ALGOL( ALGORITHM C LANGUAGE) :- Developed in 1950. It is the first language that implement nested functions.

3) FORTRAN(FORMULA TRANSLATOR):- It is developed for numeric computation and scientific calculation and it is developed by

IBM in 1950. 4) COBOL:- Common Business-oriented language design for

business, finance administrative systems. Cobol 2002 also support object-oriented programming.

5) LISP:- (List processing) It is used to implement lists that is a major data structure developed in 1958.

7) BCPL:-( Basic combine programming language) It can

perform task of many language ‘C’ is based on this language. 7) LOGO:- It gives graphics. It is develop in 1968. It is used to

create simple programs that can contain simple graphics. 8) SQL (STRUCTURE QUERY LANGUAGE):- It is used in databases

to create database and access information from it.

History Of 'C' language Many programming languages have been created

according to the programmer requirement. In earlier days programmer had to learn many languages to

perform different tasks. A language called BCPL(Basic Combined Programming Language)

designed by Martin Richards of the University of Cambridge in 1966 that perform work of many types,

this language is also known as ‘B’ language.C

Page 9: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

9

language is the modified version of basic combined programming language

called ‘B’ Using this language Dennis Ritchie developed ‘C’ language at the AT&T bell laboratories in 1972. It is one of the most popular computer

language. This language is also known as High level language as it is closer to

human languages and faster from machine language. NOTE:- C is a case sensitive language . It means uppercase alphabets are

different from lowercase alphabets e.g. ‘A’ is totally different from’a’

Why we use 'C' language 'C' was developed in 1972 but still programmers use this language due to

following reasons. (1) C is portable means program written for one computer may run

successfully on other computers. (2) C is fast means the executable program runs very fast.

(3) C is compact i.e. the statements written in 'C' language are

generally short and very powerful. Several operators can be used in one statement.

(4) C language has both the simplicity of high level language and speed of low level language, so it is also known as middle level

language. (5) 'C' Compiler is easily available.

(6) It supports pointers that can be used to create system programming.

(7) It can be run on UNIX operating system also. (8) Large number of inbuilt functions are available.

(9) C has ability to extend itself. Users can add their own functions to the c library.

(10) Program of c can be divided into small modules called functions. These function can be reused any time by the user.

Limitations Of 'C' language or Constraints in C (1) 'C' language does not support exception handling.

(2) Bound checking is not performed by the 'C' compiler. (3) 'C' language does not support concepts of OOP.

(4) 'C' language does not support Unicode characters. (5) Pointers are difficult to understand for the beginners.

C/C++ compilers

• Turbo C++ • Borland C++

• Pelles C • Intel C++

• VisualAge C++ • Tiny 'C' Compiler

CJ SOFTECH Walia Enclave Opp Punjabi UnCJ SOFTECH Walia Enclave Opp Punjabi UnCJ SOFTECH Walia Enclave Opp Punjabi UnCJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.iv Patiala.iv Patiala.iv Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 10: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

10

Phases Of Software Development:

A software development process consists of various phases, each phase ends with some defined output that become the input of next phase. The

phases are performed in a specific order. The main reason to develop software in phases is to ensure that software should be developed in

given time and cost. Various phases to develop a program are:- 1. Requirement analysis phase: The Requirement analysis identifies

what is needed from the software. Requirements analysis is done in order to understand the problem that will be solved by the software. This phase

bridges the gap between client and the programmer. The outcome of this phase is the software requirement specification document (SRS). The

person responsible for the requirements analysis is often called the analyst.

2. Software Design: The purpose of this phase is to plan a solution of the problem specified by the SRS.

It is of two types:

• System Design or Top level Design: It identifies the various modules that should be in the system, the specifications of the

modules and interconnections between the various modules. DFDs[Data Flow Diagram] are the part of system design.

• Detailed Design: It identifies the internal logic of the various modules. Data structures, algorithms, flow charts are developed in

this part of the designing phase. 3. Coding: This phase convert the design of the software into code using

some programming language. Well written code can reduce the testing and maintenance cost and efforts.

4. Testing:- Its basic function is to detect errors in the software. After the coding phase, programs are executed for testing purpose.

The different types of testing are: a. Unit testing:-It tests each module separately and detects coding

errors in the module.

b. Integration testing:- When we test all modules individually, now it is time to combine all modules with each other. Integration testing is

performed when we combine the modules with each other. c. System testing:- In integration testing we combine all the modules

now we will test whole of the project it is known as system testing. d. User Acceptance Testing: - This testing is performed by the user to

check whether system is created according to the needs of the user or not.

5. Implementation: After testing, software is implemented on the client computer to perform its actual work.

Client –server approach

Frontend:- Frontend is used by the user. The user doesn’t known anything about the back process e.g. ATM is a machine where user is working as

frontend user. Softwares used for frontend are VB,ASP.

Page 11: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

11

Backend:- Softwares used in backend are foxpro,oracle,sql server etc.

Backend is handled & maintained by the database administrator(DBA).e.g. ATM’s back process is controlled by the programmer.

Errors Errors are the bugs that can produce unexpected results, mainly errors are

divided into two types. 1. Syntax errors: These errors occur due the incorrect method to

write the code. It may be due the missing comma, semi colon etc. Like in following line, error will be displayed because string is not enclosed

in " ". printf(hello);

2. Logical errors: These errors are not due to any syntax mistake, but due to incorrect logic. The compiler does not show the logical

errors. Like to find average of 4 numbers if we forget to write brackets then the result will not be according to our expectation

avg=10+20+30+40/4; in this the value of avg=70 instead of 25.

Programming techniques:-Various Programming techniques are used to make the program simple, understandable and easy to modify. Some of the

commonly used programming techniques are:- 1. Top down design: - Using this design, program is divided into the

smaller blocks, which can be linked and called whenever needed. When it is called it begins from the bigger block to the smaller till the program

ends. 2. Bottom up design: - It is also designed in the same manner and

divides the whole program into the smaller blocks, but when it is called it begins from the smaller block to the bigger till the program end.

3. Modular design: - A level consists of one or more modules. Each module performs its own task and each module has minimal contact with

other modules, so that each module can be implemented separately. Execution is controlled by the main program

Generations Of Computer Languages

First-generation Language First-generation language is the lowest level computer language.

Information is given to the computer by the programmer in binary form. Binary instructions are the same as on/off signals. The language consists of

zeros and ones. Second-generation Language

Assembly language was the second generation of computer language. Assembly language consists of letters of the alphabet. This makes

programming much easier as compared to binary form. Third-generation Language

These languages are similar to spoken English. Third-generation computer languages are much easier than first two generations.

Fourth-generation Language

Page 12: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

12

Fourth-generation languages typically consist of English-like words and

phrases. These languages can include graphic such as icons and buttons etc .

Important Questions [Short Questions] 1. What do you mean by Programming language?

2. Write History of 'C' language. 3. What are ASCII Codes?

4. Write difference between high level language and low level language.

5. Define compiler. 6. Define interpreter.

7. Define assembler. 8. Name various high level language.

Important Questions [Long Questions] 1. Explain phases of software development.

2. Write Applications of 'C' language .

3. Write limitations of 'C' language . 4. Advantages and limitations of High level languages.

5. Advantages and limitations of Low level language. 6. Explain errors and various types of errors.

7. Write Note on: a. Top-Down Approach

b. Bottom-up Approach 8. Explain Various Generations of Computer language .

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 13: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

13

Chapter 2 BASIC OF 'C' LANGUAGE

Before Writing 'C' Program Before starting programming in ‘C’ Language, it is better to learn some basic

concepts like:- 1. Important logics that will be used in common 'C' programs.

2. Character set of 'C' language. 3. Constants

4. Variables

5. Keywords 6. Data types

7. Operands 8. Operators

9. How to open 'C' Compiler. 10. Compile and run 'C' program

11. Open and save 'C' program. 12. Algorithms and Flow Charts.

1. Basic Logics [Formulas]: Some of the basic formulas that we will use in 'C' are:-

Area of Rectangle A=L*B

Area Of Circle A=3.14*R*R

Volume Of Box V=L*B*H

Average Of 3 Numbers AVG=(A+B+C)/3

Convert Fahrenheit

Temperature To Centigrade

°C = 0.56(°F – 32)

or 5/9(°F – 32)

Convert Centigrade

Temperature To Fahrenheit

°F = 1.8(°C) + 32

or ( 9/5 x °C) + 32

Area Of Square A=L*L

Area Of Triangle A=(L*B)/2

Swap A and B T=A A=B

B=T

Discriminant of Quadratic equation

D=B*B-4*A*C

2. Character set: A character represent alphabet, digit or special symbol that we can use in 'C' language. In 'C' we can type mainly

three types of characters.

1) Alphabets :A to Z and a to z

2) Numbers: 0,1,2,3,4,5,6,7,8,9 3) Special Symbols : { } ” : ; [ ] ( ) + - * & ^ % < . ? , = !

# etc

Page 14: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

14

3. Constant: The value of a constant is fixed and we cannot

change the value of the constant. We use const keyword to declare constant in 'C' language.

Types of c constants:- 'C' constants can be divided into two major categories.

a) Primary constants Integer constants, real constants, character constants.

b) Secondary constants Array, pointers, structures, union, enum.

4. Variables: The value of variable can be changed during the

program. Variables can be local or global. Local variables: Local variables are defined with in the pair of braces

or between the body of the function. The scope of the variable is with in the function.

Global variables: These variables are defined out side of all the

functions. And these variables can be used in any function with in the file because the scope of these variables are global to the file.

Difference between constant & variable:-

5. Keywords: Keywords are the reserved words with some specified function. The meanings of keywords are already defined in 'C'

compiler. We cannot use keywords as variable names. In C there are 32 keywords like if, for, while, void, int, float, do, break, continue,

goto, struct, enum, double etc.

6. Data types: The value stored in variable or constant depends upon data type, or we can say Data types represent what type of data

will be stored in the variable . In 'C' language we have three basic datatypes int(used to store numbers without decimal), float(used to

store numbers with or without decimal), char(used to store

alphanumeric characters). Data types available in C are :-

Constant Variable

1) Constant value doesn’t

change during execution of the program.

1) Variable vary during

execution of the program.

2) It is fixed quantity. 2) It’s value can be changed.

3)e.g. z=2x+5y here 2,5,are constants.

3)e.g. z=2x+5y here x,y are variables.

Page 15: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

15

TYPE SIZE (Bits) Format Specifier Range

char

8

%c -128 to 127

int or signed int

16

%d -32768 to 32767

unsigned int

16

%u 0 to 65535

long int or signed

long int

32

%ld -2147483648 to 2147483647

unsigned long int

32

%lu 0 to 4294967295

float

32

%f 3.4 e-38 to 3.4 e+38

double

64

%lf 1.7e-308 to 1.7e+308

long double

80

%Lf 3.4 e-4932 to 3.4 e+4932

7. Operands: c=a+b, In this expression a,b,c are operands.

These are variables that store any value.

8. Operator: operators refer to symbols that represent a particular operation to be performed on data. Types of operators are:-

Assignment operator: Assignment operators are used to assign the values to a variable. Assignment operators are (+=,-=,/=,*= etc).

Arithmetic operator: These are used to perform arithmetic calculation on the operands. Arithmetic operators are +,-,*,/,%.

Relational operator: Use to check relation between operands. E g. >,<,<=,>= etc.

Logical operator: These operators are used to attach more than one relational operator in one statement. These are &&(AND), ||(OR),

!(NOT).

Conditional operators: These are used when we want to execute the statements according to the condition.

Bitwise operators:Bitwise operators are special operators designed to work on the bit level.

Bitwise Operator

Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< Shift left

>> Shift right

~ One’s complement

Page 16: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

16

9. How to install c into your computer:-

1) First of all , find turboc .exe file. 2) Copy this file and paste it on c:drive.

3) Now, open DOS prompt. 4) Type cd\ and press enter.

5) C:\turboc.exe –d. It will extract all directories from turboc c to your c drive.

10. How to open 'C' Compiler. If you are writing program in windows98, 2000,2003,XP then you can

use any compiler of 'C'. But if you use windows vista or window 7 then it is better that you use 32-bit or 64-bit Compiler according to the

operating system. Steps to open 'C' compiler

1. Select Run from start and type command or cmd in run box.

2. At DOS Prompt type [if 'C' is installed in c drive]

cd\ cd tc

cd bin

tc

Page 17: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

17

3. With these commands 'C' editor will open that look like

To maximize use alt+enter

4. To start new program select new from file menu

5. Following screen is displayed to type program.

Page 18: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

18

11- Compile and run 'C' program To compile the program select compile option from the Compile menu or

Press Alt + F9

To run the program select run option from the run menu or Press Ctrl + F9 12. Open and save 'C' program.

To open a file select open from file menu or press F3, and to save select save form file menu or press F2,the extension of 'C' program is

.c Steps to take C programs in printed form:

1) Go to c:\tc\bin and press enter.Right click on the file having

extension .c or .cpp and open it with notepad. 2) Now go to file menu of notepad & click on print option.

3) The printed form of required C program will be in your hands.

Algorithms Algorithms are the English like steps to solve a problem. It is the part of

software designing. Before creating a program or software we develop its design using some tools like algorithms, DFDs, Flowcharts etc. Mainly we

follow following steps to design an algorithm. Step 1. START //it represents beginning of the algorithm

Step 2. DECLARE //the variables used in algorithm are declared in this step. Step 3. INPUT // here we input the values

Step 4. FORMULA// the required result is generated in this step. Step 5. OUTPUT // display the result.

Step 6. STOP // end of algorithm

**We can use if else, goto ,loops etc according to requirement

Flowchart:-

Page 19: best notes in c language for b

Basics of 'C' language

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

19

A flowchart is pictorial representation to solve a problem. It is the graphical

representation of an algorithm. Also we can say that these are the symbolic diagrams which tells the user about the data flow, sequence and processing

logic in information processing.

We can use following symbols to create flowchart

Symbol Symbol Name Symbol Description

Process

Show a Process or action step. Any kind of

processing like mathematical calculations are depicted using processing box. It is nothing but

a rectangle which indicates processing.

Flowline

(Arrow)

Flow line shows the direction of flow of control.

Decision Decision box is used when there are 2 options (Yes/No). It is used as if-else. It is used to take

any decision in the program. It returns the value in true or false.

Connector Connector connects the various portion of the flowchart.A connector is used when the flowchart is

split between two pages

Input/output This is used to input and print data .

Terminator It represents starting and ending point of the flowchart. We use start & stop option in it. The

shape of terminal symbol is in oval shape.

Algorithm

Step 1: START Step 2: PRINT “hello”

Step 3: STOP

Flowchart

Q1. Write an algorithm and draw flowchart

PRINT

START

STOP

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 20: best notes in c language for b

Basics of 'C' language Page No: 20

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Q2. Write an algorithm and draw flowchart

to add 2 numbers. Flowchart:-> Algorithm :

Step 1: START Step 2: DECLARE A,B,C

Step 3: A=10 Step 4: B=20

Step 5: C=A+B Step 6: PRINT C

Step 7: STOP

Q3. Write an algorithm and draw

flowchart to add, sub, mul, div 2 numbers.

Algorithm Step 1: START

Step 2: DECLARE A, B, ADD, SUB, MUL, DIV

Step 3: INPUT A, B Step 4: ADD A+B

Step 5: SUB A-B Step 6: MUL A*B

Step 7: DIV A/B Step 8: PRINT “SUM=”, ADD

Step 9: PRINT “SUB=”, SUB

Step 10: PRINT “MUL=”, MUL Step 11: PRINT “DIV=”, DIV

Step 12: STOP

DECLARE A,B,C

C=A+B

PRINT C

A=10

B=20

START

STOP

START

Declare A, B, SUM, SUB, MUL, DIV

INPUT A,B

PRINT “SUM=”, ADD

PRINT “SUB”, SUB

PRINT “MUL=”, MUL

PRINT “MUL=”, MUL

STOP

ADD = A+B

SUB = A-B

MUL = A*B

DIV = A/B

CJ SOFTECH Walia Enclave Opp Punjabi UnCJ SOFTECH Walia Enclave Opp Punjabi UnCJ SOFTECH Walia Enclave Opp Punjabi UnCJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.iv Patiala.iv Patiala.iv Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 21: best notes in c language for b

Basics of 'C' language Page No: 21

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Q4.Write an algorithm and draw flowchart

to find greatest among two numbers. Algorithm

Step 1: START Step 2: DECLARE A, B

Step 3: INPUT A, B Step 4: IF A>B THEN GOTO STEP 5 ELSE GOTO STEP 6 Step 5: PRINT “A IS GREATEST” GOTO 7 Step 6: PRINT “ B IS GREATEST”

Step 7: STOP

Y

Pseudo code:-Pseudo code is like an algorithm but pseudo codes are nearer

to the program. It is the outline of the program and it cannot be compiled nor executed. It is easy to covert Pseudo code into program as compare to

algorithm. TOKENS:-The individual words ,special symbols , operators, punctuation

marks are called tokens.These are given below:

Keywords

Constants

Operators

Identifiers

Special symbols

Strings

C Tokens

START

DECLARE A,B

INPUT : A, B

IF A>B then PRINT: A IS

BIG

PRINT: A IS BIG

STOP

N

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 22: best notes in c language for b

Basics of 'C' language Page No: 22

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

COMMENTS:These are the statements which are not executed by the compiler . It means that these statements are ignored by the compiler.

Comments can be of two types:- 1) Single line comments

2) Multi line comments Single line comments:- Single line comments are used to display any

statements for understanding of the user.It can be used by using double slash (//) symbols.

e.g. //Single line comments Multi line comments:- When user wants to write number of statements for

knowledge of the user,but ignored by the compilers then we use multi line comments.

e.g. /*----------------- ------------------*/

Important Questions [Short Questions] 1. Define Character set Of 'C' language.

2. Define Constant and Variables. 3. Define Keywords.

4. Define Data types. 5. Define Operand and Operators .

6. How we can open 'C' compiler and run our program? 7. Write Difference between ‘a’ and “a”.

8. What are shorthand or shortcut or short circuit assignment operators?

Important Questions [Long Questions]

1. Define algorithms and basic structure of an algorithm. 2. Define Flowchart and symbols used in it.

3. Explain basic Data types of 'C' language.

4. Write algorithm and draw flowchart to find simple interest. 5. Write an algorithm to find roots of the quadratic equation.

6. Explain operators present in 'C' language.

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 UrUrUrUrban Estate Phase ban Estate Phase ban Estate Phase ban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 23: best notes in c language for b

Basics of 'C' language Page No: 23

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 3

START PROGRAMING IN 'C' LANGUAGE As we discuss we can use various approaches to develop software. Today

languages are based on two main concepts Procedural Programming and Object Oriented Programming. ‘C’ is procedural language and ‘C++, Java’

are Object Oriented languages. In procedural language functions are created to perform various tasks. Functions can be inbuilt or user defined

and in object oriented language classes are created. Classes are the combination of functions and data.

'C' language is a procedural language where every thing is done in the form of functions. In 'C' language we have two main types of functions

1. Inbuilt 2. User defined functions.

Inbuilt functions are pre defined in the 'C' compiler and we use them

according to the requirement, work of inbuilt functions are fix. With the help of inbuilt functions and statements we create user define functions. 'C'

program can contain any number of user define functions. But one of them must be main function. Main function is the entry point of the program,

compiler run the working of program from main function, all the other functions are directly and indirectly called by the main function.

Basic Structure of 'C' program Explaination of Basic structure of ‘C’

HEADER FILES:These include all the library functions,macros, it contains

inbuilt functions like printf , scanf , getch etc.In C there are 24 header files.

Global Variable declaration

Page 24: best notes in c language for b

Basics of 'C' language Page No: 24

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

PREPROCESSOR DIRECTIVE:- It instructs the C compiler to add contents

of an include file into program during compilation. Include files should have .H extension

e.g #include<stdio.h> GLOBAL VARIABLE DECLARATION:- There are some variables which are

used in different function.It is better to declare such variables outside of all the functions.These variables are called global variables.

MAIN FUNCTION SECTION:- Every program of C must have one main() function. All statements written under this function must appear between the

opening & closing braces. FUNCTION DEFINITION:- This section contains all user defined

function.These user-defined functions are always called in the main function.

Rules to create a program in 'C' language. 1. Each statement mostly ends with a semicolon (;).

2. The statements in a program must be written in

the same order in which we want to execute them. 3. All statements are written in small letters.

4. Every program must have main function. 5. clrscr() function should be written after variable declaration.

6. Program should be saved with the extension .c .

Some important functions An ISO C standard libraries is made of 24 header files, which can be used

into a program. Each header file contains one or more functions and macros, it contain inbuilt functions. In beginning we mainly use only two header files.

1. stdio.h : standard input output header file, it contains functions to input data in the program and take output from the program. Eg printf(),

scanf() functions etc 2. conio.h : console input output header file, it also contains some

additional input output functions.

Eg getch(),putch(),clrscr() etc � printf():- printf function is used to take output from the

program. � scanf():- scanf function is used to give input in the program.

� clrscr():- used to clear the screen. � getch():- To input a character.

What is a Program? It is defined as the set of instructions that we give to computer as input

through keyboard. Program is also known as passive entity and program in execution is called active entity.

Before writing program in 'C' language, it is always better that we write an algorithm of it. [Especially when we are new in programming]. In this book

we write algorithms with the some programs so that beginners can understand programs easily.

Write algorithm and program to print “hello world”

Page 25: best notes in c language for b

Basics of 'C' language Page No: 25

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Step1 Start

Step2 Print “hello world” Step3 Stop

To write a program from algorithm, we step by step convert the steps into program.

Algorithm Program

Step1 Start void main()

{

Step2 Print “hello world” printf(“hello world”);

Step3 Stop }

When we use inbuilt function in the program it is better to include header files of that functions like printf function is define in stdio.h so we include

this file in our program. The program become like this. We compile the program with alt+F9. It displays errors. After removing the

errors we can run the program using Ctrl+F9.Complier runs the program and control come back to the editor screen, we can use Alt+F5 to view result.

Output:- hello world

If a program work on some variables then we need to declare these

variables with the help of data types. We need to follow some rules to declare variables.

� The variables should be declared before clrscr() function. � Use variable names that mean something. Single-letter variables

are difficult to understand so it is better to use long names like index is better than i, count is better than c, and name is better

than n. � Variables are typically in lowercase. They can contain letters and

numbers. � Uppercase letters can be used in variable names.

� You should not begin a variable name with a number. They can contain numbers, but you begin it with a letter.

� "underscore" character can be used in variablenames like first_name, roll_no etc.

� We can not use keywords as variable names eg variable name

like int,if,float are invalid. � We can not create more than one variable with same name in

same scope.

#include<stdio.h> void main() { printf(“hello world”); }

Page 26: best notes in c language for b

Basics of 'C' language Page No: 26

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write algorithm and program to print sum of two numbers

Step1 Start Step2 declare a,b,c

Step3 a=10 Step4 b=20

Step5 c=a+b Step6 Print c

Step7 Stop

.Algorithm Program

Step1 Start void main()

{

Step2 declare a,b,c int a,b,c;

Step3 a=10 a=10;

Step4 b=20 b=20;

Step5 c=a+b c=a+b;

Step6 Print c printf(“%d”,c);

Step7 Stop }

In printf we need format specifier to print value of the variable like we use %d to print value of variable c. Some times we use getch() to avoid pressing

Alt+F5. and clrscr() function if we want to clear the screen. clrscr() function

should be used after the variable declaration.

Output:- 30

If we write printf function like :- printf(“sum=%d”,c); Output:- sum=30

Write algorithm and program to swap two numbers Step1 Start

Step2 declare a,b,c Step3 a=10

Step4 b=20

#include<conio.h>

#include<stdio.h>

void main()

{

int a,b,c;

clrscr();

a=10;

b=20;

c=a+b;

printf("%d",c);

getch(); }

Page 27: best notes in c language for b

Basics of 'C' language Page No: 27

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Step5 c=a

Step5 a=b Step5 b=c

Step6 Print a Step6 Print b

Step7 Stop

Algorithm Program

Step1 Start void main() {

Step2 declare a,b,c int a,b,c;

Step3 a=10 a=10;

Step4 b=20 b=20;

Step5 c=a c=a;

Step5 a=b a=b;

Step5 b=c b=c;

Step6 Print a printf(“%d”,a);

Step6 Print b printf(“%d”,b);

Step7 Stop }

Output:- a=20 b=10

scanf function:- It is used to take input from the user. It contain format specifiers and variables. Eg:- scanf(“%d”,&a);

%d is format specifier, & is address operator and a is a variable name which store value that we enter.We can also enter more than one

variable in scanf function like scanf(“%d%d”,&a,&b);

Qualifier :-It give properties to an identifier. The const type qualifier

declares an identifier to be fixed [not changeable]. The volatile qualifier declares an identifier whose value can rightfully be changed.

#include<conio.h>

#include<stdio.h>

void main()

{

int a,b,c;

a=10;

b=20;

c=a;

a=b;

b=c;

printf("a=%d ",a);

printf("b=%d ",b);

getch(); }

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 2 2 2 Patiala Patiala Patiala Patiala

Page 28: best notes in c language for b

Basics of 'C' language Page No: 28

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write algorithm and program to enter two numbers and print

sum of these numbers. Step1 Start

Step2 Declare a,b,sum Step3 Print “Enter value of a”

Step4 Input a Step5 Print “Enter value of b”

Step6 Input b Step7 sum=a+b

Step8 Print sum Step9 Stop

.Algorithm Program

Step1 Start void main() {

Step2 declare a,b,sum int a,b,sum;

Step3 Print “Enter value of a” printf(“Enter value of a”);

Step4 Input a scanf(“%d”,&a);

Step5 Print “Enter value of b” printf(“Enter value of b”);

Step6 Input b scanf(“%d”,&b);

Step5 sum=a+b sum=a+b;

Step6 Print sum printf(“%d”,sum);

Step7 Stop }

In this program we use format specifier %d for int in scanf function.

Output:- Enter value of a 10

Enter value of b 20 Sum=30

*10 and 20 will be entered by the user through keyboard We can use float, long, double data types according to the

requirement. And if we want to work on characters we use char data

type.

#include<conio.h>

#include<stdio.h>

void main()

{

int a,b,sum;

printf("Enter value of a ");

scanf("%d",&a);

printf("Enter value of b ");

scanf("%d",&b);

sum=a+b;

printf("sum=%d",sum);

getch(); }

Page 29: best notes in c language for b

Basics of 'C' language Page No: 29

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write a program to input and print a character.

Output:

Enter a character G

character =G We can also assign a character without scanf function, but character

should be in single quotes like ‘a’ ‘F’ etc

Output:- character=A

The Escape Sequences

Escape Sequences are used for formatting the output string mainly written in printf(). It consists of backslash followed by a character. The character

sequence is always enclosed in the control string. Various escape sequences are

\n the next line character \t tab position

\a used for sound \r carriage return

\b shifts cursor one position left

#include<conio.h>

#include<stdio.h>

void main()

{

char ch;

clrscr();

printf("Enter a character ");

scanf("%c",&ch);

printf("character=%c",ch);

getch(); }

#include<conio.h>

#include<stdio.h>

void main()

{

char ch;

clrscr();

ch='A';

printf("character=%c",ch);

getch(); }

Page 30: best notes in c language for b

Basics of 'C' language Page No: 30

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Without any Escape sequence:

printf(“hellobye”); Output:

hellobye With \n Escape sequence:

Using \n the output will be shifted to next line printf(“hello\nbye”);

Output: hello

bye With \t Escape sequence:

Using \t some space[TAB]will be displayed before printing next information

printf(“hello\tbye”); Output:

hello bye

With \b Escape sequence: After \b one character from the left of \b is deleted

printf(“hello\bbye”); Output:

hellbye With \r Escape sequence:

Using \r position of the cursor come to the beginning of the line. printf(“hello\rbye”);

Output: byelo

With \a sequence: It produce beep sound.

printf(“hello\abye”); Output:

hello[beep sound]bye

I/O functions in 'C' language

Input/Output means to receive data from any input device and send data to the output device respectively.

I/O functions can be classified into two types: 1. Disk I/O functions: These are the functions that perform I/O

operations on secondary storage device like floppy, hard disk etc. 2. Console I/O functions: These are the functions that receive

input from keyboard and write output to screen. These functions are further classified into two types:

a. Unformatted I/O Functions b. Formatted I/O Functions

Page 31: best notes in c language for b

Basics of 'C' language Page No: 31

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Unformatted I/O Function

1. getch(): When we type a character, the character would not be displayed on the screen but it is assigned to a variable immediately

without pressing enter button from the keyboard. For e.g.

char A: A=getch();

2. getche(): When we type a character, the character is displayed on the screen and assigned to a variable immediately without

pressing enter button from the keyboard. For e.g.

char A: A=getche();

3. getchar(): The typed character is displayed on the screen but it is assigned to a variable when we press enter button from the

keyboard.

For e.g. char A:

4. A=getchar(); 5. gets(): It is used to input string. We can also input spaces

between the various words of the string. 6. putch() or putchar(): These functions are exactly the same and

use to print a character to screen. 7. puts: It is used to print the string on the monitor.

Formatted I/O Functions 1. scanf(): In scanf we can input integer, float, char, string

simultaneously. The limitation of this function is that we cannot enter space between the words of the string.

2. printf(): This function is used to display values of int, float or plain messages to the user. Syntax is:

printf(“format string”,variablelist); Type casting Or Type conversion

It is used to convert the one data type into another temporarily. It can

be implicit or explicit. Implicit type conversion is automatically performed by the computer and explicit type conversion is performed by

the programmer.

void main() {

int a=5;

float b; b=a/2;

printf(“b= %f”,b); }

Output:- b= 2.000000

void main() {

int a=5;

float b; b=(float)a/2;

printf(“b= %f”,b); }

Output: b=2.500000

Page 32: best notes in c language for b

Basics of 'C' language Page No: 32

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Important Questions and programs[Short Questions]

1. Explain printf and scanf functions. 2. Explain the use of clrscr function.

3. Write a program to convert centigrade temperature into Fahrenheit temperature.

4. Write a program to swap two numbers with third variable. 5. Write a program to swap two numbers without third variable.

6. Write rules to create a simple 'C' program.

Important Questions and programs[Long Questions] 1. Write a program to print sum of digits of two digit number.

2. Write a program to reverse a three digit number. 3. Write a program to input cost and quantity. Give 10% discount

on total bill 4. Input marks in four subjects of a student. Print total and average

marks.

5. Explain escape sequences. 6. Explain various input output functions.

7. Explain Structure of the 'C' program. 8. Write various rules for variable declaration.

** Perform Programs from 1 to 15 from program list

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 33: best notes in c language for b

Basics of 'C' language Page No: 33

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 4 OPERATORS

Operators are the symbols that are used to perform various operations on

data, like arithmetic operations, comparison or logical operations etc.Operator refers to a symbol that tells the computer to perform certain

mathematical or logical tasks on operands. Operators can be Unary and Binary. Unary Operators work on one operand like –a, b++ etc and

Binary operators work on two operators like a+b, a*c etc. C provides different types of operators as follow:-

1) Arithmetic operators 2) Logical operators

3) Assignment operators 4) Relational operators

5) Bit wise operators 6) Unary operators

7) sizeof operator

8) Comma operator 9) Conditional operator

These operators are performed on operands and operands are the variables on which these operations are performed.

e.g x+y In this x,y are operands and + is operator and x+y is called expression.

1). Arithmetic operator:- These operators are used in arithmetic

operations. C provides all the basic arithmetic operators like +,-,*,/,%. The modulus(%) operator tells us what would be the remainder after integer

division.

NAME SYMBOL IN C

Addition +

Subtraction -

Multification *

Division /

Modulus %

Arithmetic operators are classified into 3 categories :-

a) Integer arithmetic:-When arithmetic operators are performed on two integers i.e a,b are integers , then the expression is known as an integer

expression and this operation is called integer arithmetic. e.g. if a & b are integer like a=9,b=4

then a+b=13

a-b=5

Page 34: best notes in c language for b

Basics of 'C' language Page No: 34

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

a*b=36

a/b=2 (decimal ignored as it is an integer arithmetic) a%b=1 (remainder)

b) Real arithmetic:- The Operators which are performed only on real operands, called real arithmetic. Real operands may include decimal or

exponential notation. e.g a=9.0 and b=4.0

then a/b=9.0/4.0=2.250000 NOTE:- The operation % cannot be used with real operands.

c) Mixed mode arithmetic:- It is the combination of real operand & integer operand. In this case if either operand is of real type then result will

always be is a real no. e.g 25/10.0=2.5 whereas 25/10=2

2) Logical operators: - The logical operators && and || are used when we want to test more than one condition to make decisions. The result of logical

operator AND (&&) will be true only if both the conditions are true, whereas

the result of a logical operator OR (||) will be true if one or more conditions are true. In other words, the result of a logical OR operation will be false

only if all conditions are false.

logical operators

e.g. 1) (age>18 && age<=25)

2) (number<0 || number>10)

LOGICAL AND (&&)

AND (&&) is a logical operator that will give result if and only if all of its conditions are true.

Condition1 Condition2 Result Value

False False

True True

False True

False True

False False

False True

0 0

0 1

LOGICAL OR (||)

OR (||) is a logical operator that will give result if minimum one of its

condition is true.

NAME SYMBOL IN 'C'

AND &&

OR ||

NOT !

Page 35: best notes in c language for b

Basics of 'C' language Page No: 35

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Condition1 Condition2 Result Value

False

False True

True

False

True False

True

False

True True

True

0

1 1

1

LOGICAL NOT (!)

NOT (!) is a logical operator that convert true into false and false into

true.

Input Output Value

False True

True False

1 0

3) Assignment Operators: - It is used to assign value to the

variable. Value can be any constant value or evaluation of an expression. It evaluates the expression on right hand side and then assigns the value

to a variable on the left hand side. Some assignment operators are:

OPERATOR EXAMPLE MEANING

+= X+=4 x=x+4

-= y-=3 y=y-3

*= Z*=4 z=z*4

/= p/=9 p=p/9

%= i%=2 i=i%2

e.g a=4 //assigns value 4 to variable a

x=a // assigns value of a to x

z=a+x //performs addition & assigns result to z

4) Relational Operators:- The relational operators are used to check the relation between two operands. These are used to compare

two different quantities and then to take decisions e.g we may compare salary of two employees , age of two students and so on. It

can be done by using relational operators. These operators are used with decision making statements such as if-else, for , while etc.

e.g. let a=1,b=5 then a<b is true

but b<a is false

It means the result of relational operators is returned as either true or false i.e.1 or 0.

Page 36: best notes in c language for b

Basics of 'C' language Page No: 36

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

NAME 'C' SYNBOL

Greater than >

Less than <

Equal to ==

Not equal to ! =

Greater than or equal to >=

Less than or equal to <=

5) Bit Wise Operators: -These operators are used for testing the

bits, or shifting them right or left. These operators are used for manipulation of data at bit level.

1. Bit wise logical operators a. Bit wise and (&)Bit wise or (|)

b. Bit wise xor ( ^ ) 2. Bit wise shift operators

a. Bit wise left(<<) b. Bit wise right(>>)

3. Complement operator(~)

Operator Meaning

& Bit wise Logical AND

| Bit wise OR

^ Bit wise XOR

<< Left shift

>> Right shift

~ Complement

#include<stdio.h>

#include<conio.h> void main()

{ int n,m,and,or,com,rs,ls,xor;

n=11; m=5;

and=n&m;

or=n|m; xor=n^m;

com=~n; ls=n<<2;

rs=n>>2; printf("\n n&m=%d",and);

printf("\n n|m=%d",or);

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 37: best notes in c language for b

Basics of 'C' language Page No: 37

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

printf("\n n^m=%d",xor);

printf(“\n ~n=%d",com); printf("\n rs>>2=%d",rs);

printf("\n ls<<2=%d",ls);

}

Output:- n&m=1

n|m=15 n^m=14

~n=-12 rs>>2=2

ls<<2=4

How Bitwise operators produce this result?

[in description we assume int is of 8 bit or 4 bit. But in 'C' language integer is of 16 bits]

The binary of n(11)= 00001011 The binary of m(5)= 00000101

a. n&m 1011

0101 0001 which is=1 so n&m=1

b. n|m 1011

0101 1111 which is=15 so n|m=15

c. n^m

1011 0101

1110 which is=14 so n^m=14 d. ~n

00001011 complement of this is 11110100 which =-12 in 2’s compliment system

e. n<<2 00001011 when we shift 2 bits left then value=00101100

Which is=44 so n<<2=44 f. n>>2

00001011 when we shift 2 bits right then value=00000010 Which is=2 so n>>2=2

6) Increment / Decrement operators:- The increment

operators increase the value of an operand by 1 and decrement

operator decrease the value of an operand by 1.It is of types: - a) Increment (++)

b) Decrement (- -) Example

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 38: best notes in c language for b

Basics of 'C' language Page No: 38

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

int a=5; a++:

printf(“%d”,a);

Output is 6 means ++ operator increase the value by 1.

Example

int a=5;

a--:

printf(“%d”,a);

Output is 4 means -- operator decreases the value by 1. Increment or Decrement operators are further two types: -

1) Pre increment operator/Pre Decrement operator

2) Post increment operator/post Decrement operator. Both operators increment or decrement the variables but at different times.

The statement ++x increments x before using its value, while x++ increments x after its value has been used.

The x++ or x-- reads the value & store a copy of it at temporary location. The computer increments or decrements the variables, & the temporary

copy is used in expression. e.g.

int x,y; x=5;

y=x++; printf(“x=%d,y=%d\n”,x,y);

o/p :- x=6,y=5

Example of pre increment operator

#include<stdio.h> #include<conio.h>

void main() {

int a=5,b; b=++a;

printf(“\na=%d”,a); printf(“\nb=%d”,b);

getch();

}

output:- a=6

b=6 Example of post increment operator

#include<stdio.h> #include<conio.h>

void main() {

int a=5,b;

Page 39: best notes in c language for b

Basics of 'C' language Page No: 39

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

b=a++; printf(“\na=%d”,a);

printf(“\nb=%d”,b);

getch();

}

output:- a=6

b=5

Example of pre decrement operator

#include<stdio.h>

#include<conio.h> void main()

{ int a=5,b;

b=--a; printf(“\na=%d”,a);

printf(“\nb=%d”,b); getch();

}

output:- a=4

b=4 Example of post decrement operator

#include<stdio.h> #include<conio.h>

void main() {

int a=5,b; b=a--;

printf(“\na=%d”,a);

printf(“\nb=%d”,b); getch();

}

output:- a=4

b=5 7) sizeof operator: - The sizeof operator returns the size , in

bytes , of the given operand. A sizeof operator is a unary operator that returns the number of bytes required to store a variable or a data

type. Syntax is:-

sizeof(datatype or variable) Example:-

sizeof (int)

Page 40: best notes in c language for b

Basics of 'C' language Page No: 40

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write a program to find the size of int , float and char.

#include<stdio.h> #include<conio.h>

void main() {

int a; float b;

char c; printf("\n size of int =%d bytes",sizeof(a));

printf("\n size of float=%d bytes",sizeof(b)); printf("\n size of char =%d byte",sizeof(c));

getch();

}

Output

size of int =2 bytes size of float=4 bytes

size of char=1 byte

8) Comma operator: - The comma operator (,) is used to declare more

than one variable in single line. It is also known as separater as it separates one variable name from other.

Example

int a,b,c; 9) Ternary operator: - Ternary operator is also known as conditional

operator or immediate if. These are ? and : ternary operator. An operator that takes three statements to work. The syntax of this operator is

<Condition>? <Expression1>: <expression2> The <condition> is evaluated first. If the result is true then expression 1 is

executed, otherwise expression 2 is executed. If <condition> is false ,expression3 is evaluated & its value becomes the

result of expression. e.g. if a=15,b=5

x=(a>b)?a:b The above example means that if a is greater than b then a will be assigned

to x, otherwise b will be assigned to x. It can be achieved using if-else statements as follows:

if(a>b)

x=a; else

x=b; Note:The detail of if-else is discussed in next chapter.

Page 41: best notes in c language for b

Basics of 'C' language Page No: 41

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Operators precedence and Associativity

Operators

Associativity ( [ - . Left to right

! - ++ -{- + * & (type-cast) sizeof Right to left * / % Left to right

+ - Left to right << >> Left to right

< <= > >= Left to right == != Left to right

& Left to right ^ Left to right

| Left to right && Left to right

|| Left to right

?: Left to right = += -= *= /= %= Right to left

&= ^= |= <<= >>= Left to right

Important Questions[Short] 1. Define relational operators.

2. Explain Advance assignment operator. 3. Define Ternary operators.

4. Define sizeof operator. 5. Write difference between logical AND and OR operators.

6. Write difference between ++I and I++. Important Questions[Long]

1. Explain Bitwise operators. 2. Explain increment and decrement operators with example.

3. Write precedence of the operators.

CCCCJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.J SOFTECH Walia Enclave Opp Punjabi Univ Patiala.J SOFTECH Walia Enclave Opp Punjabi Univ Patiala.J SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 42: best notes in c language for b

Basics of 'C' language Page No: 42

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Expression

Statement Or Statements

true

false

Chapter 5 CONDITION CONTROL STATEMENTS

Control Statements Normally program is executed in the sequential order, and when we want to

change the normal execution of the program then we need to use control

statements or we can say control statements are used to change the normal execution of the program.

Control statements are mainly divided into three types 1. Condition control statements

2. looping or iterative statements 3. branching statements

1. Condition control statements These are used when we want to execute the statement or block of

statements according to some condition. Conditional execution can be controlled by :-

a. if b. if else

c. if else if d. Nested if

e. switch case

f. Conditional operator or ternary operator If Statement

It is the basic condition control statement. When we have single condition then we mostly use it. The if statement allows a programmer

to test the value of a conditional expression and to select or reject the execution of the statement or block of statements depending on this

value.

Syntax of if: if (condition)

{ statement1;

statement2;

} Statement1 and statement2 will only execute if the

condition is true

RULES TO USE IF STATEMENT

o The IF condition ends with a pair of parenthesis

o There is no semicolon after the parenthesis

Page 43: best notes in c language for b

Basics of 'C' language Page No: 43

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

1. Write an algorithm and program to Input age and print “you

are child” if age <10.

Algorithm Program

Step1 Start void main()

{

Step2 declare age int age;

Step3 Print “Enter age” printf(“Enter age”);

Step4 Input age scanf(“%d”,&age);

Step5 if age< 10

then Print “You are child”

End

if(age<10)

{ printf(“You are child”);

}

Step7 Stop }

2. Write an algorithm and program to Input a number and print its absolute value.[eg absolute value of 10 and -10 is 10,

it is non negative value]

Algorithm Program

Step1 Start void main()

{

Step2 declare a int a;

Step3 Print “Enter value of a” printf(“Enter value of a”);

Step4 Input a scanf(“%d”,&a); Step5 if a< 0

then a=-a. End

if(a<0)

{ a=-a; }

Step6 print a printf(“%d”,a);

Step7 Stop }

Output:- 1. Enter value of a 22

22 2. Enter value of a -22

22 * when we enter 22 if block is not executed and when we enter -22 if block

convert this -22 to 22. In above program if we enter negative number then if block will executed

and convert negative number to positive number.

Page 44: best notes in c language for b

Basics of 'C' language Page No: 44

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Expression

Statement1 Statement2

true false

IF ELSE

If is a single selection structure and if else is a double-selection structure because it selects from two different actions. If else is one of the most

commonly used control statement.

Syntax

if (Expression) statement1

else

statement2 If Expression is true then it executes statement1 otherwise it executes

statement2 Write an algorithm and program to Input two number and print

greatest from them.

Algorithm Program

Step1 Start void main() {

Step2 declare a,b int a,b;

Step3 Print “Enter value of a” printf(“Enter value of a”);

Step4 Input a scanf(“%d”,&a);

Step5 Print “Enter value of b” printf(“Enter value of b”);

Step6 Input b scanf(“%d”,&b);

Step5 if a> b begin

Print “a is big” End

Else Begin

Print “b is big” End

if(a>b) {

printf(“a is big”); }

else {

printf(“b is big”); }

Step7 Stop }

Output:-

Enter value of a 20 Enter value of b 10

a is big

Page 45: best notes in c language for b

Basics of 'C' language Page No: 45

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

In above program “a is big” will be printed if a is greater than b else

result will be ”b is big”. What happen if a=b?

In above program if we input same values in both the variables then output will be “b is big”. To overcome this we need to create three blocks.

#include<stdio.h> #include<conio.h>

void main( ) {

int a,b; clrscr();

printf("enter the value of a"); scanf("%d",&a);

printf("enter the value of b"); scanf("%d",&b);

if(a>b) {

printf("a is big");

} if(b>a)

{ printf(" b is big");

} if(a==b)

{ printf(" a is equal to b ");

} getch();

}

If Else If ladder

If we have more than two conditions then we use if else if statement . In this we can create multiple blocks of statements and statements will execute

according to the condition. Syntax

if (condition) {

statements;

} else if(condition)

{ statement;

} else

{ statements;

}

CJ SOFTECH Walia Enclave Opp CJ SOFTECH Walia Enclave Opp CJ SOFTECH Walia Enclave Opp CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.Punjabi Univ Patiala.Punjabi Univ Patiala.Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 2 2 2

PatialaPatialaPatialaPatiala

Page 46: best notes in c language for b

Basics of 'C' language Page No: 46

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Example of if-else-if statement.

#include<stdio.h> #include<conio.h>

void main( ) {

int a,b; clrscr();

printf("enter the value of a"); scanf("%d",&a);

printf("enter the value of b"); scanf("%d",&b);

if(a>b) {

printf("a is big"); }

else if(b>a)

{ printf(" b is big");

} else

{ printf(" a is equal to b ");

} getch();

}

In this example if a is greater than b then first block is executed and if b>a

then second block will execute else if none of the above conditions are true then else part will execute. If –else-if is faster than multiple if block because

in this if first block is executed then all the other blocks are ignored by the compiler.

Nested if

We can write if statement within the scope of another if or else block, it is known as nested if.

Syntax of nested if:

if (condition) {

if (condition) {

do this; }

else {

do this;

Page 47: best notes in c language for b

Basics of 'C' language Page No: 47

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

and this;

} }

else {

do this; }

In this syntax if condition 1 is true then compiler check the condition 2

and if condition 2 is also true then it will execute the statements written in inner if block.

Example of nested if.

#include<stdio.h>

#include<conio.h> void main( )

{ int a,b,c;

clrscr();

printf("enter the value of a"); scanf("%d",&a);

printf("enter the value of b"); scanf("%d",&b);

printf("enter the value of c"); scanf("%d",&c);

if(a>b) {

if(a>c) {

printf("a is big"); }

} if(b>a)

{

if(b>c) {

printf("b is big"); }

} if(c>a)

{ if(c>b)

{ printf("c is big");

} }

getch(); }

CJ SOFTECH Walia ECJ SOFTECH Walia ECJ SOFTECH Walia ECJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.nclave Opp Punjabi Univ Patiala.nclave Opp Punjabi Univ Patiala.nclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 48: best notes in c language for b

Basics of 'C' language Page No: 48

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include<stdio.h>

#include<conio.h> void main( )

{ int a,b,c;

clrscr(); printf("enter the value of a");

scanf("%d",&a); printf("enter the value of b");

scanf("%d",&b); printf("enter the value of c");

scanf("%d",&c); if(a>b)

{ if(a>c)

{

printf("a is big"); }

else {

printf(“c is big”); }

} else

{ if(b>c)

{ printf("b is big");

} else

{

printf(“c is big”); }

} }

Conditional operator or ternary operator The conditional operator is sometimes called ternary operator since they

take three arguments. These are the replacement for if else statements. expression 1 ? expression 2 : expression 3

If expression 1 is true then the value returned will be expression 2 otherwise the value returned will be expression 3.

Page 49: best notes in c language for b

Basics of 'C' language Page No: 49

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include<stdio.h> #include<conio.h>

void main( ) {

int a,b; clrscr();

printf("enter the value of a"); scanf("%d",&a);

printf("enter the value of b"); scanf("%d",&b);

(a>b)?printf("a is big"):printf(" b is big"); getch();

}

Nested ternary operators.

#include<stdio.h> #include<conio.h>

void main( ) { int a,b,c;

clrscr(); printf("enter the value of a");

scanf("%d",&a); printf("enter the value of b"); scanf("%d",&b);

printf("enter the value of c"); scanf("%d",&c);

(a>b&&a>c)?printf("a is big"):(b>c)? printf(" b is big"):printf(“c is big”); getch();

}

Switch statement

When we have multiple if statements then we can use switch case statement. The variable used in switch is known as switch variable. The

variable in the switch statement can be of int or char type only. The switch

statement can also contain the default statements that will be executed if none of the case is executed, default is optional.

syntax of Switch switch (expression)

{ case 1:

...block of statements1... break;

case 2: ...block of statements2...

break; -----------------

Page 50: best notes in c language for b

Basics of 'C' language Page No: 50

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

-----------------

----------------- default:

...block of statements for default.. break;

} Program using if else if statements.

#include<stdio.h> #include<conio.h>

void main( ) {

char c; clrscr();

printf("enter the value of c"); scanf("%c",&c);

if(c==’r’) {

printf("colour is red");

} else if(c==’b’)

{ printf("colour is blue");

} else if(c==’g’)

{ printf("colour is green");

} else

{ printf("colour is white");

} }

Program using switch case statement. #include<stdio.h>

#include<conio.h> void main( )

{ char c;

clrscr(); printf("enter the value of c");

scanf("%c",&c); switch(c)

{ case ‘r’:

printf("colour is red");

Page 51: best notes in c language for b

Basics of 'C' language Page No: 51

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

break; case ‘b’:

printf("colour is blue");

break; case ‘g’:

printf("colour is green"); break;

default: printf("colour is red");

}

}

Applications of switch: 1) It makes program easy to read and understand.

2) It is the replacement of multiple if statements. 3) Whole switch block is act like a single block.

Limitations of switch: 1) We can only use int and char type data.

2) We can not write relational operators in case. Like case > 10 is wrong.

Write an algorithm and program to input two numbers if choice a

add it if choice s subtract it if choice d divide it otherwise give a

message wrong key pressed. Algorithm:- Step 1: START

Step 2: DECLARE ch,a,b,c Step 3: PRINT “Enter your choice” Step 4: INPUT ch

Step 5: PRINT “Enter two numbers” Step 6: INPUT a,b

Step 7: if(ch==’a’) then GOTO STEP 8 else GOTO STEP 9 Step 8: c=a+b PRINT c GOTO STEP 14 Step 9: If(ch==’s’) then GOTO STEP 10 ELSE GOTO STEP 11

Step 10: c=a-b PRINT c GOTO STEP 14 Step 11: if(ch==’d’) then GOTO STEP 12 else GOTO STEP 13

Step 12: c=a/b PRINT c GOTO STEP 14 Step 13: PRINT “wrong key pressed” Step 14: STOP

Program

#include<stdio.h>

#include<conio.h> void main()

{ int a,b,c;

char ch; printf(“enter two numbers”);

scanf(“%d%d”,&a,&b);

printf(“enter any character”);

Page 52: best notes in c language for b

Basics of 'C' language Page No: 52

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

fflush(stdin); scanf(“%c”,&ch);

switch(ch)

{ case ‘a’:

c=a+b; printf(“\naddition=%d”,c);

break; case ‘s’:

c=a-b; printf(“\nsubtraction=%d”,c);

break; case ‘d’:

c=a/b; printf(“\ndivision=%d”,c);

break; default:

printf(“\nwrong key pressed”);

} getch();

}

* fflush(stdin); is used to clear the buffer. It is always better to use this function before entering character.

Important Questions [Short] 1. What are control statements?

2. Write syntax of if-else-if 3. Write difference between if and if-else.

4. Define ternary operators. 5. What is the use of default statement in switch?

Important Question [Long] 1. Explain switch case statement with example.

2. Explain working of nested if statements. 3. Write syntax of various control statements used in ‘C’.

** Perform Programs from 12 to 26 from program list

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 53: best notes in c language for b

Basics of 'C' language Page No: 53

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 6 LOOPING AND BRANCHING STATEMENTS

Loops are used to execute statement or block of statements more than once. In other words, Loop is defined as continuity. In simple language, it means

to do a particular task again and again till a particular condition is true or satisfied.

For example A person is given a task to go upstairs or downstairs for five no. of times

continuously. These processes of going up and down again and again are known as loop. In a simple way we can say that a particular work or job is

done repeatedly. Use of loops in programming is to calculate the result or percentage of

100,000 students of Punjab school education board. In this case, we have to calculate the percentage of each student individually. To do this, we have to

apply the same formula again and again for each student. This process is

very time consuming, so to save memory space as well as time, loop is used in the database. We can apply formula with the help of loop in one single

line according given condition. Thus a loop is a part of program through which the control moves several

times during the execution of the program. The part which is executed again and again is known as body of the loop. During the execution of loop,

whenever control falls to end of the body of the loop, it again jumps to the starting point of body of the loop. This continues till a condition is satisfied

and control comes out of the loop if the condition is not satisfied.

In 'C' we have three types of loops. These are known as: 1. While

2. Do while 3. For

In mostly every loop we have to identify 3 main parts of the loop.

a) initialization: Starting point of the loop b) Condition:- Ending point of the loop

c) Increment/Decrement:- How will we reach from starting to end point of the loop.

1. While :- It executes the block of statements till the value of the conditional expression is true. In while if condition is true, then the body of

the loop is executed. After execution of the body [contain statements and increment/decrement part], the test condition is again tested and if it is

true, the body is executed again. This process is repeated till the test is true.

Syntax: - While (expression)

{ Statement a;

Statement b;

Page 54: best notes in c language for b

Basics of 'C' language Page No: 54

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Increment/decrement;

} There will be no semicolon at the end of the line containing the keyword

while in while loop.

1) Write an algorithm and draw flowchart to print “HELLO” 10 times.

Algorithm Step 1: START

Step 2: DECLARE A Step 3: A=1

Step 4: IF A<=10 GOTO STEP 5 ELSE GOTO STEP 7

Step 5: PRINT “HELLO” Step 6: A=A+1 GOTO STEP 4

Step 7: STOP

Or Algorithm

Step 1: START Step 2: DECLARE A

Step 3: A=1 Step 4: Repeat while A<=10

PRINT “HELLO” A=A+1

End loop Step 7: STOP

Write A Program To Print 1 To 10 Series.

#include<stdio.h>

#include<conio.h> void main()

{

int a=1; clrscr();

while(a<=10) {

printf(“\n%d”,a); a++;

} getch();

}

a=1 is the starting point of the loop and condition written in while is the

end point a++ is the increment. This represents that loop starts from 1 ends at 10 and increment 1. So output will be 1 2 3 4 5 6 7 8 9 10,

N0

yes

Declare A

IF A<=10

PRINT”HELLO”

STOP

START

A=1

A=A+1

Page 55: best notes in c language for b

Basics of 'C' language Page No: 55

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

similarly in following program loop starts from 2 ends at 100 with 2

increment.

Write A Program To Print Series 2,4,8,10-----100

#include<stdio.h>

#include<conio.h> void main()

{ int a=2;

clrscr(); while(a<=100)

{ printf(“%d”,a);

a=a*2; }

getch();

}

Loops are also very helpful if we want to multiply , add or count number

from the continue list like 2 4 6 8 10 12 14 16 18 20 to add numbers we use s=s+a where s is used for sum and a is the variable of the loop at start

value of s should be initilized with 0 as in the following example value of s

in the beging of the loop is 0 after one iteration of the loop value of s=s+1 means s=0+1 this make s=1 and after second itration s=1+2 so s is 3

similar after third itration s=3+3 (6) after fourth s=6+4 (10) this is executed 10 times. In the end value of s=1+2+3+4+5+6+7+8+9+10=55.

Similarly if we want to count numbers we use c=c+1 and for multiply m=m*a.

Write a program to find sum of 1 to 10 numbers

#include<stdio.h> #include<conio.h>

void main() {

int a=1,s=0; clrscr();

while(a<=10) {

s=s+a;

a++; }

printf(“%d”,s); getch();

}

Page 56: best notes in c language for b

Basics of 'C' language Page No: 56

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

2. DO-WHILE : - It checks the condition after executing the statements so it executes the statements at least once even if the expression is false. Condition is checked at the end of the do while loop. Mostly this loop is used for software testing (Means whether the condition is true or false, loop will be execute once)

Syntax do

{ Statement a;

Statement b;

Increment/decrement; }

while (expression); There will be no semicolon at the end of the line containing the keyword

do, But we need to place semicolon at the end of keyword while.

1) Write an algorithm to print “hello” n times.

Algorithm Step 1: START

Step 2: DECLARE i,num Step 3: PRINT “Enter the ending point number”

Step 4: INPUT num Step 5: i=1

Step 6: PRINT “hello” Step 7: i=i+1

Step 8: if(i<=num) then GOTO STEP 6 else GOTO STEP 9

Step 9: STOP

Write A Program To Print hello N times

#include<stdio.h>

#include<conio.h> void main()

{ int i =1 ,num;

clrscr(); printf(“enter number”);

scanf(“%d”,&num); do

{ printf(“hello”);

i++; }

while(i<=num);

getch();

}

CJ SOFTECH Walia CJ SOFTECH Walia CJ SOFTECH Walia CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.Enclave Opp Punjabi Univ Patiala.Enclave Opp Punjabi Univ Patiala.Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 57: best notes in c language for b

Basics of 'C' language Page No: 57

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Difference between do-while loop and while loop In both the cases the condition is checked. In case of while, condition is

checked before the execution of the statements but in case of do-while, statements are executed at least once whether the condition is true or false

i.e. condition is checked at the end of the do-while block. a=11;

while(a<=10) { printf(“%d”,a);

a++; }

a=11;

do { printf(“%d”,a);

a++; } while(a<=10);

Output: [BLANK SCREEN] Output: 11

3. FOR: - In for loop the initialization, condition and increment or

decrement can be done in one line. It executes the statements till the condition is true. Mostly this loop is used in complex programming.

Syntax for (initialization; condition; increment/decrement)

{ Statement;

Statement; }

1) First initialize the variable. 2) After initialization, condition is checked. If condition is true then

statement is executed. 3) After that increment or decrement the variable according to

condition. Write a program to find sum of 1 to 10 numbers

#include<stdio.h> #include<conio.h>

void main() {

int a,s=0;

clrscr(); for(a=1;a<=10;a=a+1)

{ s=s+a;

} printf(“%d”,s);

getch();

}

Page 58: best notes in c language for b

Basics of 'C' language Page No: 58

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write a program to print factors of a number

#include<stdio.h> #include<conio.h>

void main() {

int n,i,c=0; clrscr();

printf("enter a no"); scanf("%d",&n);

for(i=1;i<=n;i++) {

if(n%i==0) {

printf(" %d",i); }

} getch();

}

Write a program to count factors of a number To count factors we use formula c=c+1 the value of c is incremented

every time we find a value of i that divide the number n. In the end of

the loop the value of C is equal to the total factors of n.

#include<stdio.h>

#include<conio.h> void main()

{ int n,i,c=0;

clrscr(); printf("enter a no");

scanf("%d",&n); for(i=1;i<=n;i++)

{ if(n%i==0)

{ c=c+1;

} }

printf("count= %d",c);

getch();

}

Page 59: best notes in c language for b

Basics of 'C' language Page No: 59

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write a program to print number is prime or not.

*Prime numbers are only divided by 1 or itself like 7, 11, 13, 17 etc. This program is same as last one only we add a condition in the end that

if no of factors are 2 then no is prime else not.

#include<stdio.h>

#include<conio.h> void main()

{ int n,i,c=0;

clrscr(); printf("enter a no");

scanf("%d",&n); for(i=1;i<=n;i++)

{ if(n%i==0)

{ c=c+1;

}

} if(c==2)

printf("number is prime"); else

printf("number is not prime"); getch();

}

Write a program to print sum of digits of a number.

#include<stdio.h>

#include<conio.h> void main()

{ int n,i,s=0;

clrscr(); printf("enter a no");

scanf("%d",&n); //let n=1234 while(n>0)

{ i=n%10; //4 3 2 1

s=s+i; //0+4=4 4+3=7 7+2=9 9+1=10

n=n/10; //123 12 1 0 }

printf("sum of digits =%d",s); //so s=10 getch();

}

Write a program to print reverse of a number.

Page 60: best notes in c language for b

Basics of 'C' language Page No: 60

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include<stdio.h> #include<conio.h>

void main()

{ int n,i,s=0;

clrscr(); printf("enter a no");

scanf("%d",&n); // let n=1234 while(n>0)

{ i=n%10; //i=4 3 2 1

s=s*10+i;//s=0*10+4=44*10+3=4343*10+2=432432*10+1=432

n=n/10;

} printf("reverse of a number =%d",s);

getch();

}

Write a program to print no is Armstrong or not.

*153 is an Armstrong number because 1*1*1 = 1

5*5*5 = 125

3*3*3 = 27 Total 157

#include<stdio.h> #include<conio.h>

void main() {

int n,i,s=0,m; clrscr();

printf("enter a no"); scanf("%d",&n);

m=n; while(n>0)

{ i=n%10;

s=s+i*i*i; n=n/10;

}

if(s==m) printf("number is Armstrong”);

else printf("number is not Armstrong”);

getch();

}

Page 61: best notes in c language for b

Basics of 'C' language Page No: 61

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

1. NESTED LOOP: -Nested loop means nesting or loops means within

loop. In nested loop the first loop is called outer loop & second loop is called inner loop. In this the condition of outer loopis true then the

condition of inner loop is checked. If it is true then inner loop will execute. The inner loop would act as a part of the body for the outer

loop. Therefore, execution of inner loop will depend on the execution of the outer loop.

Syntax for (initialization; condition; increment/decrement) //outer

Loop {

for (initialization; condition; increment/decrement) // Inner

loop {

Statement;

} }

Why we use nested loops:- If we want to find sum of 5 subjects of a student we use single loop and if we want to find sum of 5 students in 5

subjects each then we need to execute the loop 5 times so that we can find sum of 5 students for this we need nested loops. E.g

For(stu=1;stu<=5;stu=stu+1) {

for(sub=1;sub=1;sub=sub+1) {

statements; }

} If the condition of outer loop is true then control will goto the inner loop

and if the condition of inner loop is true then executes the statement. If the

condition of outer loop is false the control doesn’t go into in the inner loop. Write a program to print :-

12345 12345

12345 12345

12345

#include<stdio.h>

#include<conio.h> void main()

{ int i,j;

clrscr();

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

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 62: best notes in c language for b

Basics of 'C' language Page No: 62

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

{ for(j=1;j<=5;j++)

{

printf(“%d”,j); }

printf(“\n”); }

getch(); }

In above program we have used nested loop. Ist loop is outer loop and 2nd

loop is inner loop. If the outer loop is true then control goes to the inner loop otherwise exit the control in outer loop. In simple meaning outer loop

act as no of rows and inner as no of column.

Write a program to print 1 12

123 1234

12345

#include<stdio.h>

#include<conio.h> void main()

{ int i,j;

clrscr();

for(i=1;i<=5;i++) {

for(j=1;j<=i;j++) {

printf(“%d”,j); }

printf(“\n”); }

getch();

}

Write a program to print 1 22

333 4444

55555

#include<stdio.h>

#include<conio.h> void main()

{

int i,j;

clrscr();

Page 63: best notes in c language for b

Basics of 'C' language Page No: 63

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

for(i=1;i<=5;i++) {

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

{ printf(“%d”,i);

} printf(“\n”);

} getch();

}

Write a program to print 9 99

999 9999

#include<stdio.h> #include<conio.h>

void main() {

int i,j; clrscr();

for(i=1;i<=5;i++) {

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

{ printf(“9”);

} printf(“\n”);

} getch();

}

Write a program to print 1 to 1000 palindrome numbers.

#include<stdio.h> #include<conio.h>

void main() {

int n,i,s=0,m; clrscr();

for(m=1;m<=1000;m++) {

n=m; s=0;

while(n>0)

{

i=n%10;

Page 64: best notes in c language for b

Basics of 'C' language Page No: 64

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

s=s*10+i; n=n/10;

}

if(s==m) printf(" %d",s);

} getch();

}

Branching Statements

There are another kind of control statements that can change the execution of loop or execution of the program. Branching statements are further

divided into three types.

a. Break

b. Continue c. goto

Break: - Break statement is used to exit from the loop or switch statement.

Whenever break statement is encountered the rest of the statements inside

the loop are ignored and the control go to the next statements after the loop. It can also be used with a while , a do while , a for or a switch

statement.

EXAMPLE BREAK STAEMENT

#include<stdio.h>

#include<conio.h> void main()

{ int i;

clrscr(); for(i=1;i<=10;i++)

{ if(i==5)

{ break;

} printf("\n% d",i);

} getch();

}

output

Page 65: best notes in c language for b

Basics of 'C' language Page No: 65

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

1

2 3

4

*exit function:- It terminates the whole program instead of loop..

Continue: -The continue statement is used to skip the remaining statements of the body of the loop where it defined, it does not terminate

the loop but the control is transferred to the start of the next loop iteration. Continue statement is used to only break the current iteration. After

continue statement the control returns to the top of the loop test conditions.

Example continue statement

#include<stdio.h> #include<conio.h>

void main() {

int i; clrcsr();

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

{ if(i==5)

{ continue;

} printf(“ %d ”,i);

} getch();

}

Output: 1 2 3 4 6 7 8 9 10 Goto: - The goto statement is control statement that causes the control to

jump to a different location in the program with or without checking any condition . It is always used with the label. It increase the readable

complexity of the program so programmers avoid to use this. The goto statement can only be used within the body of a function definition.

There are two types of goto:-

1) Unconditional jump 2) Conditional jump

Page 66: best notes in c language for b

Basics of 'C' language Page No: 66

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

1. Unconditional Jump: In this control is transferred from one

statement to another without any condition. EXAMPLE Unconditional GOTO STATEMENT

#include<stdio.h> #include<conio.h>

void main() {

clrscr(); printf(“\none”);

printf(“\nTwo”); printf(“\nThree”);

goto abc; printf(“\Four”);

printf(“\Five”); printf(“\nSix”);

abc: printf(“\nSevan”);

printf(“\nEight”);

getch();

}

Output

One

Two Three

Seven Eight

2. Conditional Jump: In this control is transferred from one

statement to another according to the condition. EXAMPLE conditional GOTO STATEMENT

#include<stdio.h> #include<conio.h>

void main() {

int a; Abc:

printf(“Enter no greater than 10”); scanf(“%d”,&a);

if(a<=10) goto Abc;

printf(“You enter number greater than 10”); getch();

}

in this program control goes back to Abc label until user not enter number

greater than 10.

Page 67: best notes in c language for b

Basics of 'C' language Page No: 67

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Important Questions[Short] 1. What do you mean by loop?

2. What are the limitations of goto statement? 3. Write advantages of for loop over while and do-while.

Important Questions[Long] 1. Explain various types of loops in 'C' language .

2. Write difference between break and continue. 3. Write difference between while and do-while.

4. What are various jump statements in 'C' language . ** Perform Programs from 27 to 51 from program list

CJ SOFTECH Walia Enclave Opp Punjabi Univ PatialCJ SOFTECH Walia Enclave Opp Punjabi Univ PatialCJ SOFTECH Walia Enclave Opp Punjabi Univ PatialCJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.a.a.a.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 68: best notes in c language for b

Basics of 'C' language Page No: 68

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 7 ARRAYS AND STRINGS

Arrays are group of similar data types. It’s used to store a large amount of data. The array elements are stored in contiguous memory locations. In

other words, if an array is declared to be of an int type, it can’t contain elements that are not of int type.

How to declare an Array: DataType variablename[size]

Example:- int ary[5];

10 20 30 40 50

ary[0] ary[1] ary[2] ary[3] ary[4] In the above program ary is variable name which hold the 5 elements which

have a same name, same data type but with different memory locations. As the memory is allocated sequentially so that data can be easily accessed by

increment or decrement by single variable. Arrays always start with index value zero.

Advantages of arrays 1. Array is the simplest data structure.

2. It is easy to create. 3. We can use one name for similar identifier.

4. Arrays use reference type so we need not to use return statement.

Limitations 1. Array may require large amount of contiguous memory, which is not

available sometimes. 2.Bound checking is not done by 'C' compiler. Means in ary[5] the index

value should be between 0 to 4 but if we write ary[7],ary[34] etc compiler does not show any error and display garbage value.

3. Overflow condition may occur in array if we want to store more values then its size.

ARRAY TYPES

Array is two types 1) One dimensional array

2) Multidimensional array 1) One dimension array:- A list of items have only one subscript and

such a list is called one dimensional array.

Declaration of an array. int a[5];

In the above example we defined an array a [5]. Here a is a variable name. Data type of a is integer and 5 is the size of an array. Size is always

written in subscript []. This means that it can store only five elements. Index of a is start from 0 to 4.

Initialization of an array:- we can also assign values to an array when we declare it.

int a[]={1,2,3,4,5};

Page 69: best notes in c language for b

Basics of 'C' language Page No: 69

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

compiler automatically sets the size of the array like in this case size of a is

5 and it requires 10bytes of memory[2 for each int] int a[10]={1,2,3,4,5,6,7,8,9,10};

In this we assign values to the ten elements of a. We can access array elements with its index, for example, if we want to print 5th element

from the list we use a[4]. Write a program to print five elements of an array.

#include<stdio.h> #include<conio.h>

void main() {

int a[]={1,2,3,4,5}; clrscr();

printf(“%d”,a[0]); printf(“%d”,a[1]);

printf(“%d”,a[2]); printf(“%d”,a[3]);

printf(“%d”,a[4]);

getch();

}

In this program 1 is store at location 0,2 at location 1 similarly others.

When we print a[0] it will display 1.

Write a program to input and print five elements using array. **it is always helpful to use loop in array

#include<stdio.h> #include<conio.h>

void main() {

int a[5],i; clrscr();

for(i=0;i<=4;i++) /*it will execute scanf statement 5 times and value in array*/

{ printf(“enter array element=”);

scanf(“%d”,&a[i]); }

for(i=0;i<=4;i++) {

printf(“ %d”,a[i]);

} getch();

}

2) Multidimensional Array: - Array in 'C' can have more than one dimension. An array with two dimensions or more is known as

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 70: best notes in c language for b

Basics of 'C' language Page No: 70

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

multidimensional array. Multidimensional array can be of 2-

Dimensional , 3-Dimensional, 4-Dimensional and so on. int a[2][2]; \\in this a is 2-D array

int a[2][3][2]; \\in this a is 3-D array int a[2][4][4][2]; \\in this a is 4-D array

2-D Array: - 2-Dimensional array is also known as matrix because in this elements are stored in the form of rows and columns. A[4][5] means A is an

array with 4 rows and 5 columns. We can store 20 elements in A[4][5] array and size of A is 40bytes.

A[0][0] A[0][1] A[0][2] A[0][3] A[0][4]

A[1][0] A[1][1] A[1][2] A[1][3] A[1][4]

A[2][0] A[2][1] A[2][2] A[2][3] A[2][4]

A[3][0] A[3][1] A[3][2] A[3][3] A[3][4]

Nested loops are used to input and print data from 2-D array. Outer loop is used to represent rows and inner is used to represent column.

Write a program to print 2*3array matrix.

#include<stdio.h>

#include<conio.h> void main()

{ int a[2][3],i,j;

clrscr(); printf(“enter array matrix”);

for(i=0;i<2;i++)

{ for(j=0;j<3;j++)

{ scanf(“%d”,&a[i][j]);

} }

for(i=0;i<2;i++) {

for(j=0;j<3;j++) {

printf(“ %d”,a[i][j]); }

printf(“\n”); }

getch();

}

Write a program to add two matrices.

#include<stdio.h>

#include<conio.h> void main()

{

Page 71: best notes in c language for b

Basics of 'C' language Page No: 71

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

int a[5][5] , b[5][5],c[5][5],i,j; clrscr();

printf(“enter 1st matrix”);

for(i=0;i<=4;i++) {

for(j=0;j<=4;j++) {

scanf(“%d”,&a[i][j]); }

} printf(“enter 2nd matrix”);

for(i=0;i<=4;i++) {

for(j=0;j<=4;j++) {

scanf(“%d”,&b[i][j]); }

}

for(i=0;i<=4;i++)

{ for(j=0;j<=4;j++)

{ c[i][j]=a[i][j]+b[i][j];

printf(“ %d”,c[i][j]); }

printf(“\n”); }

getch();

}

a b c Write a program to

multiply two matrices.

#include<stdio.h> #include<conio.h>

void main() {

int a[5][5] , b[5][5],c[5][5],i,j,k; clrscr();

printf(“enter 1st matrix”);

for(i=0;i<=4;i++)

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

2 3 4 5 6

2 3 4 5 6

2 3 4 5 6

2 3 4 5 6

2 3 4 5 6

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 72: best notes in c language for b

Basics of 'C' language Page No: 72

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

{ for(j=0;j<=4;j++)

{

scanf(“%d”,&a[i][j]); }

} printf(“enter 2nd matrix”);

for(i=0;i<=4;i++) {

for(j=0;j<=4;j++) {

scanf(“%d”,&b[i][j]); }

} for(i=0;i<=4;i++)

{ for(j=0;j<=4;j++)

{

c[i][j]=0; for(k=0;k<=4;k++)

{ c[i][j]=c[i][j]+a[i][k]*b[k][j];

} }

} for(i=0;i<=4;i++)

{ for(j=0;j<=4;j++)

{ printf(“%d”,c[i][j]);

} printf(“\n”);

}

getch(); }

Write a program to print transpose of matrix. Transpose means converting the rows into column;

#include<stdio.h> #include<conio.h>

void main()

{ int a[5][5],i,j;

clrscr(); printf(“enter array matrix”);

for(i=0;i<=4;i++) {

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

Page 73: best notes in c language for b

Basics of 'C' language Page No: 73

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

{ scanf(“%d”,&a[i][j]);

}

} for(i=0;i<=4;i++)

{ for(j=0;j<=4;j++)

{ printf(“ %d”,a[j][i]);

} printf(“\n”);

} getch();

}

A B

3-Dimensonal array:- eg int A[4][5][3]. In this

we can store total 4*5*3=60 elements and size

of A is 120 bytes. Write a program of 3-D Array.

#include<stdio.h> #include<conio.h>

void main() {

int a[3][5][4],i,j,k; clrscr();

printf(“enter array matrix”); for(i=0;i<=2;i++)

{ for(j=0;j<=4;j++)

{ for(k=0;k<=3;k++)

{ scanf(“%d”,&a[i][j][k]);

}

} }

for(i=0;i<=2;i++) {

for(j=0;j<=4;j++) {

for(k=0;k<=3;k++)

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

16 17 18 19 20 1 5 9 13 17

2 6 10 14 18

3 7 11 15 19

4 8 12 16 20

Page 74: best notes in c language for b

Basics of 'C' language Page No: 74

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

{ printf(“%d”,a[j][i][k]);

}

} }

getch();

}

String C language does not provide any data type in which we can represent

collection of character. So if we want to do this we use character array that is called string. As we can store more than one element in integer or float

array, similarly we can store more than one character in character array. Group of characters is also known as String.

A string is a one dimensional array of characters terminated by a NULL(‘\0’). For example,

char name[20]={‘P’,’R’,’A’,’T’,’H’,’A’,’M’}; or

char name[20]={“PRATHAM”}; The size of name is 20 bytes(1 byte for 1 char) and we use only first three

bytes to store “PRATHAM” after this we have 13 bytes left that contain garbage value. But when we print it, it display first three characters only

because compiler place NULL also represented as ‘\0’ at the end of the

string, so when compiler print the string it print up to NULL character. We can input and print string using %s format specifier in scanf and printf

functions. We can also use gets to input a string and puts to print a string. Write a program to input and print a string.

Output: [if we use scanf]

Enter name Charanjiv Singh Name=Charanjiv

Output:if we use gets] Enter name Charanjiv Singh

Name=Charanjiv Singh 2-D Character Array

we can use two-dimensional char array to create an array of strings.

#include<stdio.h>

#include<conio.h> void main()

{ char ch[20]; clrscr();

printf("Enter name "); scanf("%s",&ch); // or we can use gets(ch);

printf("Name=%s",ch); getch();

}

Page 75: best notes in c language for b

Basics of 'C' language Page No: 75

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

For example; char names[10][20];

it can be used to represent ten different strings For example,

char days[7][10]={“Monday”, “Tuesday”............”Sunday”}; can be used to store name of days.

Here 7 means we pass 7 strings and 10 means each string consist 10 charcaters.

#include<stdio.h> #include<conio.h>

void main() {

int i; char name[12][10]={"Jan", "feb", ",mar", "apr", "may", "jun",

"jul", "aug", "sep", "oct", "nov", "dec"}; int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};

clrscr(); for(i=0;i<12;i++)

printf(" %s has %d days:",name[i],days[i]);

getch();

}

String library functions are the functions, which are used regularly and

stored in library file and whenever these functions are needed , you need to include the required header file in your program like as,

#include<string.h> There are 7 inbuilt functions to perform different operations on strings.

1.. strlen: This function is used to count the characters in a string. It calculates the length of the string.

Syntax: strlen(array variable);

#include<stdio.h> #include<conio.h>

#include<string.h> void main()

{ char s1[20];

int i;

clrscr(); printf(“Enter string “);

scanf(“%s”,&s1); i=strlen(s1);

printf(“Length=%d”,i); getch();

}

Page 76: best notes in c language for b

Basics of 'C' language Page No: 76

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

2. strcpy: This function copies the contents of one string into another string.

Syntax strcpy(target,source);

#include<stdio.h> #include<conio.h>

#include<string.h> void main()

{ char s1[20],s2[20];

clrscr(); printf(“Enter string “);

scanf(“%s”,&s1); strcpy(s2,s1);

printf(“string =%s ”,s2); getch();

}

3. strcat: This function is used to concatenate the source string

at the end of the target string. Syntax

strcat(target,sourcetoadd);

#include<stdio.h> #include<conio.h>

#include<string.h> void main()

{ char s1[20],s2[20];

int i; clrscr();

printf(“Enter string “); scanf(“%s”,&s1);

printf(“Enter string “); scanf(“%s”,&s2);

strcat(s2,s1); printf(“ concatenated string =%s ”,s2);

getch();

}

4. strcmp: This function compares two strings to find out whether they are same or different. The two strings are compared character by

character until there is a mismatch or end of the string. This function

returns 0 if both the strings are identical. Syntax

Strcmp(string1,string2);

Page 77: best notes in c language for b

Basics of 'C' language Page No: 77

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include<stdio.h> #include<conio.h>

#include<string.h>

void main() {

char s1[20],s2[20]; int i;

clrscr(); printf(“Enter string “);

scanf(“%s”,&s1); printf(“Enter string “);

scanf(“%s”,&s2); i=strcmp(s2,s1);

if(i==0) printf(“ Both strings are same”);

else printf(“ Strings are not same”);

getch();

}

5. strrev() : - String reverse function is used to reverse the string. This function also contain a single argument

6. strupr() : - String upper case is used to convert the string in

to upper case or in capital letter. This function contains single argument.

7. strlwr() : - String lower case is used to convert the string into lower case or in small letter. This function contains single argument.

atoi()[define in stdlib header file: This function comes under <stdlib.h> header file. This function convert numeric string into integer

Syntax int atoi(string);

#include<stdio.h> #include<conio.h>

#include<stdlib.h> void main()

{ char s1[20];

int i; clrscr();

printf(“Enter string “);

scanf(“%s”,&s1); i=atoi(s1);

printf(“ i=%d”,i); getch();

}

String can also be accessed as array like we can create programs without

using string functions.

Page 78: best notes in c language for b

Basics of 'C' language Page No: 78

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

WAP to print length of string without using inbuilt function.

#include<stdio.h> #include<conio.h>

void main() {

char s1[20]; int i;

clrscr(); printf(“Enter string “);

scanf(“%s”,&s1); i=0;

while(s1[i]!=NULL) {

i++; }

printf(“ length of string =%d ”,i); getch();

}

*Similarly we can also create other string functions.

Important Questions[Short] 1. Define array.

2. How we can declare and initialize an array?

3. Define 2D array. 4. Define string.

5. Explain subscripted elements. Important Questions[Long]

1. Explain memory representation of array. 2. Explain String with example.

3. Explain inbuilt functions of string.

** Perform Programs from 52 to 72 from program list

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 79: best notes in c language for b

Basics of 'C' language Page No: 79

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 8 FUNCTIONS

Functions are the blocks of C programs which perform the specifc task. Functions are used to divide the long program into sub program. In general,

a function is a block of code that performs one or more actions. Functions are called by other functions. A program in the C language consists of

several functions. One such function we use is the main () function. Every function has a name. The name of the function ends with a pair of

parenthesis. This parenthesis may or may not contain any thing. Whatever is inside the parenthesis is known as the arguments of the function.

While defining function you must know these things: - 1. Function name.

2. Function return type (if there is no return then use void) 3. Function argument( if there is no argument here also use void).

Syntax to define a function:

<Return type> <function name>(<arguments>); Example: -

void show(); Why we use function: -

1. Functions are used to find the errors in the program. 2. Functions are used for reusability.

3. It decreases the cost of the software. 4. It increases the efficiency.

5. It makes the programming simple. 6. It reduces the complexity of the program.

Types of Functions There are two types of functions. First are known as built in functions and

second are the user defined functions.

1. Built in functions: - Built in functions are those functions,

which are provided to us by the programming language. But before using these functions we have to include some header files like,

<stdio.h> which are provided to us by the various input output related functions like printf() and scanf() function. Others are string

handling functions, mathematical functions which are stored in <string.h> and <math.h> header file respectively.

Math Functions Some examples of Math functions

Basic Math functions are sqrt() ,pow(), cos(), tan() and sin() etc. 1. sqrt ():- This function returns the square root of a number.

This function accepts a single argument. As shown in the syntax and example given below: -

The syntax for the sqrt() function is:- # include <math.h>

int sqrt(int h);

Page 80: best notes in c language for b

Basics of 'C' language Page No: 80

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Here, the sqrt() function returns the non-negative square root of h in

the integer data type. This function returns an error if h is negative. Example of sqrt() function:-

#include<stdio.h> #include<conio.h>

#include<math.h> void main()

{ int n;

clrscr(); printf(“enter any number”);

scanf(“%d”,&n); printf(“square root of n=%d”,sqrt(n));

getch();

}

2. pow():- This function returns the power of a number. This function accepts two arguments ,first is the number and the second is

its power. As shown in the syntax and example: - Syntax: -

#include <math.h> int pow(int x, int y);

Here, the value of the int variable x is raised to the power of y. The

pow() function returns the result in the int data type. Example of pow() function:-

#include<stdio.h> #include<conio..h>

#include<math.h> void main()

{ int n,p;

clrscr(); printf(“enter any number”);

scanf(“%d”.&n); printf(“enter their power”);

scanf(“%d”,&p); printf(“power of n=%d”,pow(n,p));

getch();

}

String handling functions

We also use string-handling functions, which are used for string

manipulations. These functions are like strcpy(), strcat(), strupr(),strlen(), strrev(), strlwr() and strcmp() etc.

Page 81: best notes in c language for b

Basics of 'C' language Page No: 81

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

2. User defined Functions: - These functions are defined by the

user are according to their requirement, known as User define functions. User defined functions have four types: -

a) Without Return Without Arguments b) Without Return with Arguments

c) With Return Without Argument d) With Return With Argument

For creating user defined functions we have to follow three basic steps. These are given below: -

a) Function Declaration / Function Prototyping b) Function Definition c) Function Calling

a) Function declaration: - Function declaration is also known as

function prototyping. Before using functions in your program it must be declared and defined. Function declaration or prototyping tells the

compiler that this function is used later in the programming. It also tells the compiler their name, return type, and arguments of the function. No

function can be called from any other function that hasn't first been declared. The declaration of a function is also called function prototype.A

prototype always ends with a semicolon (;).Function is declared same as we declare variables before using them.

b) Function Definition: - In function definition we can define the body of the function. It means we can write the number of statements inside

the opening and closing brace of the function, which are executed when the function is called by some other function. A function definition must

match (their name, return type and parameter list) with its declaration.

The definition tells the compiler how the function works. c) Function calling: - Function calling means to execute the function.

After declaration and definition of the function we can call the function for their execution. When you call a function, execution begins with the first

statement to last statement of the function. Functions can also call other functions and can even call themselves but mostly the main function call

the sub function.

Categories of user defined functions:

1. Without Return Without Argument: - This is the first type of user

define function and also known as no return no argument. No return means that function start with ‘void’ keyword. It tells the compiler that

the function cannot return any value. No arguments mean we cannot pass anything from the calling function to called function. It means we

can leave the parentheses blank. In C, the declaration of the show () function can be something like this:

Void show(); We can also write it as;

Page 82: best notes in c language for b

Basics of 'C' language Page No: 82

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

void show(void);

Note that the keyword ‘void’ is used in the declaration to indicate to the compiler that no argument is passed to the function. The compiler will

produce an error message if an argument is passed to show () function later in a program when this function is called.

Example1.WAP to add and subtract two numbers using function with no return no argument.

As show in the Example: -

#include<stdio.h>

#include<conio.h> void sum(); //Function declaration

void sub(); void main()

{ clrscr();

sum(); //Function calling sub();

getch();

} void sum() ///function Definition

{ int a,b,c;

printf(“enter first number”); scanf(“%d”,&a);

printf(“enter second number”); scanf(“%d”,&b);

c=a+b; printf(“sum=%d”,c);

} void sub() ///function Definition

{ int a,b,c;

printf(“enter first number”);

scanf(“%d”,&a); printf(“enter second number”);

scanf(“%d”,&b); c=a-b;

printf(“sub=%d”,c);

}

2. Without Return with argument:- This is the second type of user

define functions. This function starts with void keyword, which tells the compiler that function hasn’t any return type. It can’t return any thing to

its calling program. But with argument means we must pass information to the calling function. In this we should declare variables inside the

parentheses we cannot leave the parentheses blank. The argument of a

Page 83: best notes in c language for b

Basics of 'C' language Page No: 83

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

function is placed between the parentheses after the function name. If a

function has more than one argument then arguments must be separated by commas. We can declare a function with a fixed number of arguments,

but then you need to specify the data type of each argument. Arguments are of two types: -

1) Formal arguments 2) Actual arguments

1. Formal Arguments:-Formal arguments are those arguments which are declared at function declaration and function definition time. For

example: void sum(int a,int b);

Here a and b are the formal arguments which are passed into the sum function.

2. Actual arguments:-Actual arguments are those arguments which are passed to function at calling time. For example

sum(3,5);

Here 3 and 5 are our actual arguments which are passed into the sum() function.

As Shown in the example:- Example 2. WAP to find the square and cube of a number using

function with argument.

#include<stdio.h>

#include<conio.h> void sqr(int n); //function declaration

void cube(int n); void main()

{ int a;

clrscr(); printf(“enter any number”);

scanf(“%d”,&a); sqr(a); //calling the function

cube(a); //here a is actual parameter

getch(); }

void sqr(int n) {

int m; m=n*n;

printf(“\n the square=%d”,m); }

void cube(int n) {

int m;

m=n*n*n;

Page 84: best notes in c language for b

Basics of 'C' language Page No: 84

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

printf(“\n the cube=%d”,m);

}

Local variables: - Local variables are those variables, which are declared

inside a block or function. These variables are accessible only within the block and are passed as argument into the function or declared inside the

function. These are also known as function level variable because they are

accessible only within the function. Global variables: - Global variables are those variables, which are declared

outside the block or function. These are known as global variables. Which is accessible by each block of the program.

3. With return without Argument: - Return type functions are those functions, which return a value to the calling function. These

functions start with a specific data type in place of void keyword. These type of functions use return keyword to send the data back to the

calling function. As shown in the example:-

Example 3. WAP to find the factorial of a given number using function with return type.

#include<stdio.h>

#include<conio.h> int fact(); //Function declaration

void main()

{ int f;

clrscr(); f=fact(); //calling the function

printf(“\n the fatorial=%d”,f); getch();

} int fact() // Function definition

{ int a,b=1,n;

printf(“enter any number”); scanf(“%d”,&n);

for(a=1;a<=n;a++) {

b=b*a;

} return b;

}

4. With return with argument: - This function contains argument and also return the value to its calling function, as show in the given

example :.

Page 85: best notes in c language for b

Basics of 'C' language Page No: 85

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Example 4. WAP to reverse a number using function with return and with argument.

#include<stdio.h> #include<conio.h>

int reverse(int n); //Function declaration void main()

{ int a,b;

clrscr(); printf(“please enter any number”);

scanf(“%d”,&a); b=reverse(a); // Function calling

printf(“\n Reverse of a number=%d”,b); getch();

} int reverse(int n) ///Function definition

{

int r,s=0; while(n>0)

{ r=n%10;

s=s*10+r; n=n/10;

}

return s; }

Recursive Functions Recursive functions are those functions, which call itself again and again.

Normally function is called by the other function, but in recursive function it call itself repeatedly. This process known as recursion, as shown in the

example below: Example . WAP to find the factorial of a given number using

recursion.

#include<stdio.h>

#include<conio.h> int fact(int n);

void main() {

int n,f;

clrscr(); printf(“enter any number”);

scanf(“%d”,&n); f=fact(n);

printf(“factorial=%d”,f);

getch();

Page 86: best notes in c language for b

Basics of 'C' language Page No: 86

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

} int fact(int n)

{

if(a==1) {

return 1; }

else {

return n*fact(n-1); }

}

Example:WAP to print the fibonacci series.

#include<stdio.h> #include<conio.h>

int fibo(int a,int b); void main()

{ clrscr();

fibo(0,1); getch();

}

int fibo(int a,int b) {

printf(“%d”,a); if(a>100)

{ return 0;

} fibo(b,a+b);

}

Call by Value

In C language by default, the arguments are passed to the function by value. It means the actual arguments copy their value into the formal

arguments. In call by value, we can pass the value. If any change is done into the formal arguments, it doesn’t affect the actual arguments because

both the arguments use the different memory location.

As show in the example:-

Page 87: best notes in c language for b

Basics of 'C' language Page No: 87

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include<stdio.h> #include<conio.h>

void show(int a); //declaring the function (a is our formal

argument) void main()

{ int x;

clrscr(); printf(“enter any number”);

scanf(“%d”,&x); show(x); //calling the function ( x is our actual arguments)

printf(“\n now value of x=%d”,x); getch();

} void show(int a) // function definition ( a is our formal

argument)

{

a=a+1; printf(“\n the value of a=%d”,a);

}

Output

Enter any Number = 5 The value of a = 6

Now value of x = 5

Call by reference In call by reference we can pass the address of a variable in place of value.

It means we can pass the address of actual argument to the formal argument. If any change is done in to the formal arguments ,it also affects

the actual arguments, because the address of the actual arguments are passed to the formal arguments .In call by reference, we can pass pointer

variable as formal arguments. As show in the example:-

#include<stdio.h> #include<conio.h>

void show(int *a); //declaring the function (a is our formal argument)

void main() {

int x; clrscr();

printf(“enter any number”); scanf(“%d”,&x);

show(&x); ///calling the function ( x is our actual

arguments) printf(“\n now value of x=%d”,x);

getch();

Page 88: best notes in c language for b

Basics of 'C' language Page No: 88

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

} void show(int *a)// function definition ( a is our formal

argument)

{ *a=*a+1;

printf(“\n the value of a=%d”,*a);

}

Output Enter any Number = 5

The value of a = 6 Now value of x = 6

Passing array as argument into the function

Sometimes it's difficult to call a function that requires number of arguments.

One way around this is to store the variables into an array. So we can pass an array as argument into the function. As shown in the example:

#include<stdio.h> #include<conio.h>

void show(int a[]); //Parameter Array Type void main()

{ int x[5],i;

clrscr(); for(i=0;i<5;i++)

{

printf(“enter any number”); scanf(“%d”,&x[i]);

} show(x);

getch(); }

void show(int a[]) {

int i; for(i=0;i<5;i++)

{ printf(“\n%d”,a[i]);

}

}

Passing structure as argument into the function We can also pass structure as an argument into the function same as any

other variable. As shown in the example:

#include<stdio.h> #include<conio.h>

struct student

CJ SOFTECH Walia Enclave Opp Punjabi Univ PatialaCJ SOFTECH Walia Enclave Opp Punjabi Univ PatialaCJ SOFTECH Walia Enclave Opp Punjabi Univ PatialaCJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala....

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 89: best notes in c language for b

Basics of 'C' language Page No: 89

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

{ char name[20];

int roll,marks;

}; void show(struct student);

void main() {

struct student s; clrscr();

printf("enter student name"); scanf("%s",&s.name);

printf("enter student roll number"); scanf("%d",&s.roll);

printf("enter student marks"); scanf("%d",&s.marks);

show(s); getch();

}

void show(struct student s) {

printf("\nstudent name=%s",s.name); printf("\nstudent roll=%d",s.roll);

printf("\nstudent marks=%d",s.marks);

}

Nested Function Nested function means a function inside a function. But C does not allow

nested functions. But we can call one function into another function. It is also known as nested function. As shown in the example:

#include<stdio.h> #include<conio.h>

void sum(int a,int b); void input(int a,int b);

void input(int a,int b) {

sum(a,b); }

void sum(int a,int b) {

int c;

c=a+b; printf(“the sum=%d”,c);

} void main()

{ int x,y;

clrscr();

Page 90: best notes in c language for b

Basics of 'C' language Page No: 90

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

printf(“enter the value of x”); scanf(“%d”,&x);

printf(“enter the value of y”);

scanf(“%d”,&y); input(x,y);

getch();

}

Important Short Answer type questions 1. What are functions?

2. What are the advantages of functions? 3. What are arguments?

4. What do you mean by built in functions? 5. Write a note on user defined functions?

6. What is recursion? 7. What are the uses of functions?

8. What are the advantages and disadvantages of recursion?

Important Long Answer Type Questions 1. Write a note on user-defined functions. Why are they used?

2. What are the various types of functions supported by C? Give examples for each type of the C functions.

3. What is the relationship between actual arguments and formal

arguments? Explain with example? 4. Explain recursion in C with an example?

5. Write a function to find the factorial of a number using with return with argument.

6. Write a function to find the sum of n natural numbers using recursion.

7. Write the difference between Function prototyping and Function definition.

8. Write the two ways in which arguments can be passed to function.

9. Write a program to pass an array as an argument into the function.

10. Write a function to reverse a given integer using with return with argument?

11. Write a program to display the first n terms of Fibonacci series

using recursion.

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 91: best notes in c language for b

Basics of 'C' language Page No: 91

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 9 STORAGE CLASSES

Storage classes tell us about three things.

1. Storage classes tell us about the memory. It means a variable uses which type of memory. It uses RAM or any other memory (CPU

Memory).

2. Storage classes tells us about the scope of variable.The scope of

a variable is defined as the area of program in which it is accessible.

3. Storage classes tells us about the default value of the variable.

There are four types of storage classes. 1. Auto

2. Static 3. External

4. Register 1. Auto: - Auto means automatically. It is the default scope of variables

and they are declared with or without auto keyword, belong to auto

storage class. Auto variable are active in the block in which they are declared. Block means statements inside the braces ({}).

� The scope of auto variable is limited. It means they are local variable. They can access within the block where they are

declared. � The auto storage class variable uses primary memory for storing

data. It means RAM. � The default value of auto storage class is garbage.

For E.g :-

void main( ) {

auto int a,b; int c;

clrscr( ); printf(“Enter two numbers=”);

scanf(“%d%d”,&a,&b);

c = a + b; printf(“Sum=%d”,c);

getch( );

}

Note: - As shown above a,b and c all are belong to the auto storage class .

2) Static variable: - Static variable are those variable, which start with static keyword. Static variables retain their values through out the

execution of the program. Their initial value is zero. Static variable also use primary memory for storing data. Static variables are also active in

the block in which they are declared, means the scope of variable is

Page 92: best notes in c language for b

Basics of 'C' language Page No: 92

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

local. The declaration part of static variable execute only once even if

we call function more than once. Static variables are mostly used in functions. As shown in example: -

#include <stdio.h> #include<conio.h>

void show(); void main( )

{ clrscr( );

show( ); show( );

show( ); getch( );

} void show( )

{ static int a;

printf(“\n%d”,a);

a=a+1; }

Output :- 0

1

2

3) Extern variable: - Extern variable are those variables, which are, declared outside of the block/main. This variable can be accessible

by each block of the program. They are known as global variables. These variables are declared with extern keyword. Its initial value is

zero. They consider as local variable but work as global variables. They also use a primary memory (RAM) for storing a data.E.g :-

#include<stdio.h> #include<conio.h>

void show(); void main( )

{ extern int a;

clrscr( ); printf(“\n the value of a=%d”,a);

show( );

a = a + 10; printf(“\nNow the value of a=%d”,a);

getch( ); }

void show( ) {

extern int a;

Page 93: best notes in c language for b

Basics of 'C' language Page No: 93

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

a=a + 5; printf(“\nThe value of a=%d”,a);

}

Output :- 0

5

15

4) Register variable: -Register variable are those variable, which start with register keyword. We can use register keyword to increase

the speed of program. The Resister variable uses the CPU memory. Their default value is garbage. They are also block level variables, which

can access with in the block where they are declared. In case of non-availability of CPU memory, these variables use primary memory (RAM).

E.g :-

void main( )

{ register int a;

clrscr( ); printf(“\nThe value of a=%d”,a);

getch( );

}

Difference between auto variable and a static variable

auto variable static variable

Auto variables are start with or without auto keyword.

.Static variable start with static keyword.

They cannot retain their value throughout the execution of the

program.

They retains their value throughout the execution of the

program.

Their default value is garbage. It’s default value is zero.

These variable initialize everytime

when we call the function.

These variable initialize a single

time and retain their value,

Example: auto int a; Example: static int a;

Important Long Answer Type Questions 1. Explain the scope of variables in C?.

2. Give the difference between local and global variables in C?.

3. Explain the storage classes in C? Discuss their scope and use. 4. Discuss in brief, the difference between the following

declarations. a. static int i;

b. auto int i;

Page 94: best notes in c language for b

Basics of 'C' language Page No: 94

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 10 STRUCTURE

Structure is a group of similar and dissimilar data types. Structure is user

defined data type. To create a structure, we use struct keyword. Structure starts with a delimiters ({) and close with a delimiter(}). After closing the

delimiters, we place a semicolon. To access the elements of the structures, we create a structure variable/ structure field. With the help of structure

variable we use the dot operator and a specific element name, which we

want to access. As shown in the syntax below: Syntax

struct<structure name> {

<data type> <variable>; <data type><variable>;

}; Example

struct student {

char name[20]; int roll, marks ;

}; In this example student is structure name and in this structure we declare

two different data types , i.e. char & int.

Example of structure

#include<stdio.h> #include<conio.h>

struct student {

char name[20]; int roll,marks;

}; void main()

{ struct student s; //s is structure variable

clrscr();

printf(“enter student name”); scanf(“%s”,&s.name);

printf(“enter student roll no”); scanf(“%d”,&s.roll);

printf(“enter student marks”); scanf(“%d”,&s.marks);

printf(“\n your name=%s”,s.name); printf(“\n your roll=%d”,s.roll);

printf(“\n your marks=%d”,s.marks);

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 95: best notes in c language for b

Basics of 'C' language Page No: 95

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

getch();

}

Initialization of structure Initialization of structure means to give the initial values to the structure

elements in place of giving the values at run time. As shown in the example given below:

#include<stdio.h> #include<conio.h>

struct student

{ char name[20];

int roll,marks; };

void main() {

struct student s={“Anju”,1,89}; //initialization of structure variable s

clrscr(); printf(“\n your name=%s”,s.name);

printf(“\n your roll=%d”,s.roll); printf(“\n your marks=%d”,s.marks);

getch();

}

Memory representation in structure: - We can represent the memory

allocation of structure as given below. In it we can try to show the memory

presentation of structure.

struct student

{ char name[20];

int roll, marks;

};

name

0 1 2 3 4 ----------------------------------------- 16 17 18 19 roll

0 1 marks

0 1

Page 96: best notes in c language for b

Basics of 'C' language Page No: 96

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

As shown above it allocates 24 bytes memory for structure variables, 20

bytes memory for name, 2 bytes for roll number and 2 bytes for marks. Total memory is 24 bytes.

Structure within array:- We can also declare an array variable inside the structure. Structure and array both represents the group of elements. As

shown in the example

struct emp

{ char name[30];

char address[80]; //array

};

Dot Operator:- In structure we can use dot operator to access the elements

of the structure. We can use structure variable with dot operator and then given the element name, which we want to access. As shown in the example

struct student s; s.name=”MONCY”

s.marks=89;

Here s is the structure variable and name,marks are the elements of

structure which we are accessing using dot operator. Structure Array

We can also create an array of the structure for storing the details of more than one student.

struct student s[5]; Here s is the name of the structure array.The elements of this array are

s[0],s[1],s[2],s[3],s[4].

Write a program to enter the details of five students: their name, roll no and marks using structure.

# include<stdio.h> # include<conio.h>

struct student {

char name [20]; int roll,marks;

}; void main( )

{ int i;

struct student s [5]; clrscr( );

for(i=0;i<5;i++) {

printf(“\n enter your name”);

scanf(“%s”,& s[i].name);

printf(“please enter roll no”);

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 2 2 2 Patiala Patiala Patiala Patiala

Page 97: best notes in c language for b

Basics of 'C' language Page No: 97

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

scanf(“%d”,& s[i].roll); printf(“please enter your marks”);

scanf(“%d”,& s[i].marks);

} for(i=0;i<5;i++)

{ printf(“\n your name=%s”,s[i].name);

printf(“\n your roll no=%d”,s[i].roll); printf(“\nyour marks=%d”,s[i].marks);

} getch( );

}

Nested structure

Nested structure means a structure inside a structure.It is possible to have one structure as a member of another structure.In nested structure the

first structure is called the outer structure and second structure which inside the structure is known as inner structure.E.g :-

struct emp {

char name[20]; struct dep

{ int salary ;

}d;

}; void main( )

{ struct emp e;

clrscr( ); printf(“Enter Employ name=”);

sacnf(“%s”,& e.name); printf(“Enter your salary=”);

sacnf(“%d”,& e.d.salary); printf(“\n Your name=%s”,e.name);

printf(“\n Your salary=%d”.e.d.salary); getch();

}

As shown in the above example the emp is our outer structure and dep is inner structure.

Passing structure as argument into function: - We can also pass

structure as argument into the function. Same as variable and array. As shown in the example.In this program,we write a function show().It accepts

a structure as its argument.

Page 98: best notes in c language for b

Basics of 'C' language Page No: 98

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

struct student {

char name[30]; int roll, marks;

}; void show(struct student s);

void show(struct student s); {

print(“\n Student name=%s”,s.name); print(“\n Student roll=%d”,s.roll);

print(“\n Student marks=%d”,s.marks); }

void main() {

struct student s={“Harparteek”,1,89}; clrscr();

show(s);

getch();

}

In the above example first we declare the structure and then declare the

function with structure argument. Then we define th body of the function

and in last call the function with main function.

To check the size of the structure

To check the size of the structure, we can use sizeof() operator. It tells us how much memory is occupied by the structure elements.

As shown in the example below: -

#include<stdio.h>

#include<conio.h> struct emp

{ char name[15];

int age; float salary;

}; void main()

{ struct emp e;

clrscr();

printf(“the size of the structure=%d”,sizeof(e)); getch();

}

Page 99: best notes in c language for b

Basics of 'C' language Page No: 99

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Difference between Structure And Array

Structure Array

Structure is a group of similar

and dissimilar elements.

Array is a group of elements of similar

types.

Structure starts with struct keyword.

It does not start with any keyword but is uses subscript for creating an array.

We can use dot operator to

accesses the elements of the structure.

We can use index of the arrayto access

the element of the space array.

Structure has declaration and definition.

It has only declaration.

5. Example

struct student {

char name[20]; int roll;

};

5. Example

int a[10];

Important Short Answer type Questions

1. What are the advantages of structures? 2. What is structure?

3. Write a note on nested structure. 4. Explain self-referential structure.

5. Difference between structure and union.

Important Long Answer Type Questions 1. Explain structure in C. How can you differentiate it from an

array? 2. How structures are defined and initialized? Explain with example.

3. Explain by giving example how the members of structure are accessed in C.

4. What do you mean by structure within a structure? Give Example.

5. Explain how structure can be passed to a function as argument with example.

6. Write a program in C to define a structure student with data members like rollno, class and marks of 5 students. Calculate total

marks and show the students detail.

7. Write a program to create a structure student having data members as student name, rollno and pass it to a function as an

argument.

Page 100: best notes in c language for b

Basics of 'C' language Page No: 100

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 11 UNION

Union is a group of similar and dissimilar data types or elements. It is a user defined data type. Union starts with ‘union’ keyword and terminate with

semicolon same as structure. Union allocates a single memory to its elements. All the elements of the union share the single memory. To access

the elements of union we can create a union variable. It is same as structure.

The major difference between the union and structure is that in structure different members use different memory locations whereas in

union all members of union share the same memory location.

Syntax: - union < union name >

{ <data type> <variable name> ;

<data type> <variable name> ; };

E.g: - union student

{ char name [20];

int rollno, marks; };

Union memory representation:- As we know that union allocate largest

memory of its element and it allocate a single memory to all it elements.

As shown in the figure and Example

union student {

char name[20];

int roll, marks;

};

Memory representation name

0 1 2 3 4 5 6 ------------------------- 17 18 19 roll

marks As shown in the example and figure the union allocate 20 bytes memory for

name, roll and marks, which is the largest or higher memory in the union.

WAP to create union, which can store student detail like students name, rollno, and marks.

Page 101: best notes in c language for b

Basics of 'C' language Page No: 101

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

union student {

char name[20];

int rollno,marks ; };

void main( ) {

union student s; clrscr( );

printf(“Enter Employ name=”); sacnf(“%s”,& s.name);

printf(“\n Your name=%s”,s.name); printf(“Enter your Rollno.=”);

sacnf(“%d”,& s.rollno); printf(“\n Your Rollno.is=%d”,s.rollno);

printf(“Enter your Marks=”); sacnf(“%d”,& s.marks);

printf(“\n Your Marks is=%d”,s.marks);

getch();

}

Initialization of union

We cannot initialize the union same as structure because it uses the single memory location and all the elements use the same memory.

As shown in the example below: #include<stdio.h>

#include<conio.h> union student

{ char name;

int roll,marks; };

void main()

{ union student s;

clrscr(); s.name='h'; //initialization of union variable s

printf("\n your name=%c",s.name); s.roll=1;

printf("\n your roll=%d",s.roll); s.marks=99;

printf("\n your marks=%d",s.marks); getch();

}

Page 102: best notes in c language for b

Basics of 'C' language Page No: 102

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Union Array

We can also create the array of the union same as structure for storing the details of more than one student.

Write a program to enter the detail of five students: their name, rollno and marks using union.

# include<stdio.h> # include<conio.h>

union student {

char name [20]; int roll,marks;

}; void main( )

{ int i;

union student s[5]; clrscr( );

for(i=0;i<5;i++)

printf(“\n enter your name”); scanf(“%s”,& s[i].name);

printf(“\n your name=%s”,s[i].name); printf(“please enter roll no”);

scanf(“%d”,& s[i].roll); printf(“\n your roll no=%d”,s[i].roll);

printf(“please enter your marks”); scanf(“%d”,& s[i].marks);

printf(“\n your marks=%d”,s[i].marks); }

getch( );

}

To check the size of the union

To check the size of the union we can use sizeof() operator. It tells us how

much memory is occupied by the union elements.

As shown in the example below:-

#include<stdio.h> #include<conio.h>

union emp {

char name[15];

int age; float salary;

}; void main()

{

Page 103: best notes in c language for b

Basics of 'C' language Page No: 103

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

union emp e; clrscr();

printf(“the size of the union=%d”,sizeof(e));

getch();

}

Difference between structure and union

Structure Union

Structure start with ‘struct’ keyword

Union start with ‘union’ keyword

All the elements of the structure use different memory locations

for storing the data.

All the elements use the single memory location for storing the

data.

It allocates different memory to each element.

It allocates single memory. All the elements share the same memory.

It is commonly used in most of

the applications.

It is not commonly used.

Syntax struct <struct name>

{ <data type> <variable>;

};

Syntax union <union name>

{ <data type> <variable>;

};

Important Short Answer Type Questions

1. State limitations of union.

2. Write advantages of union. 3. How we can check the size of union?

Important Long Answer Type Questions 1. What is union? How can you differentiate it from a structure?

2. How union is defined and initialized? Explain with example. 3. Explain by giving example how the members of union are

accessed in C. 4. Write a program to define a union student with data members,

rollno as integer, stu_name as string and average marks as float.

Display the information of student and calculate the size of union. 5. What are the advantages of structure type over union type?

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 104: best notes in c language for b

Basics of 'C' language Page No: 104

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 12 ENUMERATION

The enumerated data type is used when we know in advance about a finite

list of values as a particular data type. The declaration of enumerated data type start with ‘enum’ keyword.. ‘enum’ keyword is followed by an enum

name, an open brace, each of the values separated by a comma, and finally a closing brace and a semicolon. The list of values is known as the

enumerated list of items. Syntax: -

enum <enum name>{value1,value2,value3……….value n}; example:

enum color { red, blue, green, white, black }; Note:- Here color is the name of the enum, and red, green, blue are the

symbolic constants. Each enum constant has an integer value. If we have

not given any value, then the initial value of the red is 0, blue is 1 and so on and incremented by one.

As shown in the example below:

#include<stdio.h>

#include<conio.h> enum col{red, green, blue, yellow, black, white };

void main() {

clrscr(); printf(“\n the value of red=%d”,red);

printf(“\n the value of green=%d”,green); printf(“\n the value of white=%d”,white);

getch(); }

output:- the value of red=0

the value of green=1

the value of white=5

Initialization of enum constant

We can also change the value of the each constant in the enum. Any constant can be initialized with a particular value, and those that are

not initialized ,will be incremented automatically.

As shown in the example below:

#include<stdio.h>

#include<conio.h>

enum col{red, green=5, blue, yellow, black, white };

Page 105: best notes in c language for b

Basics of 'C' language Page No: 105

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

void main() {

clrscr();

printf(“\n the value of red=%d”,red); printf(“\n the value of green=%d”,green);

printf(“\n the value of white=%d”,white); getch();

} Output: -

the value of red=0 the value of green=5

the value of white=9

Important Short Answer Type Questions

1. Give an example of enumerated data type in C. Important Long Answer Type Questions

1. Explain enum declaration in C with suitable example. 2. How can you differentiate enum from an array?

Chapter 13 POINTER

Pointer is a special type of variable, which is used to store the address of another variable. This variable starts with asterisk symbol (*). The pointer

can use two special operators. 1. The first one is *(asterisk), it is called indirection operator or

value of operator. 2. The second is &(ampersand), it is called address of operator.

Pointer declaration

A pointer is declared same as a variable with a specific data type. But declared with an asterisk sign. As show in the example below:

Example int *ip; //ip is our integer pointer

float *fp; //fp is our Float pointer char *cp; //cp is our character pointer

Address operator & (Ampersand)

As mentioned above, pointer uses two special operators; one of them is the address operator, which is used to assign the address of the variable to the

pointer variable. As shown the example below: int a,*ip;

a=5; ip=&a; /*here we can assign the address of variable a

to pointer variable ip*/

Indirection operator * (asterisk)

Page 106: best notes in c language for b

Basics of 'C' language Page No: 106

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Indirection operator is also known as value of operator, which is used to

print the value of the variable through pointer variable.The indirection operator is used to declare a pointer. As shown in the example below:

int a,*ip; a=5;

ip=&a; printf(“\n the value of a=%d”,a);

printf(“\n the value through pointer=%d”,*ip); /*here ip print the value of a */

Complete example of pointer variable

# include<stdio.h>

# include<conio.h> void main()

{ int a, *b;

clrscr();

a=5; b=&a;

printf(“\n the value of a=%d”,a); printf(“\n the address of a=%u”,&a);

printf(“\n the value of b=%u”,b); printf(“\n the value of b through pointer =%d”,*b);

getch(); }

output the value of a=5

the address of a=65524 the value of b=65524

the value through pointer b=5

5 65524

a

65524

a is Variable name

Address of the variable a

Value of the variable

b

65526

Pointer variable

Value of pointer variable

Address of pointer variable

Page 107: best notes in c language for b

Basics of 'C' language Page No: 107

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Write a program to add two numbers using pointers.

#include<stdio.h>

#include<conio.h> void main()

{ int a,,b,*c,*d, e;

clrscr(); printf(“enter the value of a=”);

scanf(“%d”,&a); printf(“enter the value of b=”);

scanf(“%d”,&b); c=&a;

d=&b; e=*c + *d;

printf(“sum=%d”,e); getch();

}

Write a program to swap two numbers using pointer without using third variable.

#include<stdio.h> #include<conio.h>

void main()

{ int a, b, *c, *d;

clrscr(); printf(“enter the value of a=”);

scanf(“%d”, &a); printf(“enter the value of b=”);

scanf(“%d” , &b); c=&a;

d=&b; //swapping of two numbers

*c= *c+ *d; *d= *c - *d;

*c= *c- *d; printf(“\after swapping the numbers”);

printf(“\n now the value of a=%d”,a);

printf(“\n now the value of b=%d”,b); getch();

}

Arithmetic pointers

We can also use pointers for arithmetic purposes same as variables. When we write a++ it increase the value of the variable but when we write p++,

Page 108: best notes in c language for b

Basics of 'C' language Page No: 108

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

it is a pointer variable it moves the pointer to the next memory location.

Like

int *p;

p++;

or

p=p+3;

Assume that the address of p is 65524.

When we add 3 to the pointer it move to the next location is 65527.

Note that we can perform any arithmetic operation on a pointer variable.

Pointers with array The values of the array can be accessed with the help of pointer. Normally

we can assign the address of first element of an array to the pointer. When we increment inside the pointer, it increments its address. It means

it reads the address of next element. The address of first element of an array is called base address of array.

As shown in the example below:

int a[]={2,4,3,5,6}; int *ip;

//here we can assign the address of array to the pointer. ip=&a[0];

/*We can also assign the address of the first element to the pointer*/ ip=a;

//Here we need not to mention the index of the array. Write a program to find the maximum number from the given array-

using pointer.

#include <stdio.h>

#include <conio.h> void main()

{ int a[5],*p, i, b;

clrscr(); for(i=0;i<5;i++)

{

printf(“enter any number”); scanf(“%d”,&a[i]);

} p=&a[0];

b=a[0]; for(i=0;i<5;i++)

{ if(*p>b)

{

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 109: best notes in c language for b

Basics of 'C' language Page No: 109

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

b=*p; }

p++;

} printf(“the maximum number=%d”,b);

getch();

}

Pointer with strings

A string is a group of characters, which contain characters. We can access the string-using pointer that read one character at time. We can assign the

address of first element of character array to the pointer. As shown in the given example below:

Write a program to print your name-using pointer.

#include<stdio.h> #include<conio.h>

void main() {

char a[50]="Charanjiv Singh"; char *p;

clrscr(); p=a;

while(*p!='\0')

{ printf("%c",*p);

p++; }

getch();

}

Pointer with two Dimensional array

We can also access the two-dimensional array-using pointer in which we can declare array with pointer.

As shown in the program: -

#include<stdio.h>

#include<conio.h> void main()

{

int a[3][3],*p,i,j; clrscr();

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

{

Page 110: best notes in c language for b

Basics of 'C' language Page No: 110

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

for(j=0;j<3;j++) {

printf("enter any number");

scanf("%d",&a[i][j]); }

} p=&a[0][0];

for(i=0;i<3;i++) {

for(j=0;j<3;j++) {

printf("%d",*p); p++;

} printf("\n");

} getch();

}

Pointer with structure

We can also access the elements of the structure with help of pointer. We can assign the address of the structure variable to the pointer variable. For

accessing the elements we can use arrow (->) operator in place of dot(.)

operator. Write a program to access the elements of the structure-using

pointer.

#include<stdio.h>

#include<conio.h> struct stu

{ char name[20];

int roll; };

void main() {

struct stu s={"Pratham",1}; struct stu *p;

clrscr(); p=&s;

printf("\n your name=%s",p->name);

printf("\n your roll=%d",p->roll); getch();

}

Pointer to pointer Pointer to pointer means which can store the address of another pointer

variable. A pointer-to-pointer variable start with double asterisk (**) sign. A

Page 111: best notes in c language for b

Basics of 'C' language Page No: 111

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

simple pointer can store the address of a variable but a pointer to pointer

can store the address of another pointer. As shown in the example below:

Example :-

int a, *p,**pp; a=5;

p=&a; pp=&p;

Example program

#include<stdio.h>

#include<conio.h> void main()

{ int a,*p,**pp;

clrscr(); a=5;

p=&a; pp=&p;

printf("\nthe value of a=%d",a);

printf("\nthe value of pointer =%d",*p); printf("\n the value of pointer to pointer=%d",**pp);

getch();

}

Pointer passing as argument to the Function We can also pass pointer variable as an argument into the function. This is

also known as reference variables.

As shown in the example below:

#include<stdio.h> #include<conio.h>

void swap(int *a , int *b); void swap(int *a, int *b)

{ *a=*a + *b;

*b=*a - *b; *a=*a - *b;

} void main()

{ int x,y;

clrscr();

printf(“enter the value of x”); scanf(“%d”,&x);

printf(“enter the value of y”); printf (“Before Swapping”);

printf(“\n %d/n%d”,x.y);

scanf(“%d”,&y);

Page 112: best notes in c language for b

Basics of 'C' language Page No: 112

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

swap(&x ,&y); printf(“\n after swapping “);

printf(“\n the value of x=%d”,x);

printf(“\n the value of y=%d”,y);

getch(); }

Function Returning Pointer

A function can return a pointer same as it returns a variable. In this we can declare and define the function with indirection (value of operator) operator.

As shown in the example given below

# include<stdio.h> #include<conio.h>

int *show(); int *show()

{ int a;

printf("enter any number"); scanf("%d", &a);

a=a*a; return &a;

} void main()

{

int *p; clrscr();

p=show(); printf("\n The value of a=%d",*p);

getch();

}

Advantages of Pointers

1. Pointers increase the speed of the program. 2. It is used to read the address of the variable.

3. It is used to the manage memory efficiently. 4. For Dynamic memory allocation we can use pointers.

5. With the help of pointers we can create efficient programs. 6. Pointers can be used to access elements of the structure.

7. It can pass as arguments into the function.

Difference Between A Variable And Pointer Variable

Variable Pointer variable

A variable starts with an alphabet. A pointer variable starts with an asterisk

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 113: best notes in c language for b

Basics of 'C' language Page No: 113

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

sign.

It can store the value. It can store the address of another variable

It can not use any special operator.

It uses two special operators first is address operator and second is indirection operator(value of operator).

When we perform any arithmetic operation on variable it increases

the value of the variable. Like

int a=5;

a++;

Now value of a=6.

when we perform any arithmetic operation on pointer variable it moves to

the next memory address. It increments in their address. Like int a=5,*p;

p=&a;

p++;

Now it increment in their address.

A float variable can store the value of an integer variable.

A float pointer can store the address of a float variable it cannot store the

address of integer variable.

Example

int a;

a=5;

Example

int *p,b=5;

p=&b;

It is also known as pointer variation. It mean the slightly difference between

the pointer variable and other variable

Dynamic memory allocation Dynamic memory means, memory which is allocated at run time in place of

compile time. In normal array or variable, the memory is allocated at compile time. It is known as static memory. The memory which is allocated

at run time is known as dynamic memory. This memory is accessed using pointer. For dynamic memory we can use various methods, which are stored

in the alloc.h header file.These function are:- 1. malloc() function

2. calloc () function 3. realloc() function

4. free() function 1. malloc()Function:- malloc means memory allocation function.

This function is used to allocate dynamic memory at run time to the

pointer variable. This function allocates a single block of memory of specific data type. As shown in the example below:

Write a program to print the elements of pointer using malloc function

#include<stdio.h>

#include<conio.h>

Page 114: best notes in c language for b

Basics of 'C' language Page No: 114

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include<alloc.h> void main()

{

int i, n,*p; clrscr();

printf("enter the size of the values"); scanf("%d",&n);

p=(int*) malloc(n); for(i=0;i<n;i++)

{ printf("enter any number");

scanf("%d",(p+i)); }

for(i=0;i<n;i++) {

printf("%d\n",(*p)); p++;

}

getch(); }

2. Calloc() Function:- This function is also used for dynamic memory

allocation same as malloc function but this function contain two arguments. The first argument tells the number of elements(items) and

the second argument tells their size. It allocates number of blocks memory. As shown in the syntax and example program given below:

void calloc(number of items, size);

#include<stdio.h> #include<conio.h>

#include<alloc.h> void main()

{ char *p=NULL;

clrscr(); p=(char*) calloc(10,sizeof(char));

printf("enter any string"); scanf("%s",p);

printf("%s",p);

getch();

}

3. Realloc() Function:- Realloc function means reallocation of memory. This function is used to reallocate memory to the preallocated pointer

variable. This function is used to increase and decrease the size of the memory. As shown in the syntax and example below:

Page 115: best notes in c language for b

Basics of 'C' language Page No: 115

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

#include <stdio.h> #include <alloc.h>

#include <string.h>

#include<conio.h> void main()

{ char *p;

clrscr(); p = (char *) malloc(10);

strcpy (p, "CJSOFTECH"); printf("String is %s”,p);

printf(“\n Address is %u”, p); p = (char *) realloc(p, 20);

strcpy(p,"CJSOFTECH Patiala"); printf(“String is %s”,p);

printf(“\n New address is %u",p); getch();

}

4. Free function:- This function is used to release the memory which is

occupied by the variable. That memory, which is allocated by the above discussed functions like malloc(), calloc(), realloc(), so this function is

used to free the memory. This function contains a single argument,

whose memory we want to release. As shown in the syntax and example below:

void free (pointer variable);

Example free(*p);

Important Short Answer Type Questions

1. List the applications of pointers in C. 2. What is indirection operator?

3. What is address of operator? 4. What are the advantages of pointers?

5. What is the significance of calloc function in C?

6. What is dynamic memory allocation? 7. What do you mean by pointer to pointer?

8. Why pointer is called double edge weapon? Explain.

Important Long Answer Type Questions

1. Explain with examples the pointer concept in C. State the advantages of pointers in C.

Page 116: best notes in c language for b

Basics of 'C' language Page No: 116

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

2. What is a pointer? Explain the difference between simple variable and

pointer variable. 3. Demonstrate how pointer can be used to access data of a structure.

4. Describe how pointers are used for handling character string. 5. Write C program-using pointers to find the greatest of given three

numbers. 6. Write C program-using pointers to sort the given list of number in

ascending order. 7. What do you mean by dynamic memory allocation. Explain different

methods used for dynamic memory allocation.

CJ SOFTECH Walia Enclave CJ SOFTECH Walia Enclave CJ SOFTECH Walia Enclave CJ SOFTECH Walia Enclave Opp Punjabi Univ PatialOpp Punjabi Univ PatialOpp Punjabi Univ PatialOpp Punjabi Univ Patiala.a.a.a.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 2 2 2

PatialaPatialaPatialaPatiala

Page 117: best notes in c language for b

Basics of 'C' language Page No: 117

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 14 FILE HANDLING IN C

To understand the concept of File handling, we must understand the following things;

1. Data : Raw information is called data. For example student

name, father’s name, address, dob, rollno etc. Each individual item is called data.

For example

Name is a data, rollno is a data, dob is a data. In electricity dept person name, address, meter no is a data.

2. Record: Record is a collection of data of same type. It is a detail of data. For example all things in your admission form name,

fname, dob, rollno, marks of yours together is known as record. For example (navjeet, s. karamjit singh, 2-08- 1983, 1. 89). It is a

record of a single student. In one record data should be of same concerned item or thing or

person. In one record we cannot mix data of different things.

Eg; name of ram

Roll no of sham This is wrong. Here Roll No and Name must be of same person.

Now you see two different records Student’s Record Record in Electricity dept

Suppose these two different records are of yours. Name, Ph.no,

Address is common. But Roll no, meter no is different that’s why we create different records.

3. File : File is a collection of similar same type of records. For example student’s records will be placed in a one file. (Student name,

Address, father’s name, phno, rollno, school name) Electricity dept will hold records of bill in different file(Person Name,

Address , Ph No, Meter No, Old Reading, New Reading) Note

Person name Address Ph No Meter No Old Reading New Reading

Student name Address Father’s Name Ph No Roll No School Name

D A T A

Page 118: best notes in c language for b

Basics of 'C' language Page No: 118

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

We cannot mix different records in a one file. To maintain different

records we need to maintain different records. That’s why we need to maintain different files.

Diagram of file

In earlier days, the amount of information is stored in manual form. The

major drawbacks of manual system are Required more space to store the data in file Updating of data was very difficult.

Searching is quite difficult. No security in manual Files Manual file were not reliable means if file was

lost all the data would also lost. Now modern files are made on computers. The data is stored in

computerized files. It has following advantages;

1. Data can be easily stored in compact space updating of data is very easy. Using the pointers concept when we perform any changes

in a file, all the files which related with that file are automatically updated.

2. Searching is very easy.

3. The data in modern file are very secure. Only the authorized persons can view data.

4. Files are very reliable because adequate backup checks are there.

The main motive of file handling is to transfer the data from primary memory to secondary memory.

Types of Files

There are three types of files, which are;

Data Data Data Data Data Data Data

Data

1 record

2nd record

Name Father’s Name Address Ph No DOB City School Marks

(N records mark 1 file) N records

3rd record

Page 119: best notes in c language for b

Basics of 'C' language Page No: 119

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

1. Text Files

2. Data Files 3. Binary Files

1. Text Files: - Text files are those files, which store the information in the text format. It stores the data into character or strings. The

extension of text file is .txt. 2. Data Files: - Data files are known as database files, which store the

data in different formats. The extension of data file is .dat. 3. Binary Files: - These files store data in binary form. These files store

data in sequence of bytes. It is an Encrypted file so we cannot read it. FILE Structure

FILE is our inbuilt structure, which is used to create a file. We can create a pointer of the FILE structure. It is known as file declaration. As shown in the

example and syntax. Syntax:-

FILE filepointer;

Example:-

FILE *fp;

Note: The type name FILE is always written in capital letters

File handling Functions

1. fopen() functon:- Before using data file it is necessary to open that file. It can be opened by using fopen() function. The function has

two arguments, first is name of the file to be opened , and second is string representing mode in which the file is to be opened. As shown in

the syntax and example given below:

Syntax:-

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

e.g.

fp=fopen(“CJSOFTECH.txt”,”w”);

File name: - It specifies the file name where we want to store the

data. Like “CJSOFTECH.txt”, here CJSOFTECH is the file name and .txt

its extension. It means it is a text file.

Modes: -File can be opened in following modes:

1. Read: - In this mode we can read the data from the file. When a file is opened in this mode, it is not possible to write the data into the

file. We can use ”r” as a parameter in fopen function.

2. Write: - If a file in this mode is opened we can write the data

into the file but it is not possible to read the data from file. A file already exists is opened in the write mode, the old contents of the file

will be deleted and new data can be written in the file. We can use ”w” as a parameter in fopen function.

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 120: best notes in c language for b

Basics of 'C' language Page No: 120

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

3. Append: - If a file in this mode is opened we can add the data

into the file at the end of the file. Parameter used in fopen is “a”. r+ mode:- To open the file for reading and writing the data.

w+ mode:- To open the file for writing. Data can be read after writing. a+ mode:- To open the file ,write the data at the end of the file. Data

can be read after writing. 2. fclose() function:- It is used to close a file. This function

contains a single argument, which is the file pointer. As shown in the syntax and example given below:

Syntax: - fclose(file pointer);

Example:

fclose(fp); 3. fputs() function:- It is used to write a string into the file. This

function contains two arguments first is string and second is the file pointer. As shown in the syntax and example

Syntax : - fputs(string, file pointer);

Example:- fputs(str, fp);

4. fgets() function:- This function is used to read the data from a file in string format. This function contains three arguments. First is

string in which data is stored, second argument is the length of the string and third is the file pointer (fp). As shown in the syntax and

example

Syntax: - fgets(string, length, file pointer);

Example: -

fgets(str,40,fp); 5. getc() Function:- This function is used to read a character from a

file. This function contains a single argument of file pointer. As shown in the syntax and example-

Syntax: - variable=getc(file pointer);

Example: char a;

a=getc(fp); Note:

The character read from the file is assigned to a char variable a.

6. putc() Function:-This function is used to write a character to a file. It has two arguments, first is the character variable and second is

the file pointer. As shown in the example:- Example:char a;

putc(a,fp); Note:

Page 121: best notes in c language for b

Basics of 'C' language Page No: 121

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

The value of a char variable ‘a’ is written in the file.

7. getw () Function:- This function is used to read an integer from a file. This function also contains a single argument, which is the

file pointer. As shown in the example: - a=getw(fp);

8. putw() Function:- This function is used to write an integer to a file. This function contain two arguments, first is the integer variable

and second is the file pointer. As shown in the example: - putw(a,fp);

9. feof function :- feof means file end of file. This function reads the file till end. This function returns a negative number when we reach

at the end of the file. As shown in the example:- while(feof(fp)!=-1)

Write a program to store the data in the file using fputs() function.

include<stdio.h>

include<conio.h> void main()

{

char str[32]; FILE *fp;

clrscr(); printf(“enter any string”);

gets (str); fp=fopen(“CJSOFTECH.txt”,”w”);

puts(str,fp); printf(“data is written into the file”);

fclose(fp);

getch(); }

WAP to read the data from a file using fgets() function.

include<stdio.h>

include<conio.h> void main()

{ char str[32],*p;

FILE *fp; clrscr();

fp=fopen(“CJSOFTECH.txt”,”r”); while((p=fgets(str,40,fp))!=’\0’)

{

printf(“%s”,str); }

fclose(fp);

getch(); }

WAP to copy the contents of one file into another file.

include<stdio.h>

Page 122: best notes in c language for b

Basics of 'C' language Page No: 122

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

include<conio.h> void main()

{

char str[32],*p; FILE *fp,*fp1;

clrscr(); fp=fopen(“CJSOFTECH.txt”,”r”);

fp1=fopen(“CJSOFTECH.txt”,”w”); while((p=fgets(str,40,fp))!=’\0’)

{ fputs(str,fp1);

} fclose(fp);

printf(“data is copied”); fclose(fp1);

getch();

}

Write a program to write Integer data in a Binary file.

void main()

{ FILE *fp;

int i; clrscr();

fp=fopen("CJSOFTECH.dat","w");

for(i=1;i<=10;i++) {

putw(i,fp); }

printf("data is written"); fclose(fp);

getch();

}

Write a program to read integer data from a Binary file.

#include<stdio.h>

#include<conio.h> void main()

{ FILE *fp;

int n; clrscr();

fp=fopen("CJSOFTECH.dat","r"); while((n=getw(fp))!=EOF)

{

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 123: best notes in c language for b

Basics of 'C' language Page No: 123

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

printf("%d",n); }

fclose(fp);

getch();

}

Random Access Files

Random access file are those files in which we can read and write the data at

random location. But in some situation, when we need to access the data from a specific part of a file., then we use fseek(), ftell(), and rewind()

functions.

1. fseek() Function:- fseek function is used to move the file

pointer to a desired location within the file. This function contains three arguments . The first argument is the file pointer, second

argument tells how many bytes move in the file and third argument tells the current position of the pointer. As shown in the syntax: -

fseek(file pointer, n, position); 2. ftell() Function:- This function tells us the current position of

the pointer. This function contains a single argument of file pointer. As shown in the given syntax:-

n=ftell(file pointer); 3. rewind() Function:- This function is used to set the pointer or

cursor in the beginning of the file. This function contains a single

argument of file pointer. As shown in the syntax: rewind(fp);

Error Handling during input/output operations Error is occurring during input/output operation of the file when an

error is occurred in the program the program is terminated. There are so many reasons for an error like file not found, null pointer etc.

Error Handling Error handling means to solve the problem or to remove the errors

with the help of inbuilt function, which are provided us by the programming language.

� NULL: - This help us to check if the file is exist or not. If file does not exist then it equal to null. As shown in the example:-

FILE *fp; Fp=fopen(“CJSOFTECH.txt”,”r”);

If(fp==NULL) {

printf(“File doesn’t exist”);

exit(0); }

else {

Read the file contents” }

Page 124: best notes in c language for b

Basics of 'C' language Page No: 124

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

� ferror():- This is known as file error function. This function is

used when we access the file, if there is any problem in accessing the file then this function returns a positive or negative number. But when

there is no problem in accessing the file then it returns zero. As shown in the example: -

FILE *fp; fp=fopen(“CJSOFTECH.txt”,”w”);

if (ferror(fp)==0) {

printf(“No problem in file accessing”); }

else {

printf(“There is problem in file accessing”);

}

� EOF():- This is known as End of file. This function is used to check the file end. In place of EOF we can use –1. It is same as end of

file; when our cursor reach as the end of the file then it returns a negative number –1 or EOF. As shown in the example:-

FILE *fp; int a;

fp=fopen*(“CJSOFTECH.txt”,”r”); While(a=getw(fp)!=EOF)

{

printf(“\n %d”,a);

}

Important Short Answer Type Questions 1. List down two file opening modes in C?

2. What are random access files? 3. What is a FILE?

4. What are the advantages of data file over other data types? 5. Difference between fseek() and ftell() function.

Important Long Answer Type Questions 1. Explain various File Handling Functions available in C.

2. Write a C program to read a text from the file and display it on the screen.

3. Write a C program to copy the contents of a file into another file and also update that file.

4. Discuss in brief getw(), putw() functions. 5. Distinguish between append mode and write mode.

6. State the difference between Sequential Files and Random

Access Files. 7. Explain character input/output handling functions.

8. Write a C program to create a file containing integers and display them.

9. What is the advantage of using a data file?

Page 125: best notes in c language for b

Basics of 'C' language Page No: 125

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

Chapter 15 MACRO

Macro is also called a substitution string. A macro always start with # define. After the # define, we can give the name to the macro and after that

we can give replacement text/value. Wherever the preprocessor encounters that name, it will replace it with the replacement text. Macro is always

declared in capital letters, which differentiate the macro from variable. If we want to change the value of the macro variable we can do it at only at place

where it is defined. Macro never ends with semicolon. The value of the macro body specified by a #define directive can be any

character string or number. For example, the following definition is NAME

with the string "CJSOFTECH". SYNTAX:

#define <identifier><value> Example:-

#define A 50 WAP to use macro in the program.

#include<stdio.h> #include<conio.h>

#define a 10 void main()

{ int b;

clrscr(); b=a*a;

printf(“square=%d”,b); getch();

}

In macro we can also pass arguments inside the macro. It works as function, which are defined before using it.

Write a program to swap two numbers without using third variable

and by using macro.

#include<stdio.h>

#include<conio.h> #define swap(x,y)x=x+y;y=x-y;x=x-y

void main() {

int a,b; clrscr();

printf(“enter two no”); scanf(“%d%d”, &a,&b);

swap(a,b); printf(“\n now value of a=%d” ,a);

printf(“\n now value of b=%d”,b);

Page 126: best notes in c language for b

Basics of 'C' language Page No: 126

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

getch(); }

Typedef Definition: - Typedef means to rename the existing data type. With the

help of ‘typedef’ we can give the new name to the inbuilt data type

/structure typedef declaration does not declare any new data type which does not exist in the C language. Typedef means to create new definition

name of an existing data type.

SYNTAX: -

typedef<data type><new data type>; Example: -

typedef int cj ;

Example:-

#include<stdio.h>

#include<conio.h> void main()

{ typedef int cj;

clrscr(); cj a,b,c;

printf(“enter two numbers”)

scanf(“%d%d”,&a,&b); c=a+b;

printf(“sum=%d”,c); getch();

}

Command Line Arguments Command line arguments is the another way to input the values into our

program using console instead of using scanf() function. In C ,mostly we use scanf() to input the values into the program. Command line arguments are

the values passed into the main function from command line (Dos prompt). We can pass two arguments to the main() function:

1. argc : integer type argument Indicates the number of parameters passed.

2. argv : array of strings Each string in this array will represent a parameter that is passed to

main().

CJ SOFTECH Walia CJ SOFTECH Walia CJ SOFTECH Walia CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.Enclave Opp Punjabi Univ Patiala.Enclave Opp Punjabi Univ Patiala.Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 Patiala 2 Patiala 2 Patiala 2 Patiala

Page 127: best notes in c language for b

Basics of 'C' language Page No: 127

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

As shown in the program below:

#include<stdio.h>

#include<conio.h> void main(int argc,char *argv[])

{ int i;

clrscr(); for(i=1;i<argc;i++)

{ printf("%s",argv[i]);

} getch();

}

Steps to execute the program

1. After typing the program save the file with .c extension. 2. Now compile the program using ALT+F9.

3. Now click on file menu and select “Dos shell” option. 4. Now first type file name and then type number of arguments.

Example: - C:\tc\bin> filename one two three

Note: -Here CJSOFTECH is the file name and one ,two three are

arguments 5. Now press enter key.

To go back to the C program type “exit” and press enter key

Imp Short Answer Type Questions 1. Define Macro.

2. Write a note on typedef. 3. What are command line arguments?

4. Why do we use #define? 5. WAP to create a macro to find the square of a number.

CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.CJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Estate Phase Urban Estate Phase Urban Estate Phase Urban Estate Phase –––– 2 2 2 2 Patiala Patiala Patiala Patiala

Page 128: best notes in c language for b

Basics of 'C' language Page No: 128

Prepared By: CJ SofTech [Charanjiv Singh 98156-18658] Coaching Of C,C++,C#, Java, Blue J, VB, VB.NET, Oracle, Data Structure And Project Work

CJ SOFTECH CJ SOFTECH CJ SOFTECH CJ SOFTECH Walia Enclave Walia Enclave Walia Enclave Walia Enclave

Opp Punjabi Univ Opp Punjabi Univ Opp Punjabi Univ Opp Punjabi Univ Patiala.Patiala.Patiala.Patiala.

# 3058 # 3058 # 3058 # 3058 Urban Urban Urban Urban Estate Phase Estate Phase Estate Phase Estate Phase –––– 2 2 2 2

PatialaPatialaPatialaPatiala