SlideShare a Scribd company logo
1 of 128
Notes
Of
C
Language
By
Cj-SofTech
Opp
Punjabi Univ.
Patiala
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
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.
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
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
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
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
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
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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.
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
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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
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.
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
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
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.
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:tcbin 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:-
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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 Phaseban Estate Phaseban Estate Phaseban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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
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”
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”);
}
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();
}
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2222 PatialaPatialaPatialaPatiala
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();
}
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();
}
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(“hellonbye”);
Output:
hello
bye
With t Escape sequence:
Using t some space[TAB]will be displayed before printing next
information
printf(“hellotbye”);
Output:
hello bye
With b Escape sequence:
After b one character from the left of b is deleted
printf(“hellobbye”);
Output:
hellbye
With r Escape sequence:
Using r position of the cursor come to the beginning of the line.
printf(“hellorbye”);
Output:
byelo
With a sequence:
It produce beep sound.
printf(“helloabye”);
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
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
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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
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 !
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.
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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=%dn”,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;
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)
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.
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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
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.
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
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 OppCJ SOFTECH Walia Enclave OppCJ SOFTECH Walia Enclave OppCJ SOFTECH Walia Enclave Opp
Punjabi Univ Patiala.Punjabi Univ Patiala.Punjabi Univ Patiala.Punjabi Univ Patiala.
# 3058# 3058# 3058# 3058 Urban Estate PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2222
PatialaPatialaPatialaPatiala
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;
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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.
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;
-----------------
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");
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”);
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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;
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
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();
}
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 WaliaCJ SOFTECH WaliaCJ SOFTECH WaliaCJ 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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();
}
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();
}
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.
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();
}
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
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();
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;
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
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
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.
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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language
best notes in c language

More Related Content

What's hot

C presentation book
C presentation bookC presentation book
C presentation bookkrunal1210
 
Command line arguments
Command line argumentsCommand line arguments
Command line argumentsAshok Raj
 
structured programming
structured programmingstructured programming
structured programmingAhmad54321
 
Introduction of c programming
Introduction of c programmingIntroduction of c programming
Introduction of c programmingTarun Sharma
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm designNahid Hasan
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basicsSabik T S
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CPrabu U
 

What's hot (20)

Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
 
C presentation book
C presentation bookC presentation book
C presentation book
 
History of c
History of cHistory of c
History of c
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
structured programming
structured programmingstructured programming
structured programming
 
Modular programming
Modular programmingModular programming
Modular programming
 
Introduction of c programming
Introduction of c programmingIntroduction of c programming
Introduction of c programming
 
Break and continue
Break and continueBreak and continue
Break and continue
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm design
 
pseudo code basics
pseudo code basicspseudo code basics
pseudo code basics
 
C#.NET
C#.NETC#.NET
C#.NET
 
Function in C
Function in CFunction in C
Function in C
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Features of c
Features of cFeatures of c
Features of c
 
Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to C
 
Programming in c notes
Programming in c notesProgramming in c notes
Programming in c notes
 

Similar to best notes in c language

CS291(C Programming) assignment
CS291(C Programming) assignmentCS291(C Programming) assignment
CS291(C Programming) assignmentKuntal Bhowmick
 
Report in Java programming and SQL
Report in Java programming and SQLReport in Java programming and SQL
Report in Java programming and SQLvikram mahendra
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
C - Programming Assignment 1 and 2
C - Programming Assignment 1 and 2C - Programming Assignment 1 and 2
C - Programming Assignment 1 and 2Animesh Chaturvedi
 
Important C program of Balagurusamy Book
Important C program of Balagurusamy BookImportant C program of Balagurusamy Book
Important C program of Balagurusamy BookAbir Hossain
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newLast7693
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newscottbrownnn
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab neweyavagal
 
Assignment 1 for 2nd sem
Assignment 1 for 2nd semAssignment 1 for 2nd sem
Assignment 1 for 2nd semhome
 
C_Lab Manual_Part A.docx
C_Lab Manual_Part A.docxC_Lab Manual_Part A.docx
C_Lab Manual_Part A.docxPandiya Rajan
 
Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- Cswatisinghal
 
HSc Computer Science Practical Slip for Class 12
HSc Computer Science Practical Slip for Class 12HSc Computer Science Practical Slip for Class 12
HSc Computer Science Practical Slip for Class 12Aditi Bhushan
 

Similar to best notes in c language (20)

Programming qns
Programming qnsProgramming qns
Programming qns
 
CS291(C Programming) assignment
CS291(C Programming) assignmentCS291(C Programming) assignment
CS291(C Programming) assignment
 
Cp manual final
Cp manual finalCp manual final
Cp manual final
 
Report in Java programming and SQL
Report in Java programming and SQLReport in Java programming and SQL
Report in Java programming and SQL
 
Java Practice Set
Java Practice SetJava Practice Set
Java Practice Set
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Mmt 001
Mmt 001Mmt 001
Mmt 001
 
Programming Fundamental handouts
Programming Fundamental handoutsProgramming Fundamental handouts
Programming Fundamental handouts
 
C - Programming Assignment 1 and 2
C - Programming Assignment 1 and 2C - Programming Assignment 1 and 2
C - Programming Assignment 1 and 2
 
