Upload
toaster97
View
272
Download
23
Embed Size (px)
Citation preview
7/30/2019 C Language Full Notes
1/179
INTRODUCTION
COMPUTER: Computer is an electronic device, which has memory and performs arithmetic and logicaloperations.
Input: The data entered in the computer is called input. Ex:- Keyboard, mouse, joy stick etc.,
Output: The resultant information obtained by the computer is called output. Ex:- Through Screen, Printer etc.,
Program: A sequence of instructions that can be executed by the computer is called program.
Software: A group of program to operate and control the computer is called software
Hardware: All the physical components or units of computer system connected to the computer circuit is calledhardware.
Operating System: It is an interface between user and the computer. In other words, operating system is acomplex set of programs, that manage the resources of a computer. Resource include input, output, processoretc., So operating system is a Resource manager.
Language: It consists of a set of executable instructions.
Package: It is designed by any other language with limited resources.
Various steps involved in program or Application development: The following steps are involved inprogram development.
1. Problem definition
2. Analysis and Design3. Algorithms4. Flow Chart5. Coding and Implementation6. Debugging ( errors) and testing7. Documentation1. Problem Definition: Problem definition phase is a clear understanding of exactly what is needed for
creating a workable solution. We must know exactly what we want to do before we do a problem. Itinvolves three specifications regarding a proper definition.
Input Specification Output Specification Processing
2. Analysis and Design: Before going to make a final solution for the problem, the problem must beanalyzed outline solution is prepared in the case of simple problems. But in the case of complexproblems, the main problem is divided into sub problems called modules. These modules can behandled and can be solved independently. When the task is too big, it is always better to analyze thetask, such that, it can be divided into number of modules and seek solution for each.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
2/179
3. Algorithms: Once the problem is divided into number of modules, the logic for solving each modulecan be developed. The logic is expressed step by step. A step by step procedure to solve the givenproblem is called algorithm. An algorithm is defined as a finite set of instructions which accomplish aparticular task. An algorithm can be described in a natural language like English.
4. Flow Chart: After completion of algorithm, the program can be visualized by drawing a flow chart. A
flow chart is nothing but a graphical or symbolic representation of how instructions will be executed oneafter another.5. Coding and Implementation: Coding is a process of converting6. the algorithm solution of flow chart in computer program. In this7. process each and every step of algorithm is converted to instructions of selected computer program
language. Before selecting the programming language we must follow three considerations. Nature of problem
Programming language available.
Limitations of computer.
8. Debugging and Testing:-
Debugging: Before loading the program into the computer we must correct all the errors. This processis called debugging. There are three types of errors.
*Syntax error
*Runtime error
*Logical error
Testing:- It is very important to test the program written to achieve a specific task. Testing is runningthe program with known data and known result.
7. Documentation:- It is the most important aspect of programming. It is a continuous process. To keepthe copy of continuous process. To keep the copy of all the phases (involving) in parts, definitionanalysis and designing, algorithm, flow chart, coding and implementation, debugging and testing are theparts of the documentation. This phase involves to produce written document for the user.
Classification of Programming Language
Programming language can be classified into 2 types1. High Level Language and2. Low Level Language.
High Level Language:- Those are more English like language and hence the programmers foundthem very easy to learn to convert the programs in high level language to machine languagecompilers and interpreters are used.
Low Level Language:- All low level language called assembly language is designed in thebeginning. It has some simple instructions. Those instructions are not binary codes. But thecomputer can understand only the machine language. Hence a converter or translator is developed totranslate the low level language programs into machine language. This translator is known asAssembler.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
3/179
Translators:- There are three types of translators available for the language.
1. Assembler
2. Compiler
3. Interpreter
1. Assembler:- This translator is used to convert the programs written in low levellanguage(Assembly) into machine language.
2. Compiler:- Compiler is used to convert high level language into machine level language. Itchecks for error in the entire program and converts the program into machine language.
3. Interpreter:- This is also used to convert high level language into machine language. It checksfor errors statement by statement and converts the statement into machine level language.
There are 256 characters by the micro computer. These values 0 to255. These can be divided operating system under.Character type Number of Character
Capital letteres 26 ( A to Z)Small Letters 26 (a to z)Digits 10 ( 0 to 9)Special symbols 32Control Characters 34Graphics Characters 128
Out of the 256 character set. First 128 are called ASCII Characters and the next 128 as extendedASCII Characters each ASCII character has a unique appearance.
A to Z 65 to 90a to z 97 to 1220 to 9 48 to 57Enter 13Space 32Tab 9Back Space 8
Algorithm:-A step by step procedure to solve the given problem is known as algorithm.1. To find the sum, product, and division of given two numbers.
Steps:--
1. Read any two numbers a,b2. sum=a+b3. product=a*b4. division=a/b5. print sum, product, division6. end
2. To find the maximum value of given two numbers:
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
4/179
Steps:-
1. Read any two values a,b2. max=a3. if max
7/30/2019 C Language Full Notes
5/179
2. fact=13. fact=fact*n4. n=n-15. if n>=1 then go to step36. print fact
7. end
8. To display how many digits in given number
Steps:
1. Read n2. nd=03. nd=nd+14. n=n/105. if n>0 then go to step36. print nd7. end
9.To calculate and display sum of given digits in given number
Steps:-
1. Read n 252. Sum=03. Sum=Sum+(n%10) sum=5+2=74. n=n/10 2/10=05. If n>0 then go to step36. Print sum7. end
10. To check whether the given number is Palindrome or not
Steps:-
1. Read n 222. rev=0,m=n m=223. rev=rev*10+(m%10) 2*10+(2%10)=224. m=m/10 22/10 =25. if n>0 then go to step36. if n= = rev then print n is palindrome
elsen is not palindrome
7. endFLOW CHART
Definition: Graphical or Symbolic representation of given algorithm or problemknown as Flow Chart.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
6/179
Frequently used Symbols in Flow Charts as Follows
1. Rectangles with round edges or Oval shape is used to indicate the Start or Stop the procedure.
2. Parallelograms are used to represent the input and outputoperators.
3. Rectangles are used to represent a data transfer operations and arithmetic operations (Processing)
4. Rhombus or Diamond shape is used to represent the conditional statement.
5. Circles are used to join the different parts of a flow chart
6. Arrows indicator the directions to be followed in a flow chart. Every line in a flow chart must be an
arrow on it
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
7/179
C LANGUAGE
C is a programming language it is designed by DENNIS RITCHIE in 1972 at AT & T [AmericanTelephone and telegraphs] Bell labs in USA. C is most popular general purpose language.
BRIEF HISTORY OF C LANGUAGE:In 1960s COBOL was being used for commercial applications and FORTRAN for scientific andengineering applications. At this stage people started to develop a language which is suitable for all possibleapplications. Therefore an international committee was setup to develop such a language ALGOL 60 wasreleased. It was not the generality a new language called CPL [Combine Programming Language] wasdeveloped at Cambridge University then some other features were added to this language a new language calledBCPL [Basic combine programming language] developed by MARTIN RICHARDS at Cambridge UniversityThen B language was developed by KENTHOMSON at AT &T Bell labs.
DENNIS RITCHIED inherited the features of B and BCPL, added some of its own feature anddeveloped C language in 1972.
Features of C Language:
1. C is structured programming language with fundamental flow chart constructions.2. C is highly portable programming language. The programs return for one computers can be run on
another with or without any modifications.3. The programs return in C are efficient and fast.4. C improves by itself it has several predefined functions.5. C has only 32 keywords.6. C supports all data conversions and mixed mode operators.7. Dynamic memory storage allocation is possible with C.8. C is simple and versatile programming language.9. C easily manipulate with bytes, bits and address.10. C has a richest of operators.11. Extensive verities of da x ta types such as pointers, structures, Unions etc., available in C.12. Recursive function calls for algorithmic approach is possible with C.13. Mainly we are using the C language to implement the system software those are compilers, text
editors, Network drives, data base utilities and finally the operating systems.14. C compiler combines the capabilities of assembly level language with the features of high leve
language. So it is called as middle level language.
Important Points
1. C is a case sensitive programming language. C statements are entered in lower case letters only.2. Every C statement must be terminated by a semicolon ( ; ) except preprocessor statements and
function definition.3. C is a function oriented language. Any C program contains one or more functions. Mainly one
function is necessary by the name called main. Without main we cannot execute C Programs.4. A function is represented by a function name with a pair of parenthesis.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
8/179
BLOCK DIAGRAM OF EXECUTION OF C PROGRAME
Once the coding is completed, the program is feed into the computer using a compiler to produceequivalent machine language code.In C compilation two parts are there namely 1) Compiler and 2) Linker.Compiler receives C source file as input and converts the file into object file. Then the linker receives
that object file as input and linking with C libraries after linking it produces executable file. After creation ofexecutable file then start the program execution and loads the information of the program in the primarymemory through loading process after loading the information the processor processing the information andgives the output.
BASIC STRUCTURE OF C PROGRAM
[Document Section]Pre-Processor section
OrLink Section.
[Global declaration section]Main(){
[Local declaration section]Statements
}[Sub programming section]
[User Defined function]
Document Section: It consist the set of comment lines. The document section consists the set of comment linesgiving the name of the program, author name and other details.
Link Section: It provides instructions to the compiler to link the functions from the system library.
Global Declaration Section: The variables that are used in more than one function are known as globalvariables and these variables are declared in the global declaration section.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
C source
program(.c)
Compiler Object file
(.obj)LINKER
Executable
File(.exe)
Start ProgramExecutionLOADING
Primarymemory(Ram)
C Libraries
Output
Processor
7/30/2019 C Language Full Notes
9/179
Main( ) Section: Every C program must have one main function this section consists two parts namely localdeclaration section and statement parts. The local declaration section declares all the variables used instatements. The statement part consist a sequence of executable instructions. These two parts must appearbetween the opening and closing curly braces. The program execution begins at the opening brace and end atthe closing brace.
Sub-Programming Section: This section consists all the user defined function.
Comments: Un executable lines in a program are called comments. These lines are skipped by the compiler.//-------------------------------- Single line comment
/*------------------------------*/ Group of lines comment
Pre-Processor statements:- The pre processor is a program that process the source code before it passesthrough the compiler.
#include: It is a pre processor file inclusion directive and is used to include header files it provides instructions
to the compiler to link the functions from the system library.Syntax: # include file name
Or#include
When the file name is included with in double quotation, the search for the file is made first the currentdirectory and then the standard directories or the file name is included within angular bases then the file issearched only in the standard directories.
Printf( ): It is a function and is used to print data on the screen.Syntax: int printf(control sting,[arg-1,arg-2,..arg-n]);
Or(format string)
The printf statement is used to print messages, the values contain in the variable on the screen.
stdio.h:- Standard input and output header file.conio.h:-Consol input and output header file.Example: printf(Welcome to C Programming);
Program:
#include#incudeVoid main(){
printf(Welcome to C Programming);}
clrscr():- It clears text mode window.Syntax:- void clrscr();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
10/179
getch():- It gets a character from console but does not echo to the screen.Syntax:- int getch();
Program:
#include
#inculdevoid main(){clrscr();printf(WELCOME TO C PROGRAMMING);getch();}
C TOKENS
The smallest individual units or elements in a program are called tokens. C has the following tokens1. Identifiers
2. Keywords3. Constants4. Operators5. Special characters.
1.Identifier:- Identifiers can be defined as name of the variables, arrays, functions and some other programelements using the combination of the following characters.Alphabets: A to Z
a to zDigits: 0 to 9Underscore: _ ( It is usually used as a link between two words in long
IdentifiersNote:- 1. The first character of an identifier will be an alphabet or underscore
2. The default identifier length is 32 characters.
2.Keywords:- Keywords are the words whose meaning has all ready been explained to the compiler. Thatmeans at the time of designing a language some words are reserved to do specific tasks. Such words are calledas keywords or reserve words. C has only 32 keywords. They are
Auto break case char Const Continue default externFloat Far for gotoif Int long register Return Short signed sizeof Static Struct switch typedef Union Unsigned void whileDo Double else enum
Constants: Constants in C referred to fixed values that do not change during the execution of program. Csupports the following constants.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
11/179
Constants
Numeric Constants Character constants
Integer constants, Real Constants Single Character Constants, String Constants
Operators:- It is a symbol which perform a particular operation. C has a rich set of operators.The following operators available in C are
1. Arithmetic Operator.2. Logical Operator.3. Relational Operator.
4. Bit-wise operator etc.,Special Characters:- All characters other than alphabet and digits are treated as special symbols.
DATA TYPES
The kind of data that variables may hold in a programming language is called data types. C data typescan be classified into three types namely..
Primary data types User defined data types
Derived data types
PRIMARY DATA TYPES OR PRIMITIVE DATA TYPES
All C compilers supports four fundamental data types namely int, char,, float, double).
int:- It is a positive, negative and the whole values but not a decimal number.Example: 10,50,-25,-153,0 etc.,
char:- A single character can be treated as character data type. It is defined between single quotation ()Example: a,H, *,8 etc.,
string:- A string is a group of characters. But in C language a string is also a character data type and is definedbetween ( ) double quotation.
Example: welcome, BDPS, abc123 etc.,
float:- The number which are stored in the form of floating point representation is known as float data type. (or)The value with decimal point./
Example: 11.53,153.2502,0.2345, etc.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
12/179
double:- The number which are stored in the form of double precision floating point representation is known asdouble data type.
Example: 15325.437897, -2427.09987, 0.45972
USER DEFINED DATA TYPES
The user defined data types enable a program to invent his own data types and define what values it cantaken on.
Thus this data types can help a programmer to reducing the programming errors. There are two types ofuser defined data types namely..1. enum (enumerated data type)2. typedef (type definition)
DERIVED DATA TYPES
The derived data types are created from the basic integers, characters and floating values. The examplesof derived data types are arrays, pointer, structures, unions, etc.,
Type Modifiers or Type Qualifiers
(signed, unsigned, short, long)
A type modifier alters the meaning of the base data type to yield a new type. Each of these modifierscan be applied to the base type int. The modifiers signed and unsigned can also be applied to the base type charIn addition, long can applied to double.
DATA TYPES, FORMAT SPECIFIERS, MEMORY SIZE AND THEIR ACCESS ABILITY RANGE
S.NO. Data type Format
specifies
Memory
size
Accessibility range
1. unsigned char %c 1 byte 0 to2552. Char %c 1byte 128 to 1273. Int %d 2 bytes -32768 to 327674. unsigned int %u 2bytes 0 to 65535
5. Long int or long %ld 4 bytes -2147483648 to2147483647
6. unsigned long %lu 4bytes 0 to 42949672957. float %f 4bytes 3.4*(10**-38) to
3.4*(10**+38) or[-3.4e38 to +3.4e38]
8. double %lf 8bytes 1.7*(10-308) to1.7*(10**+308) or
[1.7e308to+1.7e308]9. Long double %Lf 10 bytes 3.4*(10**-4932) to
1.1*(10**+4932)10. Char[ ] or string %s ---- -----
%x Hexa Decimal base %o Octal base %p Memory Address
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
13/179
Variables:- A quantity which may vary during the execution of a program is known as variable.
Declaration of a variable:- data type identifier;(or)
data type identifier-1, identifier-2,identifier-n;Examples: int n;char ch ;float f;int a,b,c;
Initialization:- At the time of declaring a variable we can store some data into that variable is known asinitialization.
data type identifier=value;Examples:- int n=10;
char ch=s;int a=10,b=20,c=30;
int a=100,b,c=150;Example:- int n=100;1.printf(%d,n); 2.printf(value of n=%d,n);
output=100 output:- value of n=100Program:
#include#includevoid main( ){int n=10;clrscr();printf(Value of n=%d,n);getch();}Program: Write a program to initialize 4 standard data type variables and display initial data.
#include#includeVoid main(){int n=100;char ch=h;float f=158.0962;double d=54932.2154;clrscr();printf(n=%d,n);printf(\n ch=%c,ch);printf(\n f=%f,f);printf(\n d=%lf,d);getch();}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
14/179
Note:
1. In C language all declarations will be done before the first execution of programs.2. Floating values displays 6 digits after the decimal point by defaultProgram:
#include
#includeVoid main(){float f=158.0962;clrscr();printf(f=%f,f);printf(\n f=%.2f,f);getch();}
Escape sequence characters
\n = new line \t = Horizontal tab (default 8 spaces)
\v = Vertical tab (default 1 line) \b = Back space\r = Carriage return \a = Alert (Beep sound)Program:
#include#inculdevoid main(){clrscr();printf(BDPS SOFTWARE LIMITED);printf(\nVIJAYAWADA);getch();}Constants:- Constants in C referred to fixed values that do not change during the execution of a program.
Const:- It is a keyword and is used to define constants.Syntax:- const data type identifier=value;
(or)Constdatatypeidentifier-1=value,identifier-2=value,identifier-n=value;
Program:
#include#inculdevoid main(){const int n=100;clrscr();printf(n=%d\n,n);/*n=200; cannot modify*/printf(n=%d,n);getch();}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Output:- n=100n=100
7/30/2019 C Language Full Notes
15/179
Symbolic Constants:- It is a pre-processor statement and is used to define symbolic constants.Syntax:- #define identifier value.Example:- #define pi 3.14
#define g 9.8Program
#include#inculde#define pi 3.14#define g 9.8{clrscr();printf(pi=%.2f,pi);printf(\n g=%.lf,g);getch();}scanf():- It is a function, which is used to read data from standard input device.
Syntax:- int scanf(format(s),address-1,address-2,.,address-n);Example:- int n ;
Address of n=&nscanf(%d,&n);
Program
#include#inculdevoid main(){int n;clrscr();prinf(Enter the value of n:);scanf(%d,&n);printf(Given value=%d,n);getch();}Program
#include#inculdevoid main(){char ch;int n;float f;double d;clrscr();prinf(Enter any charactaer:);scanf(%c,&ch);prinf(Enter any value:);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
16/179
scanf(%d,&n);prinf(Enter any float:);scanf(%f,&f);prinf(Enter any double:);scanf(%lf,&d);
printf(Given Characer=%c,ch);printf(Given value=%d,n);printf(Given float=%f,f);printf(Given double=%lf,d);getch();}
Program
#include#inculdevoid main()
{int n;char ch;clrscr();prinf(Enter any integer:);scanf(%d,&n);prinf(Enter any charactaer:);scanf(%c,&ch);printf(Given integer=%d,n);printf(Given Characer=%c,ch);getch();}
In the above program it cannot read character into a character variable, because the int reading statementcreates a new line char in the input stream that will assign to the character variable.
To avoid this problem we use fflush function (or) \n character
fflush:- It flushed specified streamSyntax:- int fflush (stream-name);Example:-fflush(stdin);
flushall:- It flushes all open streams.Syntax:- int flushall();
Program:
#include#inculdevoid main(){int n;char ch;clrscr();prinf(Enter any integer:);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
17/179
scanf(%d,&n);prinf(Enter any charactaer:);scanf(%c,&ch);fflush(stdin) or flushall ( );printf(Given integer=%d,n);
printf(Given Character=%c,ch);getch();}Program:
#include#inculdevoid main( ){int n;char ch;clrscr();
prinf(Enter any integer:);scanf(%d,&n);prinf(Enter any charactaer:);scanf(%\nc,&ch);printf(Given integer=%d,n);printf(Given Characer=%c,ch);getch();}String:- A group of characters define between double quotation marks is a string.
In C language a string is nothing but an array of characters and terminated by a null character (\0).Syntax:- char identifier[size];Example:- char st(20);
Initialization:- char identifier= string;Example:- char st[20]= WELCOME;
Note:- When the compiler assigns a character string to a character array it automatically supplies a nullcharacter(\0) at the end of the string.
Therefore the size should be equal to the maximum number of characters are string+1.Program
#include#includevoid main(){char st[20];clrscr();printf("Enter any string:");scanf("%s",st);printf("Given string:%s",st);getch();}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
18/179
Note:- scanf statement cant be blank spaces in keyboard into a string variable. If we want to read a string withblank spaces from keyboard into a string variable by the following technique.
Syntax:- scanf(%[^\n]s,st);
gets:- gets a string from stdin. It is a function which is used to read a string with blank spaces from keyboardwith a specified variable.Syntax:- char*gets(string variable);
Program
#include#includevoid main(){char st[20];clrscr();printf("Enter any string:");
gets(st); // scanf("%[^\ns",st);printf("Given string:%s",st);getch();}
OPERATORS
Definition:-It is a symbol which performs particular task. Ex:- +,-,*,etc....
Operand:- It is an entity which acts on operator.
Unary operators:- The operators consists only one operand are called unary operators.
Binary operators:- The operators consists two operands are called binary operators.C has rich set of operators. They are
1. Arithmetic operators2. Relational operators.3. Logical operators.4. Assignment operators.5. Bit-wise operators6. Increment and decrement operators7. Special operators
(i) ternary operator (or) Conditional operator(ii) comma operator.(iii) sizeof operator.
Arithmetical Operators:-These are the basic operators in C language. They are useful forperformingarithmetic calculations.
+ addition / division- subtraction % Modulus (remainder)* Multiplication
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
19/179
Program:-Write a program to accept any two numbers and test all arithmetic operators
#include#includevoid main(){
int a,b;clrscr();printf("Enter any Two numbers:");scanf("%d%d",&a,&b);printf("\nAddition of %d and %d is %d",a,b,a+b);printf("\nSubtraction of %d and %d is %d",a,b,a-b);printf("\nMultipliction of %d and %d is %d",a,b,a*b);printf("\nDivision of %d and %d is %d",a,b,a/b);printf("\nModulus of %d and %d is %d",a,b,a%b);getch();}
Logical operators:- These operators are used for combine the result of two or more expressions.&& Logical AND|| Logical OR ! Logical NOT
E1 E2 E1 && E2 E1 || E2
T T T TT F F TF T F TF F F F
If E1 = True then !E1= false If E1 = False then !E1 True
Relational operators:-These are used to test the relation between two values or two variablesor expressionsAll c relational operators are binary operators and hence requires two operands.
< less than> greater than= greater than or equal to
= = equal to!= not equal to
Assignment operators:- These are used to assign a value of an expression to an identifier.= Assignment operator.
Compound assignment operators (or) Short hand assignment operators:-+=, -=, *=, /=, %=Example:-int a=10;
a=a+20; (or) a+=20;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
20/179
Increment and Decrement operators:- These are used to control the loops in an effective method.
Increment operators:- The symbol '++' is used for incrementing by 1. Syntax:- ++identifier; (prefix increment)
identifier++; (postfix increment)
Example:- int a=10,b;b=a++ here o/p : a=11,b=10b=++a here o/p : a=11,b=11
Decrement operators:- The symbol '--' is used for decrementing by 1.Syntax:- --identifier; (prefix decrement)
identifier--; (postfix decrement)Example:- int a=10,b;
b=a-- here o/p : a=9,b=10b=--a here o/p : a=9,b=9
BIT-WISE operators:- These are used for manipulating data at bit level they are two types: 1. Bitwise logical operators. 2. Bitwise shift operators.
Bit wise logical operators:-These are used for the bitwise logical decision making.& bitwise AND| bitwise OR^ bitwise exclusive OR
E1 E2 E1 & E2 E1 | E2 E1 ^ E2
1 1 1 1 0
1 0 0 1 10 1 0 1 10 0 0 0 0
Program:
#include#includevoid main(){int a,b;clrscr();
printf("Enter any two values:");scanf("%d%d",&a,&b);printf("\na&b=%d",a&b);printf("\na|b=%d",a|b);printf("\na^b=%d",a^b);getch();}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
21/179
Bitwise shift operators:-The shift operators take binary patterns and shift the bits to the left or right.> - right shiftProgram:- To find b, c values using shift operators.
#include
#includevoid main(){int a=8,b,c;clrscr();b=a3;printf("\n a=%d", a);printf("\n b=%d", b);printf("\n c=%d", c);getch();
SPECIAL OPERATORS:a) Ternary operator (or) Condition operator:-A Ternary operator is represented as "?:" It is used toconstruct a conditional expression. The general form of ternary operator is exp1?exp2:exp3; here exp1 , exp2 ,exp3 are expressions.
If exp1 is true, then exp2 is evaluated and its value becomes the value of expression. If exp1 is false,then the exp3 is evaluated and its value becomes the value of the expression.
Program:- Write a program to find max and min of given two values by using ternary operaotrs#include#include Example: int a=10,b=20,c,d;void main() c=a>b?a:b;{ a=10, b=20 and c=20,d=10int a,b,max,min;clrscr();printf("Enter values for a,b:");scanf("%d%d",&a,&b);max=a>b ? a:b;min=a
7/30/2019 C Language Full Notes
22/179
void main() Therefore a=10, b=20 , c=30{ (first assigns the value 10 to a next assignsint a,b,c; the value 20 to b and finally assignsclrscr(); the value 30 to c)c=(a=10,b=20,a+b);
printf("a=%d",a);printf("\nb=%d",b);printf("\nc=%d",c);getch();}Program:
#include#includevoid main(){int a,b,c;
clrscr();c=(a=10,b=20,(a+b)*2);printf("\n a=%d",a);printf("\n b=%d",b);printf("\n c=%d",c);getch();}c) sizeof operator:- It is a compile name operator and is used to get the memory size of a variable , expressionand data type.
Syntax:- sizeof(variable(or)exp(or)datatype);Program:
#include#includevoid main(){char ch;int n;float ft;double db;clrscr();printf("\nSize of char:%d byte",sizeof (ch));printf("\nSize of int:%d byte",sizeof (n));printf("\nSize of float:%d byte",sizeof (ft));printf("\nSize of double:%d byte",sizeof (db));getch();}
Program:- Write a program to find maximum of given three values by using ternary operators.
#include#include
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
23/179
void main(){int a,b,c,max;clrscr();printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);max=(a>b&&a>c)?a:(b>c?b:c);printf("Maximum value=%d",max);getch();}
Program:-Write a program to find out the given value is even or Odd number by using ternary operators.#include#includevoid main(){
int a;clrscr();printf("Enter any number:");scanf("%d",&a);a%2= =0? printf("Given number is even"):printf("Given number is odd");getch();}
Program:- Write a program to accept any two values and swapping the given values#include#includevoid main(){int a,b,t;clrscr();printf("Enter any two values into a and b:");scanf("%d%d",&a,&b);printf("Given values before swapping:");printf("\na=%d",&a);printf("\nb=%d",&b);t=a;a=b;b=t;printf("After Swapping:");printf("\na=%d",&a);printf("\nb=%d",&b);getch();}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
24/179
Program:- Write same program without using third variable
#include#includevoid main(){
int a,b;clrscr();printf("Enter any two values into a and b:");scanf("%d%d",&a,&b);printf("Given values before swapping:");printf("\na=%d",&a);printf("\nb=%d",&b);/* AFTER SWAPPING*/a=a+b;b=a-b;a=a-b;
printf("After Swapping:");printf("\na=%d",&a);printf("\nb=%d",&b);getch();}
PRECIDIENCE OF OPERATORS
S.No Category Operator What it is or does
1 Highest ( )[ ]
Function callArray subscript
2 Unary !+
-++--&
sizeof
Logical negationUnary plus
Unary minusIncrement operatorDecrement operatorAddress(returning size ofoperand, in bytes)
3 Multiplicative */
%
MulitiplyDivisionRemainder(modulus)
4 Additive +
-
Binary Plus
Binary minus5 Shift >
Left shift operatorRight Shift operator
6 Relational =
LessthanLess than or equal toGreaterthanGreaterthan or equal to
7 Equality = = Equal to
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
25/179
!=&^|
&&
||
Not equal toBitwise AndBitwise Exclusive OrBitwise orLogical and
Logical or8 Conditional ?: Ternary operator 9 Assignment =
*=/+
%=+=-=
Simple AssignmentAssign ProductAssign QuotientAssignremainder(modulus)Assign sumAssign difference
10 Comma , Evaluate
CONTROL STATEMENTS(OR)
CONTROL STRUCTURES
C is consider as a structure programming language. One of the reason for this is having various programcontrol structures.
C process the decision making capabilities and supports the statements known as control statements.There are 3 types of control statements supported by C
1. Condition control statements2. Un condition control statements3. Loop control statements.
1. Condition control statements:- C supports five types of condition control statements. Simple if statement If else statement Nested if statement Else if ladder Switch statement
i) Simple if statement:- It is a decision making statements and is used to control the flow of execution.Syntax:-if(expression)
{Statements;
False }
True
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Entry
Statements
Next Statements
Expr.
7/30/2019 C Language Full Notes
26/179
If expression is true then the statement block will be executed and the statement block will be executedand the control transfer to the next statement. Otherwise the expression is false then the control directly go tothe next statement.
Program: Write a program to find max of two values by using simple if statement?#include#includevoid main(){int a,b,max;clrscr();printf("Enter any two numbers:");scanf("%d%d",&a,&b);max=a;
if(max
7/30/2019 C Language Full Notes
27/179
void main(){int d,m,y;clrscr();printf("Enter any date (dd-mm-yyyy):");
scanf("%d-%d-%d",&d,&m,&y);printf("Given date:%.2d-%.2d-%d",d,m,y);getch();}
Program: Write a program to enter current date and date of birth. Calculate and display
#include#includevoid main(){int d,m,y,cd,cm,cy,bd,bm,by;
clrscr();printf("Enter current date (dd-mm-yyyy):");scanf("%d-%d-%d",&cd,&cm,&cy);printf("Enter Birth date (dd-mm-yyyy):");scanf("%d-%d-%d",&bd,&bm,&by);y=cy-by;m=cm-bm;d=cd-bd;if(d
7/30/2019 C Language Full Notes
28/179
Entry
False True
If the expression is true then if block statements are executed and else block statements are ignored.Otherwise the expression is false, then else block statements are executed and if block statements are ignored.Program:
#include#includevoid main(){int a,b,max;clrscr();printf("Enter any two numbers:");scanf("%d%d",&a,&b);if(a
7/30/2019 C Language Full Notes
29/179
}
iii) Nested if statement:- Using a if statement within another if is called nested if statement. If a series ofdecisions are involved we use nested if statement.Syntax:- if(expression-1)
{If(expression-2){------------------------{Statements;}
}}
Syntax-2
if(expression-1){if(expression-2){statements-1;}else
{statements-2;}
}else{if(expression-3){statements-3;}
else{statements-4;}}
Program:Write a program to find the maximum value of given 3 no's using nested if.#include#includevoid main(){int a,b,c,max;clrscr();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
30/179
printf("Enter any three numbers:");scanf("%d%d%d",&a,&b,&c);if(a>b){if(a>c)
max=a;elsemax=c;}else{if(b>c)max=b;elsemax=c;}
printf("Max Value for given 3 numbers:%d",max);getch();}
Program:Write a program to accept any character and check whether the given character is alphabet or digitor a special character.#include#includevoid main(){char ch;clrscr();printf("Enter any character:");scanf("%c",&ch);if((ch>=65 && ch=97 && ch=48 && ch
7/30/2019 C Language Full Notes
31/179
clrscr();printf("Enter any character:");scanf("%c",&ch);if((ch>=65 && ch=97 && ch=50 && cpp>=50 && unix>=50){printf("\n Result :Pass");if(avg>=60)
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
32/179
printf("\n Division :First");elseprintf("\n Division :Second");}else
printf("\n Result :Fail");getch();}iv) else if ladder:- It is also used for a serried of decisions are involved.Syntax:-if(expression-1)
{stataement-1;
}else if (expression-2){
statements-2;
} ------------------------------------------
else if (expression-n){
statements-n;}else{
statements;}In this statement expression are evaluated top to bottom. If the condition true, the statements associated
that blocks is executed and the control transfer to the next statement. When all expressions are false, then thefinal else block statements will be executed.
Program: Write a program to find the maximum value of given 3 no's using nested if.
#include#includevoid main(){int a,b,c,max;clrscr();printf("Enter any three numbers:");scanf("%d%d%d",&a,&b,&c);if(a>b && a>c)max=a;
else if(b>c)max=b;
else
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
33/179
max=c;printf("Max Value for given 3 numbers:%d",max);getch();}
Program: Write a program to accept month and year. Calculate and disiplay number of days in the givenmonth
#include#includevoid main(){int m,y,nd;clrscr();printf("Enter any month number:");scanf("%d",&m);printf("Enter any year number:");
scanf("%d",&y);if(m==2){
if(y%4==0)nd=29;elsend=29;
}else if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)nd=31;elsend=30;printf("Number of days in the given month:%d",nd);getch();}
Program: Write a program to enter consumer number, name, present month reading and last month reading.Calculate and display total units and bill amount by the following table
Units Rate per Unit
0-50 Rs1.2551-100 Rs 2.10101-200 Rs 2.85201-400 Rs. 3.50Above 400 Rs.4.50
#include#includevoid main(){int cno,pmr,lmr,tu;char cname[20];
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
34/179
float bill;clrscr();printf("Enter consumer number:");scanf("%d",&cno);printf("Enter consumer name:");
fflush(stdin);gets(cname);printf("Enter pmr and lmr:");scanf("%d%d",&pmr,&lmr);tu=pmr-lmr;if (tu
7/30/2019 C Language Full Notes
35/179
void main(){
int dno,nps,nds,nks;char dname[20],dregion[20];float trgc,tcn,tcs,tce,tcw;
clrscr();printf("Enter dealer number:");scanf("%d",&dno);printf("Enter dealer name:");fflush(stdin);gets(dname);printf("Enter no of litres petrol sold:");scanf("%d",&nps);printf("Enter no of litres Kerosene sold:");scanf("%d",&nks);printf("Enter no of litres diesel sold:");
scanf("%d",&nds);tcn=nps*49.75+nds*32.65+nks*18.95;tcs=nps*49.25+nds*32.15+nks*18.25;tce=nps*48.95+nds*31.75+nks*17.50;tcw=nps*48.35+nds*30.85+nks*17.35;trgc=tcn+tce+tcs+tcw;clrscr();printf("\ntotal collection in north :%.2f",tcn);printf("\ntotal collection in east :%.2f",tce);printf("\ntotal collection in West :%.2f",tcw);printf("\ntotal collection in South :%.2f",tcs);printf("\ntotal region class :%.2f",trgc);getch();
}
II method:
#include#includevoid main(){
int dno,np,nd,nk;char dname[20],reg;float pa,da,ka,ta;clrscr();printf("Enter dealer number:");scanf("%d",&dno);printf("Enter dealer name:");fflush(stdin);gets(dname);printf("Enter dealer region:");
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
36/179
scanf("%c",®);if(reg!='N' && reg!='S' && reg!='W' && reg!='E'){
printf("Invalid region:");getch();
exit(0);}printf("Enter no of lts petrol sold:");scanf("%d",&np);printf("Enter no of lts diesel sold:");scanf("%d",&nd);printf("Enter no of lts kerosene sold:");scanf("%d",&nk);if (reg=='N'){
pa=np*49.75;
da=nd*32.65;ka=nk*18.95;}else if (reg=='S'){
pa=np*49.25;da=nd*32.15;ka=nk*18.25;
}else if (reg=='E'){
pa=np*48.95;da=nd*31.75;ka=nk*17.50;
}else{
pa=np*48.35;da=nd*30.85;ka=nk*17.35;
}ta=pa+da+ka;clrscr();printf("\n Dealer number :%d",dno);printf("\n Dealer name :%s",dname);printf("\n Dealer Region :%c",reg);printf("\n No of lts petrol sold :%d",np);printf("\n No of lts kerosene sold :%d",nk);printf("\n No of lts diesel sold :%d",nd);printf("\n Petrol amount :%.2f",pa);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
37/179
printf("\n Kerosene amount :%.2f",ka);printf("\n Desel sold :%.2f",da);printf("\n Total amount :%.2f",ta);getch();}
Program: Write a program to enter employee number, employee name, employee grade,basic salary. Calculateand display HRA, DA, TA, IT, PF, GROSS SALARY ANDNET SALARY by the following table.
----------------------------------------------------------------------------
Grade Baic HRA DA TA IT PF -----------------------------------------------------------------------------
A 2000 &4000 & 5000 14% 18% 5% 6% 8%-----------------------------------------------------------------------------
B =2000 & 40000 0% 14% 5% 3% 4%------------------------------------------------------------------------------
#include#include#includevoid main(){
int eno;char ename[20],gr;float bs, hra, da, ta,it,pf,ded,gs,ns;clrscr();printf("Enter Employee number:");scanf("%d",&eno);printf("Enter Employee name:");fflush(stdin);gets(ename);printf("Enter Employee Grade:");scanf("%c",&gr);if(gr!='A' && gr!='a' && gr!='B' && gr!='b'){
printf("Invalid grade");getch();exit(0);
}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
38/179
printf("Enter basic salary:");scanf("%f",&bs);if(gr=='A' || gr=='a'){
if(bs
7/30/2019 C Language Full Notes
39/179
}if(bs
7/30/2019 C Language Full Notes
40/179
----------------------Case value n;
Statements n;Break.;
Default;
Default statement;}The switch statement tests the value of the given variable or expression against a list of case values and
when a match is found, a block of statements associated that case is executed. Otherwise the default blockstatements will be executed.
Break:- It is unconditional control statement and is used to terminate a switch statement.Syntax :- break;
Note:- i) In switch statement the variable or expression is an integral value.(int & char).ii) It cannot pass string and floating values.
iii) In switch statement the default block is optional.Program: Write a program to test all arithmetic operations using switch statement#include#includevoid main(){int a,b,opt;clrscr();printf("Enter any two numbers:");scanf("%d%d",&a,&b);printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Enter Option");scanf("%d",&opt);switch(opt){
case1 :printf("\nAddition %d and %d is %d",a,b,a+b);break;
case2 :printf("\nSubtraction %d and %d is %d",a,b,a-b);break;
case3 :printf("\nMultiplication %d and %d is %d",a,b,a*b);break;
case4 :printf("\nDivision %d and %d is %d",a,b,a-b);break;
case5 :printf("\nModulus %d and %d is %d",a,b,a%b);break;
default :
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
41/179
printf("\nInvalid Region:");}getch();}
Program: Write a menu driven program to compute the electricity bill for the domestic and commercialpurposes with the following data.
For Domestic purpose:
units Rate/unit --------------------------
0-50 1.45
51-100 2.85
101-200 3.95201-300 4.50
201-300 5.00
--------------------------
extras: Rs.10/- Service charge and Rs.0.06 ps per unit power tax, Subject tominimum of Rs.10 single phase and Rs.20 for 3 phase
For Commercial purpose
units Rate/Unit
-----------------------------
0-100 3.95above 100 7.00
----------------------------
extras: Rs.20/- Service charge and Rs.0.06 ps per unit power tax, Subject tominimum of Rs.20 single phase and Rs.50 for 3 phase
#include#includevoid main(){
int cno, pmr,lmr,tu,ph;char cname[20],type;float bill,se, pt,tamt;clrscr();printf("\n\t\tMENU");printf("\n\t\t---------------");printf("\n\t\tCOMMERCIAL(C\c)");printf("\n\t\tDOMESTIC(D/d)");printf("\n\t\t---------------");printf("\n\t\tEnter your option:");scanf("%c",&type);if(type!='C' && type!='c' && type!='D' && type!='d'){
printf("\n\t\tInvalid Type:");getch();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
42/179
exit(0);}printf("\n\tEnter phase type (1 or 3):");scanf("%d",&ph);if(ph!=1 && ph!=3)
{ printf("\n\t Invalid phase");getch();exit(0);
}clrscr();printf("Enter consumer number:");scanf("%d",&cno);printf("Enter consumer name:");fflush(stdin);gets(cname);
printf("Enter pmr and lmr:");scanf("%d%d",&pmr,&lmr);tu=pmr-lmr;switch(type){
case 'd':case 'D':
if(tu
7/30/2019 C Language Full Notes
43/179
case 'c':case 'C':
if(tu
7/30/2019 C Language Full Notes
44/179
3. Goto:- The goto statement is an unconditional control statement which is used up the execution of programsequence by transfer of control to the some other part of the program.
Syntax:- goto label;Where label is C valid identifier used to the label of the destination such that the control could
transferred label. Syntax:- identifier;
Program: Write a program to display natural numbers from one to given natural numbers using gotostatement.
#include#includeint n,i=1;clrscr();printf(Enter any number:);scanf(%d,&n);lb:
printf(Natural numbers from 1 to %d,n);printf(%d\t,i);
i++;if(i
7/30/2019 C Language Full Notes
45/179
Program:
#include#inculdevoid main(){
clrscr();gotoxy(70,25);printf(WELCOME);getch();}Program:
#include#includevoid main(){
int sno,c,cpp,java,tot,sc=23,ec=57,i;
char sname[20],ch;float avg;_setcursortype(2);do{
clrscr();gotoxy(24,5);printf("---------------------------------");gotoxy(30,6);printf("BDPS SOFTWARE LIMITED");gotoxy(35,7);printf("VIJAYAWADA");gotoxy(24,8);printf("---------------------------------");gotoxy(23,5);printf("%c",'');gotoxy(57,5);printf("%c",'');gotoxy(57,22);printf("%c",'');gotoxy(23,22);printf("%c",'');for(i=6;i
7/30/2019 C Language Full Notes
46/179
printf("%c",'');}gotoxy(24,9);printf("SNO :"); //31gotoxy(24,11);
printf("SNAME :");gotoxy(24,13);printf("MARKS IN C :"); // 39gotoxy(24,15);printf("MARKS IN CPP :");gotoxy(24,17);printf("MARKS IN JAVA :");gotoxy(33,19);printf("TOTAL :");gotoxy(33,21);printf("AVERAGE :");
gotoxy(24,22);printf("---------------------------------");gotoxy(32,9);scanf("%d",&sno);gotoxy(32,11);fflush(stdin);gets(sname);gotoxy(45,13);scanf("%d",&c);gotoxy(45,15);scanf("%d",&cpp);gotoxy(45,17);scanf("%d",&java);tot = c + cpp + java;avg = (float) tot/3;gotoxy(45,19);printf("%d",tot);gotoxy(45,21);printf("%.2f",avg);gotoxy(24,23);printf("Do you enter another record(y/n):");fflush(stdin);scanf("%c",&ch);
}while(ch!='n');}
LOOP CONTROL STATEMENTS
Loop:- The process of repeated executing a block of statements is called loop. C supports three types of loopingstatements. They are
While Loop do-while loop and
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
47/179
for-loopAny loop has three things. They are
1. Initialize the index2. Test condition3. Update the index
1. while loop:- It is a conditional control loop statement in C language.Syntax:- while(test condition)
{Statements;}
First the test condition is evaluated and if it is true then the statement block will be executed. After theexecution of statements the test condition is evaluated once again.Then if it is true the statement block will be executed continuous until the test condition finally becomes false.
Program: Write a program to display natural numbers from 1 to given number using
'While Loop'#include#includevoid main(){
int n,i=1;clrscr();printf("Enter no of elements:");scanf("%d",&n);printf("Natural Numbers from 1 to %d:\n",n);while (i
7/30/2019 C Language Full Notes
48/179
i++;}if(count==2)printf("Given no is prime");else
printf("Given no is not prime");getch();}
Program: Write a program to accept any number and display reverse number(image no)#include#includevoid main(){
int n;unsigned long rev=0;clrscr();
printf("Enter any number:");scanf("%d",&n);while(n>0){
rev=rev*10+(n%10);n=n/10;
}printf("Reverse number=%lu",rev);getch();
}Program: Write a program to accept any number and check whether the given number is palindrome number
#include#includevoid main(){
int n,m,rev=0;clrscr();printf("Enter any number:");scanf("%d",&n);m=n;while(m>0){
rev=rev*10+(m%10);m=m/10;
}if(n==rev)printf("Given number is Palindrome");elseprintf("Given number is not Palindrome");getch();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
49/179
}Program: Write a program to accept any number and display sum of digits in the given number#include#includevoid main()
{ unsigned long n;int sum=0;clrscr();printf("Enter any number:");scanf("%lu",&n);while(n>0){
sum=sum+(n%10);n=n/10; //n=1234,n>0,
} // sum=9+1,s=10,n=0
printf("Sum of digits in the given number:%d",sum);getch();}Program:
#include#includevoid main(){
int n,i=1;clrscr();printf("Enter any number:");scanf("%d",&n);printf("Factors of %d:",n);while(i
7/30/2019 C Language Full Notes
50/179
scanf("%d",&n);printf("Factorial of %d is %lu:",n,f);while (i
7/30/2019 C Language Full Notes
51/179
while(n>0){nd++;n=n/10;}
printf("No of digits in the given number is %d",nd);getch();}
Program:
#include#includevoid main(){
int i=0;clrscr();
while(i0){
r=m%10;sum=sum+(r*r*r);m=m/10;
}if(n==sum)printf("Given number is Armstrong");elseprintf("Given number is not Armstrong");
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
52/179
getch();}Program: Write a program to display even and odd no of 1 to given number using continue statement#include#include
void main(){int n,i=0;clrscr();printf("Enter any number:");scanf("%d",&n);printf("Even number from 1 to %d:\n",n);while(i
7/30/2019 C Language Full Notes
53/179
getch();}Program: Write a program to accept any two numbers calculate and display L.C.M of given two number#include#include
void main(){int a,b,lcm;clrscr();printf("Enter any two numbers:");scanf("%d%d",&a,&b);lcm=a>b?a:b;while(1){
if(lcm%a==0 && lcm%b==0)break;
lcm++;}printf("lcm of %d and %d is %d",lcm);getch();
}Program: Method 1#include#includevoid main(){
unsigned long n;int sum=0;clrscr();printf("Enter any number:");scanf("%lu",&n);while(n>0){
sum=sum+(n%10);n=n/10;if(n==0){if(sum>9){
printf("%d\n",sum);n=sum;sum=0;
}}
}printf("Final sum is:%d",sum);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
54/179
getch();}Method-2
#include#include
void main(){unsigned long n;int sum=0;clrscr();printf("Enter any number:");scanf("%d",&n);sum=n%9;if(sum==0)printf("Sum is %d",9);else
printf("Sum is %d",sum);getch();}Program: Write a program to accept any decimal number and displays binary number
#include#includevoid main(){
int n;unsigned long bin=0,b=1;clrscr();printf("Enter any number:");scanf("%d",&n);while(n>0){
bin=bin+(n%2)*b;n=n/2;b=b*10;
}printf("Binary number of given decimal number:%lu",bin);getch();
}Program: Write a program to accept any binary number and display decimal number
#include#includevoid main(){
int n=0,b=1,r;unsigned long bia;clrscr();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
55/179
printf("Enter any binary number:");scanf("%lu",&bia);while(bia>0){
r=bia%10;
if(r!=1 && r!=0){printf("Invalid binary number:");getch();exit(0);
}n=n+r*b;bia=bia/10;b=b*2;
}printf("Decimal number of given binary number :%d",n);
getch();}2. do-while loop:- It is an alternative form of while loop. The only difference between while and do while isthe minimum number of execution of while is 0. For minimum no of execution of do-while is 1.
Syntax:- do{Statements;}While(test condition);
Flowchart
First the statement block will be executed and then test condition will be evaluated. If the condition istrue then the statement block will be executed once again. This process of repeated executed continuous untithe test condition finally becomes falseProgram: Write a program to accept and display natural numbers, from one to given number using do-while
loop
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Entry
True
Statements
Testconditon
Next Statements
7/30/2019 C Language Full Notes
56/179
#include#includevoid main(){
int n,i=1;
clrscr();printf("Enter any number:");scanf("%d",&n);printf("Natural numbers form 1 to %d:\n",n);do{
printf("%d\t",i);i++;
}while(i
7/30/2019 C Language Full Notes
57/179
#include#includevoid main(){
int n,sum=0,i;
clrscr();printf("Enter any number:");scanf("%d",&n);for(i=1;i
7/30/2019 C Language Full Notes
58/179
{rev=rev*10+(m%10);m=m/10;
}if(rev==i)
printf("%d\t",i);}getch();
}Program: Write a program to display prime numbers from 1 to given numbers
#include#includevoid main(){
int n,i,j,c;clrscr();
printf("Enter any number:");scanf("%d",&n);printf("Prime Numbers from 1 to %d:",n);for(i=1;i
7/30/2019 C Language Full Notes
59/179
{if(i%j==0)sum=sum+j;
}if(sum==i)
printf("%d\t",i);}getch();
}Program: Write a program to display Armstrong numbers from 1 to given numbers.
#include#includevoid main(){
int n,m,i,r,sum;clrscr();
printf("Enter any number:");scanf("%d",&n);printf("Armstrong numbers from 1 to %d:",n);for(i=1;i0){
r=m%10;sum=sum+(r*r*r);m=m/10;
}if(sum==i)printf("%d\t",i);
}getch();
}Program:Write a program to accept any number calculate and display square root of a given number withoutusing library functions.#include#includevoid main(){
int n,i;float j;clrscr();printf("Enter any number:");scanf("%d",&n);i=1;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
60/179
while(i*i < n){
i++;}if(i*i == n)
printf("Square root of given number is %d",i);else{
j=i-1;while(j*j0){
for(i=1;i
7/30/2019 C Language Full Notes
61/179
Int n=100;
Printf(%d,n) or printf(%5d,n); or printf(%-6d,n);
o/p:100 o/p:--100 (2spaces) o/p:100--- (3 spaces)Char:-
Char ch=H;Printf(%c,ch); printf(%3c,ch); printf(%-5c,ch);
o/p:H o/p:--H (2spaces) o/p: H---- (4 spaces)
Float:-
float ft=123.734;
Printf(%f,ft); printf(%12f,ft); printf(%.2f,ft);o/p:123.734000 o/p:--123.734000 (2spaces) o/p: 123.73
printf(%8.2f,ft); o/p:--123.73
String:-
string st= WELCOME;
printf(%s,st); printf(%9s,st); printf(%.3s,st);o/pWELCOME o/p--WELCOME(2spaces) o/pWEL
int n=3pirntf(%.*s,n,st);o/p:WEL
Program: Write a program to generate the following pattern WWEWELWELCWELCOWELCOMWELCOME
#include#includevoid main(){
char st[10]="WELCOME";int i;clrscr();for(i=1;i
7/30/2019 C Language Full Notes
62/179
}Program:
#include#includevoid main()
{ int n,i;clrscr();printf("Enter any number:");scanf("%d",&n);for(i=1;i
7/30/2019 C Language Full Notes
63/179
r=1;}}getch();
}
Program: Write a program to generate the following pattern * * * * ** * * * ** * * * ** * * * *
#include * * * * *#includevoid main(){int n,i,j;clrscr();printf("Enter any number:");
scanf("%d",&n);for(i=1;i
7/30/2019 C Language Full Notes
64/179
printf("\n\n");}getch();
}Program: Write a program to generate there following pattern
112123123412345#include#includevoid main(){
int n,i,j;clrscr();
printf("Enter any number:");scanf("%d",&n);for(i=1;i
7/30/2019 C Language Full Notes
65/179
for(j=1;j
7/30/2019 C Language Full Notes
66/179
}Program:
#include#include
void main(){int n,m,i,j,k,s=2;clrscr();printf("Enter any number into n:");scanf("%d",&n);clrscr();for(i=n;i>=1;i--){
k=i;printf("%*c",s,32);
for(j=1;j
7/30/2019 C Language Full Notes
67/179
if(i%2==0)k--;else
}
}}}Program:
#include#includevoid main(){
int n,m,i,j,k,s;clrscr();printf("Enter any value into n:");
scanf("%d",&n);s=2*n;m=1;for(i=1;i
7/30/2019 C Language Full Notes
68/179
k--;elsek++;
}printf("\n");
if(i
7/30/2019 C Language Full Notes
69/179
}else{
x++;y--;
}}}getch();
}
Program:
#include#includevoid main()
{ int i,j,p,x=7,y=7;clrscr();for(i=1;i=x && j
7/30/2019 C Language Full Notes
70/179
Text Background:- It selects a new text background color.Declaration:-void textbackground(int newcolor);
Color(text mode)
S.no
.
Constant Value Background Fore ground
1 BLACK 0 YES YES2 BLUE 1 YES YES3 GREEN 2 YES YES4 CYAN 3 YES YES5 RED 4 YES YES6 MAGENTA 5 YES YES7 BROWN 6 YES YES8 LIGHT GRAY 7 YES YES9 DARK GRAY 8 NO YES
10 LIGHT BLUE 9 NO YES
11 LIGHT GREEN 10 NO YES12 LIGHT CYAN 11 NO YES13 LIGHT RED 12 NO YES14 LIGHT MAGENTA 13 NO YES15 YELLOW 14 NO YES16 WHITE 15 NO YES17 BLINK 128 NO ***
*** To display blinking characters in text mode, add BLINK to the foreground color.
Textmode():-It Changes screen mode (in text mode)
Declaration: void textmode(int newmode);
Constant ValueText Mode
LASTMODE -1 Previous text modeBW40 0 Black and white 40 columnsC40 1 Color 40 columnsBW80 2 Black and white 80 columnsC80 3 Color 80 columnsMONO 7 Monochrome 80 columnsC4350 64 EGA and 43-lineVGA 50-line
cprintf:- It is same as printf if you want to display colors in text mode we use cprintf.Program:
#include#includevoid main(){
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
71/179
clrscr();textmode(1);textcolor(RED+BLINK);textbackground(WHITE);gotoxy(16,12);
cprintf("WELCOME");getch();}
Delay: Suspends execution for interval (milli seconds)Declaration: void delay (unsigned milliseconds);
kbhit:- It checks for currently available keystrokes.Declaration: int kbhit();
DIGITAL CLOCK
#include
#include#includevoid main(){
int h,m,s;clrscr();printf("Enter any time(hh:mm:ss):");scanf("%d:%d:%d",&h,&m,&s);textmode(0);textcolor(RED);_setcursortype(_NOCURSOR);while(!kbhit()){clrscr();gotoxy(15,12); cprintf("%.2d:%.2d:%.2d",h,m,s);delay(100);s++;if(s>59){m++;s=1;}if(m>59){h++;m=0;}if(h>12)h=1;}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
72/179
}
Program:
#include#include
#includevoid main(){
int c=1,c1=75,r=1;textmode(2);_setcursortype(0);textcolor(RED);while(!kbhit()){
clrscr();gotoxy(37,r);
cprintf("LOVES");gotoxy(c,12);cprintf("PRIYA");gotoxy(c1,12);cprintf("MADHU");c=c+2;c1=c1-2;r=r+1;if(c>75){
c=1;c1=75;
}if(r>25)r=1;delay(80);
}}Program: Write a program to get the following output#include#includevoid main(){
int n,i,j;clrscr();printf("Enter any value:");scanf("%d",&n);for(i=1;i
7/30/2019 C Language Full Notes
73/179
{printf("%3c",'*');
}printf("\n");
}
getch();}Program: Write a program to generate the following pattern#include#includevoid main(){int n,i,j;clrscr();printf("Enter any number:");scanf("%d",&n);
for(i=1;i
7/30/2019 C Language Full Notes
74/179
Function:- It is a self contained block of statements and it can be used at several multiple times in a programbut defined only once.
Library function or Predefined functions:- The functions which are in built with the C-compiler is called as
library functions. Ex:- printf, scanf, getch(), clrscr(); etc.,
User defined function:- User can defined functions to do a task relevant to their programs. Such functions arecalled as user defined functions.
Any function has three things. They are1. Function declaration2. Function definition3. Function calling.
In case ofpre-defined functions thefunction declaration is in header files, definition is in C Libraries
and callingis in yoursource program.
But in case ofuser defined functions all the three things are in yoursource program.
Function declaration:-
Syntax:- Returntype func_name([Arg List]);Example:-Void test();
Int sum(int , int );
Function definition:-
Syntax:- returntype func_name([Arg List]){Body;}
Function calling:-
Syntax:- func_name([Arg List]);
The arguments which we given at the time offunction declaration or definition are called arguments orformal arguments.
The arguments which are given at the time of function calling are called actual arguments orparameters.
void:- (Empty data type)#include#includevoid main(){void test( ); /*declaration*/clrscr();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
75/179
test( ); /*calling*/getch();
}void test() /*definition*/{
printf(welcome to c functions:);}
Rules for creating and accessing user defined functions:-
1. A function can be called by any number of times.2. A function may or may not receive arguments.3. A function may or may not return a value.4. If a function does not return any value the function return data type will be specified as void5. If a function returns a value only one value can be returned.6. We cannot specify any return data type, the function returns on integer value by default.7. The returning value must be return with a statement return.
8. If a function returns a value, the execution of return statement should be last9. If a function returns a value, the returning value should match with the function return data type.10. A function is executed when a function is call by its name.11. Before a function call, function declaration or definition must and should12. A function definition may be placed before or after the main function.13. If a function call, function definition can be specified any where in the program14. If a function definition is specified before the function called then the function declaration is not
necessary.15. The function definition should not be terminated with semicolon( ; )
Return:- Exits immediately from the currently execution of function to the calling rotated optionally returninga value.
Syntax:- return [];Program:
#include#includevoid main(){int sum(int,int);int a,b,n;clrscr();printf("Enter any two values:");scanf("%d%d",&a,&b);n=sum(a,b);printf("Sum is %d",n);getch();}int sum(int x,int y){
return x+y;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
76/179
}
Function Prototypes and category of functions:
A Function depending and whether arguments are present or not and a value is returned or not, may
belong to one of the following categories.Category 1: Function with no arguments and no return valueCategory 2: Function with arguments and no return valueCategory 3: Function with arguments and return value.Category 4: Function with no arguments and return value.1. Function with no arguments and no return value:- When a function has no arguments it does not receiveany data from the calling function. Similarly when it does not return a value the calling function does notreceive any data from the called function. In affect there is no data transfer between the calling function and thecalled function.Program:
#include#includevoid main(){void sum(); /*declaration;*/clrscr();sum(); /*calling;*/getch();}void sum() /* definition*/{
int a,b;printf("Enter any two values:");scanf("%d%d",&a,&b);printf("Sum is %d\n",a+b);
}
2.Function with arguments and no return value:- In this type the function has some arguments, it receive datafrom the calling function but it does not return any value. The calling function does not receive data from thecalled function. So there is one way data communication calling function and the called function.
Program:
#include#includevoid main(){void sum(int, int); /*declaration;*/int a,b;clrscr();printf("Enter any two values:");
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
77/179
scanf("%d%d",&a,&b);sum(a,b); /*calling;*/getch();}void sum(int x, int y) /* definition*/
{printf("Sum is %d\n",x+y);
}
3.Function with arguments and return value:- In this type the function has some arguments. It receives datafrom the calling function. Similarly it returns a value. The calling function receive data from the calledfunction. So it is a two way data communication between the calling function and the called function.Program:
#include#include
void main(){int sum(int,int);int a,b,n;clrscr();printf("Enter any two values:");scanf("%d%d",&a,&b);n=sum(a,b);printf("Sum is %d",n);getch();}int sum(int x,int y){
return x+y;}
4. Function with no arguments and return value:- In this type the function has no arguments. It does notreceive data from the calling function. But it returns a value the calling function receive data from the calledfunction. So it is a one way data communication between called function and the calling function.Program:
#include#includevoid main(){int sum(); /*declaration;*/int s;clrscr();s=sum(); /*calling;*/printf("Sum is %d",s);getch();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
78/179
}int sum() /* definition*/{
int a,b;printf("Enter any two values:");
scanf("%d%d",&a,&b);return a+b;}
Program: Write a program to display natural numbers from one to given number by using user defined
functions
#include#includevoid main(){void disp(int);
int n;clrscr();printf("Enter any number:");scanf("%d",&n);disp(n);getch();}void disp(int x){int i;for(i=1;i
7/30/2019 C Language Full Notes
79/179
{if(x%i==0)printf("%d\t",i);}}
Program: Write a program to calculate and display reverse number of given number.#include#includevoid main(){unsigned long revnum(int);int n;unsigned long r;clrscr();printf("Enter any number:");scanf("%d",&n);
r=revnum(n);printf("reverse number is:%lu",r);getch();}unsigned long revnum(int x)while(x>0){rev=rev*10+(x%10);x=x/10;}return rev;
}
Program: Write a program to calculate factorial of given number
#include#includevoid main(){unsigned long fact(int);int n;unsigned long f;clrscr();printf("Enter any number:");scanf("%d",&n);f=fact(n);printf("Factorial of given number:%lu",f);getch();}unsigned long fact(int x){
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
80/179
unsigned long f=1;while(x>=1){f=f*x;x--;
}return f;}
Program: Write a program to accept any number and display sum of natural numbers using user defined
function
#include#includevoid main(){void sum(int);
int n;unsigned long f;clrscr();printf("Enter any number:");scanf("%d",&n);sum(n);getch();}void sum(int x){int i=0,sum=0;while(i
7/30/2019 C Language Full Notes
81/179
{int n,t,t1=0,t2=1,i;clrscr();printf("Enter no of terms:");scanf("%d",&n);
printf("Fibonacci series:");printf("%d\t%d",t1,t2);for(i=1;i
7/30/2019 C Language Full Notes
82/179
printf("\n b=%d",b);getch();}
2. Static Variables:- The memory of static variables remains unchanged until the end of the program.
Storage Main MemoryDefault value ZeroScope Local to the block in which it is defined.Life A Value of static variable consists between different
function calls. (No Changes). That means it cannot realized between differentfunction calls.
Keyword static
Program:
#include
#includevoid main(){static int a,b;clrscr();printf("\n a=%d",a);printf("\n b=%d",b);getch();}
3. External Variables or Global Variables:- The variables both alive and active throughout entire
program is known as external variable.Storage Main MemoryDefault value ZeroScope globalLife as long as the program execution does not come to
endKeyword extern
Program:1
#include#include
int a,b;void main(){clrscr();printf("\n a=%d",a);printf("\n b=%d",b);getch();}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
83/179
Program:2
#include#includeint a=100;
void main(){extern int a;clrscr();printf("\n a=%d",a);getch();}
4. Register Variables:- We can use register variables for frequently used variables the fast execution of aprogram. These variables are declared inside the function block.
Storage
CPU, RegisterDefault value garbage valueScope local to the block in which it is definedLife the control remains within the block in which it is definedKeyword Register
Program:
#include#includevoid main()
{register int a,b;clrscr();printf("\n a=%d",a);printf("\n b=%d",b);getch();}
Note:- If there is no storage classes specifier before the function declaration of variables inside the functionblock by default it takes auto storage class.
Recursive function:- Calling a function with the same name function definition is known as recursive function
If you want to work with recursive function we must follow two conditions.
1. Calling itself2. Termination condition
Program: Write a program to display natural numbers from 1 to given number using recursive function#include#includevoid main()
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
84/179
{void disp(int);int n;clrscr();printf("Enter any number:");
scanf("%d",&n);disp(n);getch();}void disp(int x){if(x>1)disp(x-1);printf("%d\t",x);}
Program: Write a program to display natural numbers from one to given number using recursive functioncalling main with in main.#include#includevoid main(){
Static int i=1;n;If(i==1){
Clrscr();Printf(Enter any number:);Scanf(%d,&n);Printf(Natural numbers from 1 to %d:,n);
}Printf(%d\t,i);i++;if(i
7/30/2019 C Language Full Notes
85/179
clrscr();printf("Enter any number:");scanf("%d",&n);f=fact(n);printf("Factorial is:%lu",f);
getch();}unsigned long fact(int x){if(x0)revnum(x);return rev;}
MATH.H FUNCTIONS
abs():- abs (a macro) gets the absolute value of an integerSyntax:- int abs(int x);
Program:
#include#include#includevoid main()
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
86/179
{int n,a;clrscr();printf("Enter any two numbers:");scanf("%d",&n);
a=abs(n);printf("Absolute value:%d",a);getch();
}sqrt():-It calculates the square root of the given number.
Syntax:- double sqrt(double x);Program:
#include#include#includevoid main()
{ int n;double s;clrscr();printf("Enter any number:");scanf("%d",&n);s=sqrt(n);printf("Square root of given number:%.2lf",s);getch();
}pow():- It calculates the exponential value of given base and power.
Syntax:- double pow(double x, double y);Program:
#include#include#includevoid main(){
int b,p;double e;clrscr();printf("Enter any two value into b and p is:");scanf("%d%d",&b,&p);e=pow(b,p);printf("Exponential value of %d and %d is %.2lf",b,p,e);getch();
}floor():- It rounds down the given value. Syntax:- double floor(double x);ceil():- It rounds up the given value. Syntax:- double ceil(double x);Program:
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
87/179
#include#include#includevoid main(){
double n,ce,fl;clrscr();printf("Enter any value:");scanf("%lf",&n);ce=ceil(n);fl=floor(n);printf("\nCeil value:%.2lf",ce);printf("\nFloor value:%.2lf",fl);getch();
}Program:-
#include#include#includevoid main(){
int a,b,c,d,max,min;clrscr();printf("Enter any two values:");scanf("%d%d",&a,&b);c=a+b;d=abs(a-b);max=(c+d)/2;min=(c-d)/2;printf("\nMaximum value:%d",max);printf("\nMinimum value:%d",min);getch();
}Program: Write a program to calculate and display area of triangle with the given three sides
Note:-Any two angles greater than equal to third angleNot form:- 3,4,7 because 3+4=7
#include#include#include#includevoid main(){
float a,b,c,s,area;clrscr();printf("Enter three sides of triangle:");scanf("%f%f%f",&a,&b,&c);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
88/179
if((a+b)
7/30/2019 C Language Full Notes
89/179
{sum=sum+(float)1/i; //type casting
}printf("Sum = %.2f",sum);getch();
}Program:Write a program to compute the following exponential seriescpower of x=1+1/x+xsquare/2!+xqube/3!+---+xpowerof n/n!
#include#include#includeunsigned long fact(int x){
if(x
7/30/2019 C Language Full Notes
90/179
float sum=0;clrscr();printf("Enter x and n values:");scanf("%d%d",&x,&n);for(i=1;i=1)return 1;
elsereturn x*fact(x-1);
}void main(){
int i,n,x,p=0;float sum=0;clrscr();printf("Enter n & p values:");scanf("%d%d",&n,&p);for(i=1;i
7/30/2019 C Language Full Notes
91/179
ARRAYS
Definition:-A group of data items (variables) of same data types stored in a continuous memory location isknown as arrays.
That means a group of related data items that shape location name that particular is indicated or
subscript in square braces [ ] or array name. C Supports 3 types of arrays. They are1. Single Dimension arrays or One dimensional2. Double Dimension arrays or Two dimensional3. Multidimensional arrays
1. Single Dimensional array: A group of items can be given one variable name using only index such as avariable is known as single dimensional array. Single dimensional arrays the elements are represented one ortwo index of memory bytes.Declaration: datatype arr_name[size];
Example: int a[5];
Elements: a[0], a[1], a[2], a[3], a[4] In any array the array index is 0 to (n-1).Initialization: [Form1]
Datatype arr_name[size]={value 1, value 2,. Value b} Here size is optional
Example: int a[5]={1,2,3,4,5};Int a[ ]={100,200,300,400};
Program: Write a program to initialize single dimensional array elements
#include#includeVoid main(){int a[5]={1,2,3,4,5};int i;clrscr();for(i=0;i
7/30/2019 C Language Full Notes
92/179
scanf("%d",&n);if(n>20){printf("Array index out of bonds");getch();
exit(0);}for(i=0;i
7/30/2019 C Language Full Notes
93/179
{int a[20],n,rev,i;clrscr();printf("Enter no.of elements:");scanf("%d",&n);
printf("Enter array elements:");for(i=0;i=0;i--){
printf("%d\t",a[i]);}getch();
}Program:- Write a program to accept a single dimensional integer array and search specify elements in thegiven array.
#include#includevoid main(){
int a[20],n,i,se,ck=0;clrscr();printf("Enter no.of elements:");scanf("%d",&n);for(i=0;i
7/30/2019 C Language Full Notes
94/179
getch();}Program:-Write a program to accept a single dimensional integer array and display array elements inascending order
#include
#includevoid main(){
int a[20],n,i,j,t;clrscr();printf("Enter no.of elements:");scanf("%d",&n);printf("\nEnter array elements:");for(i=0;i
7/30/2019 C Language Full Notes
95/179
#includevoid main(){
int a[20],n,i,j,de,ck=0;clrscr();
printf("Enter no.of elements:");scanf("%d",&n);printf("Enter array elements\n");for(i=0;i
7/30/2019 C Language Full Notes
96/179
Program:Write a program to accept a single dimensional array and insert an element in the given array at aspecified position#include#includevoid main()
{ int a[20],n,i,ie,pos,t;clrscr();printf("Enter no.of elemens:");scanf("%d",&n);printf("Enter array elements:");for(i=0;i
7/30/2019 C Language Full Notes
97/179
printf("\n Given elements after insertion:");for(i=0;i
7/30/2019 C Language Full Notes
98/179
for(i=0;i
7/30/2019 C Language Full Notes
99/179
for(i=0;i
7/30/2019 C Language Full Notes
100/179
{c[id]=a[i];id++;
}}
}return id;}int un_arr(int a[],int b[],int d[],int m,int n){
int i=0,j=0,k=0;while(i
7/30/2019 C Language Full Notes
101/179
2. Two dimensional arrays :- A two dimensional array can store a table of values which contains rows andcolumns . In two dimensional arrays we use two index values. One forrows and another for columns.Declaration:- data type arr_name[row_size][col_size];Example:- int a[2][3];
here elements:- a[0][0] a[0][1] a[0][2]a[1][0] a[1][1] a[1][2]
Initialization :-
Form:1 datatype arr_name[rowsize][colsize]={val-1,val-2,.........,val-n};Example:- int a[2][3]={1,2,3,4,5,6};
Form:2: datatype arr_name[rowsize][colsize]={ {val-1,val-2,......},{val-1,val-2,...val-n},{val-1,val-2,....val-n}...........};
Example:- int a[2][3]={ {1,3,4},{2,3,4} };
Program:Write a program to initialize a two dimensional integer array and display arrayelements.#include#includevoid main(){
int a[3][3]={1,2,3,4,5,6,7,8,9};//int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};int i,j;clrscr();for(i=0;i20)
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
102/179
{printf("\nInvalid size");getch();exit(0);
}
for(i=0;i
7/30/2019 C Language Full Notes
103/179
scanf("%d",&a[i][j]);}
}printf("\n given elements\n");for(i=0;i
7/30/2019 C Language Full Notes
104/179
int i,j;for(i=0;i
7/30/2019 C Language Full Notes
105/179
for(i=0;i
7/30/2019 C Language Full Notes
106/179
printf("\nSecond matrix:\n");disp(b,r,c);add_matrix(a,b,add,r,c);printf("\nAddition of given two matrix:\n");disp(add,r,c);
getch();}void accept(int x[][20],int m,int n){
int i,j;for(i=0;i
7/30/2019 C Language Full Notes
107/179
void accept(int [][20],int,int);void disp(int [][20],int,int);void mul_mat(int [][20],int [][20],int [][20],int,int,int);int a[20][20],b[20][20],mul[20][20],m,n,p,q;clrscr();
printf("\nEnter the first matrix:\n");scanf("%d%d",&m,&n);printf("\nEnter the second matrix rows & colos:\n");scanf("%d%d",&p,&q);if(n!=p){
printf("Invalid matrix");getch();exit(0);
}printf("\nEnter the first matrix:\n");
accept(a,m,n);printf("\nEnter the second matrix :\n");accept(b,p,q);clrscr();printf("\nGiven first matrix:\n");disp(a,m,n);printf("\nGien second matrix :\n");disp(b,p,q);mul_mat(a,b,mul,m,n,q);printf("\nMultiplication matrix of given two matrix:\n");disp(mul,m,q);getch();
}void accept(int x[][20],int m,int n){
int i,j;for(i=0;i
7/30/2019 C Language Full Notes
108/179
{printf("\t%3d",x[i][j]);
}printf("\n");
}
}void mul_mat(int a[][20],int b[][20],int mul[][20],int m,int n,int p,int q){
int i,j,k;for(i=0;i
7/30/2019 C Language Full Notes
109/179
scanf("%d",&a[i][j][k]);}
}}for(i=0;i
7/30/2019 C Language Full Notes
110/179
#include#includevoid main(){
char st[20];
clrscr();puts("Enter any string:");gets(st);printf("Given string:");
puts(st);getch();
}
getch():- It gets a character from stdin and does not echo to the screen. Syntax: int getch(void);
getche():- getche gets a character from console, and echoes to the screen. Syntax: int getche(void);Program:
#include#includevoid main(){
char ch;clrscr();printf("Enter any character:");
// ch=getch();ch=getche();
printf("\nGiven Character:%c",ch);getch();
}getchar():- It is a macro that gets a character from stdin. Syntax: int getchar(void);putchar():- putchar is a macro that outputs a character on stdout. Syntax: int putchar(int c);
Program:
#include#includevoid main(){
char ch;clrscr();printf("Enter any character:");ch=getchar();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
111/179
printf("Given character:");putchar(ch);getch();
}
STRING HANDLING FUNCTIONS:-
1) strlen():- It calculates the length (no of characters ) of a string. Syntax: size_t strlen(const char *s);
Program:
#include#includevoid main(){
char st[30];int len;clrscr();printf("Enter any string:");gets(st);len=strlen(st);printf("Length of given string:%d",len);getch();
}DESIGN.H
#include
#includevoid hline(int r,int sc,int ec){
int i;for(i=sc;i
7/30/2019 C Language Full Notes
112/179
void box(int sc, int sr, int ec, int er){
gotoxy(sc,sr);printf("%c",218);gotoxy(sc,er);
printf("%c",192);gotoxy(ec,sr);printf("%c",191);gotoxy(ec,er);printf("%c",217);hline(sr,sc+1,ec-1);hline(er,sc+1,ec-1);vline(sc,sr+1,er-1);vline(ec,sr+1,er-1);
}
Program: BOX#include"design.h"#include#includevoid main(){
clrscr();textmode(2);_setcursortype(0);gotoxy(38,12);textcolor(2+BLINK);cprintf("MADHU");box(20,5,60,20);getch();
}
2) strrev():- Reverses all characters in s (except for the terminating null).Syntax: char *strrev(char *s);
Program:
#include#includevoid main(){
char st[20];clrscr();printf("Enter any string:");gets(st);strrev(st);printf("Reverse of given string:%s",st);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
113/179
getch();}3) strcpy():- It copies the given string(src) to the specified string(dest).
Syntax: char *strcpy(char *dest, const char *src);
Program:#include#includevoid main(){
char st[20], st1[20];clrscr();printf("Enter any string:");gets(st);strcpy(st1,st);printf("Given String:%s",st);
printf("\nCopied String:%s",st1);getch();}4) strcat():- It appends one string to another. Syntax: char *strcat(char *dest, const char *src);
Program:
#include#include#includevoid main(){
char st[20],st1[20];clrscr();printf("Enter any First string:");gets(st);printf("Enter Second String:");gets(st1);strcat(st,st1);printf("Concatenated string:%s",st);getch();
}5)strlwr():- It converts all upper case characters in given string into lower case. Syntax: char *strlwr(char *s);
6)strupr():- It converts all lower case characters in given string into upper case.Syntax: char *strupr(char *s);
Program:
#include#include
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
114/179
void main(){
char st[30],st1[30];clrscr();printf("Enter first string into lowercase:");
gets(st);printf("Enter second string into uppercase:");gets(st1);strupr(st);strlwr(st1);printf("\nFirst string:%s",st);printf("\nSecond string:%s",st1);getch();
}7)strncpy():- Copies at most maxlen characters of src to dest. Syntax: char *strncpy(char *dest, const char *src, size_t maxlen);
Program:
#include#includevoid main(){
char st[20],st1[20];int n;clrscr();printf("Enter any string:");gets(st);printf("Enter no of characters to be copied:");scanf("%d",&n);strncpy(st1,st,n);st1[n]='\0';printf("Given string:%s\n",st);printf("Copied string:%s",st1);getch();
}
8)strcmp():- It compares the given two strings with case sensitivity.syn:- int strcmp(const char *s1, const char *s2);
9)stricmp():-It compares the given two strings without case sensitivity.syn:- int stricmp(const char *s1, const char *s2);
10)strcmpi():- It is a macro and it compares two strings with out case sensitivity.syn:- int strcmpi(const char *s1, const char *s2);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
7/30/2019 C Language Full Notes
115/179
Return value:-
These return an int value that is< 0 if s1 < s2== 0 if s1 == s2
> 0 if s1 > s2Program:
#include#include#includevoid main(){
char st[20],st1[20];int k;clrscr();
printf("Enter first string:");gets(st);printf("Enter second string:");gets(st1);k=strcmp(st,st1);k=strcmpi(st,st1);k=stricmp(st,st1);if(k>0)
printf("First string is greater then second:");else if(k
7/30/2019 C Language Full Notes
116/179
elseprintf("Given string is not palindrome");
getch();}
Program:Write a program to accept a string and display number of characters, no of digits, no of alphabets,no of words, no of special characters and no of spaces.#include#include#includevoid main(){
char st[80];int nc=0,na=0,nd=0,ns=0,nsp=0,nw=0,i;clrscr();printf("Enter any string:");
gets(st);for(i=0;i=65 && st[i]=97 && st[i]=48 && st[i]
7/30/2019 C Language Full Notes
117/179
printf("\nNo of Alphabets :%d",na);printf("\nNo of digits :d",nd);printf("\nNo of words :%d",nw);printf("\nNo of special characters :%d",nsp);printf("\nNo of Spaces :%d",ns);
getch();