Important C program of Balagurusamy Book
Important C program of Balagurusamy BookImportant C program of Balagurusamy Book
Important C program of Balagurusamy Book
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
Md university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab newMd university cmis 102 week 4 hands on lab new
Md university cmis 102 week 4 hands on lab new
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
Assignment 1 for 2nd sem
Assignment 1 for 2nd semAssignment 1 for 2nd sem
Assignment 1 for 2nd sem
 
C_Lab Manual_Part A.docx
C_Lab Manual_Part A.docxC_Lab Manual_Part A.docx
C_Lab Manual_Part A.docx
 
Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- C
 
HSc Computer Science Practical Slip for Class 12
HSc Computer Science Practical Slip for Class 12HSc Computer Science Practical Slip for Class 12
HSc Computer Science Practical Slip for Class 12
 
Java codes
Java codesJava codes
Java codes
 

More from India

Isometric
IsometricIsometric
IsometricIndia
 
Ortographic projection
Ortographic projectionOrtographic projection
Ortographic projectionIndia
 
Ortho.ppt
Ortho.pptOrtho.ppt
Ortho.pptIndia
 
Projection of solids(thedirectdata.com)
Projection of solids(thedirectdata.com)Projection of solids(thedirectdata.com)
Projection of solids(thedirectdata.com)India
 
Projection of lines(new)
Projection of lines(new)Projection of lines(new)
Projection of lines(new)India
 
Projection of lines with problems
Projection of lines with problemsProjection of lines with problems
Projection of lines with problemsIndia
 
Ortographic projection
Ortographic projectionOrtographic projection
Ortographic projectionIndia
 
Lecture 1 for ed
Lecture 1 for edLecture 1 for ed
Lecture 1 for edIndia
 
Lect 1.point
Lect 1.pointLect 1.point
Lect 1.pointIndia
 
Engg graphics complete course
Engg graphics complete course Engg graphics complete course
Engg graphics complete course India
 

More from India (10)

Isometric
IsometricIsometric
Isometric
 
Ortographic projection
Ortographic projectionOrtographic projection
Ortographic projection
 
Ortho.ppt
Ortho.pptOrtho.ppt
Ortho.ppt
 
Projection of solids(thedirectdata.com)
Projection of solids(thedirectdata.com)Projection of solids(thedirectdata.com)
Projection of solids(thedirectdata.com)
 
Projection of lines(new)
Projection of lines(new)Projection of lines(new)
Projection of lines(new)
 
Projection of lines with problems
Projection of lines with problemsProjection of lines with problems
Projection of lines with problems
 
Ortographic projection
Ortographic projectionOrtographic projection
Ortographic projection
 
Lecture 1 for ed
Lecture 1 for edLecture 1 for ed
Lecture 1 for ed
 
Lect 1.point
Lect 1.pointLect 1.point
Lect 1.point
 
Engg graphics complete course
Engg graphics complete course Engg graphics complete course
Engg graphics complete course
 

Recently uploaded

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 

Recently uploaded (20)

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 

best notes in c language

  • 2. 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
  • 3. 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.
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 10. 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.
  • 11. 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
  • 12. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 13. 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
  • 14. 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.
  • 15. 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
  • 16. 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
  • 17. 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.
  • 18. 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:tcbin 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:-
  • 19. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 20. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 21. 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 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 22. 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 Phaseban Estate Phaseban Estate Phaseban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 23. 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
  • 24. 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”
  • 25. 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”); }
  • 26. 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(); }
  • 27. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2222 PatialaPatialaPatialaPatiala
  • 28. 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(); }
  • 29. 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(); }
  • 30. 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(“hellonbye”); Output: hello bye With t Escape sequence: Using t some space[TAB]will be displayed before printing next information printf(“hellotbye”); Output: hello bye With b Escape sequence: After b one character from the left of b is deleted printf(“hellobbye”); Output: hellbye With r Escape sequence: Using r position of the cursor come to the beginning of the line. printf(“hellorbye”); Output: byelo With a sequence: It produce beep sound. printf(“helloabye”); 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
  • 31. 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
  • 32. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 33. 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
  • 34. 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 !
  • 35. 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.
  • 36. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 37. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 38. 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=%dn”,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;
  • 39. 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)
  • 40. 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.
  • 41. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 42. 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
  • 43. 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.
  • 44. 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
  • 45. 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 OppCJ SOFTECH Walia Enclave OppCJ SOFTECH Walia Enclave OppCJ SOFTECH Walia Enclave Opp Punjabi Univ Patiala.Punjabi Univ Patiala.Punjabi Univ Patiala.Punjabi Univ Patiala. # 3058# 3058# 3058# 3058 Urban Estate PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2222 PatialaPatialaPatialaPatiala
  • 46. 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;
  • 47. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 48. 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.
  • 49. 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; -----------------
  • 50. 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");
  • 51. 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”);
  • 52. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 53. 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;
  • 54. 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
  • 55. 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(); }
  • 56. 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 WaliaCJ SOFTECH WaliaCJ SOFTECH WaliaCJ 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 57. 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(); }
  • 58. 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(); }
  • 59. 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.
  • 60. 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(); }
  • 61. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala
  • 62. 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();
  • 63. 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;
  • 64. 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
  • 65. 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
  • 66. 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.
  • 67. 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 PhaseUrban Estate PhaseUrban Estate PhaseUrban Estate Phase –––– 2 Patiala2 Patiala2 Patiala2 Patiala