notes on c by vinayaka.docx

74
Vinayaka Solutions Language Language is a way of communication with each other.Naturally a language is the source of communication between two persons, and also between person to machine like computer. The languages we can use to communicate with the computer are known as Computer programming languages. In other words a Language is broadly defined as : Alphabets are combined to form words, Words are combined to from sentences, sentences are combined to form paragraphs, and also rules and regulations are combined to form sentences. This whole combination is known as Language. CLanguage C is a programming language that has been developed and designed by Dennis Ritchie in 1970’s at AT& T’s Bell Laboratories of USA. It was originally written in UNIX. Later on UNIX was rewritten in C language. By 1960’s COBOL language used for business & commercial use and FORTRAN for engineering and scientific purpose etc. Basic Combined Programming Language(BCPL) is further developed by Ken Thompson and give its name as B Language the first letter of BCPL. When the language was modified and improved to its present state, the second letter of BCPL,C was chosen to represent the new version by Dennis Ritchie is called C Language. C is also called Middle level language because it was designed for both i.e. relatively good programming efficiency( As in High Level Language) and relatively good machine efficiency ( As in Low Level Language). C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions ofUNIX- Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 1 Ph. 01672230170 ALPHABE SENTENCES PARAGRAPHS

Upload: harshwinder-hunjan

Post on 12-Apr-2015

34 views

Category:

Documents


2 download

DESCRIPTION

c language

TRANSCRIPT

Page 1: notes on c by vinayaka.docx

Vinayaka Solutions

Language

Language is a way of communication with each other.Naturally a language is the source of communication between two persons, and also between person to machine like computer. The languages we can use to communicate with the computer are known as Computer programming languages. In other words a Language is broadly defined as : Alphabets are combined to form words, Words are combined to from sentences, sentences are combined to form paragraphs, and also rules and regulations are combined

to form sentences. This whole combination is known as Language.

Words

CLanguage

C is a programming language that has been developed and designed by Dennis Ritchie in 1970’s at AT& T’s Bell Laboratories of USA. It was originally written in UNIX. Later on UNIX was rewritten in C language.

By 1960’s COBOL language used for business & commercial use and FORTRAN for engineering and scientific purpose etc.Basic Combined Programming Language(BCPL) is further developed by Ken Thompson and give its name as B Language the first letter of BCPL. When the language was modified and improved to its present state, the second letter of BCPL,C was chosen to represent the new version by Dennis Ritchie is called C Language.

C is also called Middle level language because it was designed for both i.e. relatively good programming efficiency( As in High Level Language) and relatively good machine efficiency ( As in Low Level Language).

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions ofUNIX-based operating systems are written in C. C has been standardized as part of the Portable Operating System Interface (POSIX).

With the increasing popularity of object-oriented programming, C is being rapidly replaced as "the" programming language by C++, a superset of the C language that uses an entirely different set of programming concepts, and by Java, a language similar to but simpler than C++, that was designed for use in distributed networks.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 1 Ph. 01672230170

ALPHABE SENTENCES PARAGRAPHS

Page 2: notes on c by vinayaka.docx

Vinayaka Solutions

C language is a way of communication with computer. It can be broadly defined as below.

Character set of C languageA character contains any alphabet, digit or special symbol to represent information. The set or

character which is valid in C program is called character set.Def: All allowable symbols in this language are called "Character set". The following characters are used in this language.Alphabets ---------- A to Z, a to zDigits ---------- 0 to 9Special Symbols ---------- , . ; : ? ! @ $ # % + - = { } etc.

Constants, Variables and KeywordsCharacter set can be combined to form Constants, Variables and Keywords.ConstantsA constant is a quantity that does not change with the execution of the program, but remains same throughout the whole program execution. e.g. 10,19.75, “INDIA” etc.Constants may be numbers, characters or strings and are also known as LITERALS.e.g. In a statementZ=3.2*X+5*Y+193.2, 5 and 19 are constants.

Classification of Constants

INTEGER ARRAYREAL(FLOAT) STRINGCHARACTER STRUCTURES

POINTERSUNIONENUM

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 2 Ph. 01672230170

ALPHABETSDIGITSSPECIAL SYMBOLS(CHARACTER SET)

CONSTANTSVARIABLESKEYWORDS

INSTRUCTIONS

PROGRAM

CONSTANTS

PRIMARYSECONDARY

Page 3: notes on c by vinayaka.docx

Vinayaka Solutions

INTEGER CONSTANTSIs an integer valued number. It consists of a sequence of digits. It consist of any combination of digits taken from 0 to 9. If it consist two or more digits the first digit must not be 0.

FLOATING POINT CONSTANTSFloating point constants can be written in two forms, fractional form and Exponential

form. Floating point represented as double precision quantities in C. Each floating point will occupy 4 bytes of memory. In floating point constants there must be a decimal point. If it is not present it must be assumed after the last digit.e.g. 225.75 , 0.0, 426.0 , -335.675, -9999.99 are some valid float points.9,975.67, 36-76.76 invalid float points.

The exponential form of floating point constant is used if the values of the constant is either too small or too large. First part before ‘e’ is called mantissa and the second part is called exponent.3.4e+38 3.4 is mantissa and 38 is exponent.e.g. 3.2e-10 , -4.75e+30, 0.67e+35

CHARACTER CONSTANTA character constants is a single character enclosed in apostrophes i.e. single quotation

marks. It may be an alphabet, digit or a special enclosed in single quotation marks. The maximum length of a character constant is 1 character in memory. Character constant has a range from -128 to +127.e.g. ‘A’ ‘1’ ‘_’ ‘z’ “=”

VARIABLES Variables is name given to memory locations where different constants are stored. It may

vary during the execution of the program.A variable is an entity that may change it value. In any program we typically do lots of calculations. The results of these calculations are stored in computer memory locations. To make the retrieval and usage of these values we give names to the memory locations. These names are called variables.

Types of VariablesThere are two main types of variables in C: numeric variables that hold only numbers or values, and

string variables that hold text, from one to several characters long.

Basic fundamental data types in C LanguageName Description Size Range

Char Character or small integer. 1bytesigned: -128 to 127unsigned: 0 to 255

short int Short Integer. 2bytessigned: -32768 to 32767

unsigned: 0 to 65535

long int (long) Long integer. 4bytessigned: -2147483648 to 2147483647

unsigned: 0 to 4294967295

BoolBoolean value. It can take one of

two values: true or false.1byte true or false

Float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)Double Double precision floating point 8bytes +/- 1.7e +/- 308 (~15 digits)

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 3 Ph. 01672230170

Page 4: notes on c by vinayaka.docx

Vinayaka Solutions

number.

long doubleLong double precision floating

point number.8bytes +/- 1.7e +/- 308 (~15 digits)

Meaning: The quantity that can change their value during programexecution.Def: It is a user-defined name. That is given to the memory location,where the quantity is stored.

e.g. Z=3.2*X+5*Y+19Z,X,Y are the variables.

Variable name must start with alphabetIs a combination of 1 to 8 alphabets, digits or underscore. Some compilers allow 40 characters.Variable name must not have any commas or blank spaces.Variable name must not have any special symbol other than underscore.e.g. hra, d_a, si, si_int, sub_5 etc are valid variable names.

IDENTIFIERS AND KEYWORDSIDENTIFIERS

Identifiers are the name given to various elements of program such as variables, functions, arrays, structure, union etc. They have same rules to construct as the rules for constructing variable names. Both Uppercase and lowercase letters can be used.e.g. area, average, sum, SUM, MARKS, M5 etc. are all valid identifiers.6th, basic-pay, d.a are invalid identifiers.

KEYWORDSKeywords are the reserved words that have standard, predefined meaning in C i.e. the

words whose meaning has already been defined to C compiler are called keywords. We should not have to use keywords to construct variable names because it will create confusion as well as we can’t assign new meanings to the keywords. There are 32 keywords available in C. There are basically 32 keywords in C.

int switch while structlong case for unionshort default far enumfloat break near typedefdoublegoto auto voidchar continue regitster singedif return extern unsignedelse do static const

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 4 Ph. 01672230170

Page 5: notes on c by vinayaka.docx

DATA TYPES

PRIMARY DATAInt.

FloatCHAR

SECONDARY DATA TYPE

Array Structure

Union Pointers

USER DEFINED

DATA TYPEEnum

Typedef

Vinayaka Solutions

What is a Compiler

When we are writing a program for computer it is in English we can understand it but the computer knows only machine language(Binary language). But we can not understand the machine language so there is a need of such program which can convert the program to machine language. Such program is called Compiler.

Data Types

Data type is a finite set of values along with set of rules for different operations. Data is very important in terms of programming. Data structure is basically how data is stored and the different operations performed on that particular data. C language provides various data types for holding different kinds of values. There are several integral data types, a character data type, floating point data types for holding real numbers and more. In addition you can define your own data types using aggregations of the native types.There can be various types of data that can be used in our daily life to solve any type of problems

Integer values like 5,-15,-32768 etc.

Floating point numbers like 2.345,-6.789,-10.11 etc.

Characters like X, Y, -, ?etc.

Names like HITUL, Hiten, XYZ etc.

Record like ( Name, Address, Phone no.), (Ac_name, Ac_no, Ac_type)C has provide us three types of Data types.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 5 Ph. 01672230170

Page 6: notes on c by vinayaka.docx

Short int

Long int

float

Long double

Vinayaka Solutions

PRIMARY DATA TYPEPrimary data types are the building blocks of the data structures.Three primary data types in C.

1. Int(for integers) e.g. 0-92. Float(for real numbers) e.g. 3.21, 45.323. Char(for characters) e.g. A to Z , a to z

Integer data typeIntegers are whole numbers with a range of values supported by a particular machine.The integer data type consists of a subset of integers. An integer constant consists of a sequence of digits preceded by an optional sign(+) or (-). In this decimal or comma in not allowed.

DATA TYPE Bytes Range FormatShort intOr intOr signed short int

2 -32768 to 32767 %d

Unsigned short intOr unsigned int

2 0 to 65535 %u

Long int or signed long int or long

4 -2147483648nto 2147483647 %ld

Unsigned long int or unsigned long

4 0 to 4294967295 %lu

Bytes are the number of bytes taken by a particular data type in a memory.

Float Data Type

The floating point data type consists of a subset of the real numbers. Floats are those values which have a decimal point in them. If we talk about 5, it is an integer but 5.0 is a float. It generally requires 4 bytes of memory for their storage. A float is accurate to 6 decimal positions i.e. number of digits after fraction are 6 and double value is accurate to 12 decimal.

Data type Bytes Range FormatFloat 4 -3.4e38 to +3.4e38 %fDouble 8 -1.7e308 to 1.7e308 %lfLong double 10 -1.7e4932 to 1.7e4932 %Lf

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 6 Ph. 01672230170

int

double

Page 7: notes on c by vinayaka.docx

Vinayaka Solutions

Character data Type

A single character can be defined as a character(char) type data. It is used to store the special characters and alphabets. It consists of ASCII characters. Characters are usually stored in 8bits(one byte) of internal storage.

Data Type Bytes Range FormatSigned char or char 1 -128 to +127 %cUnsigned char 1 0 to 255 %c

Secondary and user defined Data types are discussed later on.

HOW TO WRITE THE PROGRAM IN C

The basic format of C Program is as below

main() main function{program starts from hereStatements here statements or other declaration and calculation here } program ends here

This is the basic program or basic syntax of C program. In the program main() is the main function that calls other functions from the library or from database. The simple program is

1. main()2. {3. printf (“ Make a House.”);4. }

When you will run this program it gives a prototype error.

In line no1 function starts the program and try to find out the printf function but it did not find it then the complier gives an error of prototype.

It is described with a simple example

You want to make a house and tell the contractor to make a house for me. Then the contractor hires the different workers(like for wood work he needs a carpenter and for sanitation work he needs a plumber) to make a house. First of all to make a house the contractor needs the raw material like bricks, sand and cement. This is your duty to provide the raw material to the

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 7 Ph. 01672230170

Page 8: notes on c by vinayaka.docx

Vinayaka Solutions

contractor or give him the address of the shop from where he pick the raw material. When he will not get the raw material he will tell you.

As per above example the main() function does not get the address for raw material( printf function) so it gives you an error. To remove this error you have to tell him the address from where he will get the raw material(printf function). When you will tell the address the program runs without any error and gives the output on screen as Make a House.

Printf is a output command which will print on screen whatever is written in the “ ” inverted commas.

Now the modified and fully working program is given below.

1. #include<stdio.h>2. main()3. {4. printf(“Make a House.”);5. }

C is a Case Sensitive Language(normally program is written in small case letters)

We will discuss the above program line wise.

In first line

#include<stdio.h> first line of our program

# include <stdio.h>

Preprocessor include standard input output headerशा�मि�लकरना�

# is called preprocessor. It includes the preprocessed functions.(the functions already written by developer)Include is used to include the preprocessed functions.<less than sign is a symbolstdio.hstd stands for standard and i for input and o for output, h for header files where the input output functions are stored for use. It is like a library file.This full line tells the compiler to use the printf function from stdio.h library file. In other words it is like to tell the contractor the address of the raw material shop.>greater than sign is a symbol

2. main() ------ main function करने�वा�ला�

3. { ------- program starts

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 8 Ph. 01672230170

Page 9: notes on c by vinayaka.docx

Vinayaka Solutions

4. printf ( “ ”);

Print function that prints on the screen ( output ) whatever is written in “ ” commas.; end of line

printf() function is used to output data from the computer onto a standard output device in a fixed format. It is also a formatted I/O function. Its general form isprintf(“format string”,arguments);

5.} ----------- program ends

1. #include<stdio.h>2. main()3. {4. printf(“Make a House.”);5. }

The output of this program is

Standard Input Output FunctionsThese functions which are used for data input and output are called standard input output Functions.

1. Formatted2. Unformatted

Formatted console I/O functions : are used to input data from a standard input device (Keyboard) as well as output is sent to a standard output device (Monitor). In these functions scanf() as input and printf() function is used for output.

scanf() function is used to input data from a standard input device(keyboard) in a fixed format. It is also a formatted I/O function. Its general form isscanf(“format string”,arguments);

printf() function is used to output data from the computer onto a standard output device in a fixed format. It is also a formatted I/O function. Its general form isprintf(“format string”,arguments);

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 9 Ph. 01672230170

Make a House

Page 10: notes on c by vinayaka.docx

Vinayaka Solutions

Format String contains the format specifiers which begin with character ”%” and another charcter selected from the following Format Specifierstable.e.g. %d for signed decimal integer

Data Type Format Specifier Input TypesInteger %d or %i

%u%ld%lu%x%o

Short signed integerShort unsigned integerLong signed integerLong unsigned integerUnsigned hexadecimal integerUnsigned octal integer

Float %f%lf

Single precision floatDouble precision float

Character %c%c

Signed characterUnsigned character

String %s String

ArgumentsThe arguments specify where the input data to be stored while receiving it from a keyboard or input device. There must be an argument for each input data, the extra arguments are ignored and if arguments are less, the results are unpredictable. The arguments for scanf function must be preceded by an ampersand(&) i.e. address of operator and entered data from keyboard is stored at an address in the memory.e.g.scanf(“formatted string”,arguments);

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

integer float character

There are three format strings %d integer %f float and %c for character and the corresponding arguments a,b and c and these are precede by & operator.

The arguments specify where the output data to be collected from where it was stored for output device. There must be an argument for each output data, the extra arguments are ignored and if arguments are less, the results are unpredictable. The arguments for printf function must not be preceded by an ampersand(&)

e.g.printf(“formatted string”,arguments);

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 10 Ph. 01672230170

Page 11: notes on c by vinayaka.docx

Vinayaka Solutions

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

integer float character

scanf(“%d”,&a); 5 5aContainer name isa

printf(“%d”,a); 5shows the output 5 on screen

when you press numerical value 5 on keyboard it goes to operator a and stores there.when you recall it with printf it comes back from operator a and printf function print it on the screen.

Some more program examples are given below.

/* program to print “hello, how are you?”*/ comment lines

#include<stdio.h>#include<conio.h> console input output header filemain(){crlscr(); clear the screen and geted from conio fileprintf(“HELLO,HOW ARE YOU?”);getch(); it will skip the alt+f5 keyword to show the result}

The out put of this program is HELLO,HOW ARE YOU?

/* …………….*/ are comment lines the compiler does not read the text between these lines.it can be used for single line or for paragraph.

When you run this program by pressing ctrl+f9 the program runs if there is no getch() function in the program you can not see the result . to see the result you have to press alt+f5 the you can see the output black screen. But with getch() function you do not need to press alt+f5. As you press ctrl+f9 you will reach directly at output black screen.

Program example for format specifiers

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 11 Ph. 01672230170

Page 12: notes on c by vinayaka.docx

Vinayaka Solutions

/* print a value in different formats*/ /* comment lines */#include<stdio.h>#include<conio.h>main(){clrscr();int a=100; /*integer a is defined as int a and its value is 100*/float x=9.75,y=11.57,z=113.75; /* float x,y,z and their values 9.7,11.57,113.75*/printf(“\n Value of a is %d”,a); /* print on screen the value of a i.e. 100 */printf(“\n Value of a is %6d”,a); /* print the value of a but due to %6 it print it right justified*/printf(“\n Value of a is %-6d”,a); /* print the value of a but due to %-6 it print it left justified*/printf(“\n%f,%f,%f”,x,y,z); /* print the value of x,y,z */printf(“\n%10.1f,%10.2f,%10.3f”,x,y,z); /*print the value of x,y,x but see the decimal values in result*/getch();}

The out put of this program is given below:

Value of a is 100Value of a is ...100right justified ( … means empty spaces)

Value of a is 100…left justified ( … means empty spaces)

9.75000,11.570000,113.750000 Normal float print result after decimal 6 values printed

9.7,11.57,113.750 See the format specifier effect on result like %10.1 means the one value after decimal point,10.2 means 2 digits after decimal points.

Escape sequencesThe format specifier may also contain the sequence that starts with character ’\’(back slash)also known as Escape sequences along with the text to be output and the variables whose value is to be printed.The given below table for Scape sequence

Scape Sequence Purpose Effect\n\t\b\r\f\a\’\”\\

New LineTab SpaceBack spaceCarriage ReturnFormfeedAlertSingle quoteDouble quoteBack slash

The out put starts with new lineMove over to next spaceMoves the cursor one space leftCarriage ReturnMoves to the top of the next page on printerAlerts as beep tone of speakerInsert the character ‘ in the outputInsert the character “ in the outputInsert the character \ in the output

Program on Escape sequence

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 12 Ph. 01672230170

Page 13: notes on c by vinayaka.docx

Vinayaka Solutions

/* To demonstrate escape sequence*/ #include<stdio.h>#include<conio.h>main(){printf(“Crazy man \t don\’t follow me \n”);printf(“Hey! \\ Where are you moving?”);getch();}

Output

Crazy man don’t follow meHey! \ Where are you moving?

Unformatted Console I/O FunctionThe function that can deal with a single character and also with a string of characters are known

as unformatted console I/O functions.Dealing with single character are called as character I/O Dealing with input and output of set of characters(string) are called string I/O functions

1. getchar()2. getche() Character I/O3. getch()4. putchar()5. gets()6. puts() String I/O

getchar()This function reads a single character from the standard input device(keyboard). The read character is echoed on the screen and also the user has to press Enter Key.

getche()This function reads a single character from the standard input device(keyboard). The read character is echoed on the screen and the user has not to press Enter Key as soon as the user type the character it is immediately accepted.

getch()It also reads a character but neither this character is echoed nor the user is required to press the Enter Key. It is used where user does not want to show the input.

putchar()This function is used to send a single character to the standard output device. i.e. screen.

gets()

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 13 Ph. 01672230170

Page 14: notes on c by vinayaka.docx

Vinayaka Solutions

This function reads a string from the standard input device i.e keyboard. The length of the string is limited by declaring a string variable. String entered can have multiple words and typing Enter Key completes the input.

puts()It is used to send a string to the standard output device i.e. screen.

/* Program to show character I\O functions*/#include<stdio.h>#include<conio.h>main(){clrscr();charch;char name[20]; /*20 in square brackets are length of string*/printf(“\n Press any key to continue”);getch();printf(“\n Enter any Character”);ch=getche();printf(“\n Entered character is”);putchar(ch);printf(“\n Enter another character”);ch=getchar();printf(“\n Entered character now is”);putchar(ch);/* this part of program shows the string I/O function */printf(“\n Enter you name please”);gets(name);printf(“\n Your Name is”);puts(name);getch();}

OutputPress any key to continueEnter any character XEntered character is XEnter another character AEntered character now is AEnter your name please Harsh HunjanYour Name is Harsh Hunjan

/*program to convert temperature given in fahrenheit degree into centigrade degree */

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 14 Ph. 01672230170

Page 15: notes on c by vinayaka.docx

Vinayaka Solutions

#include<stdio.h>#include<conio.h>main()clrscr();floatf,c;printf(“\n Enter the temperature in Fahrenheit”);scanf(“%f”,&f);c=5.0/9*(f-32);printf(“\n %f degree fahrenheit=%f degree centigrade”,f,c);getch();}

OutputEnter the temperature in Fahrenheit 68.568.500000 degree fahrenheit=20.277777 degree centigrade

/* Exchange two variables*/#include<stdio.h>#include<conio.h>main()clrscr();inta,b,t;printf(“\n Enter two numbers to be exchanged”);scanf(“%d%d”,&a,&b);t=a;a=b;b=t;printf(“\n Exchanged numbers are %d,%d”,a,b);getch();}

OutputEnter two numbers to be exchanged 10 20Exchanged numbers are 20,10

Compound interest=Amount-PrincipalAmount=Principal*(1+rate/100)time/* To calculate compound interest*/#include<stdio.h>#include<conio.h>#include<math.h>main(){clrscr();floatp,r,t,a,ciprintf(“\n Enter principal amount ,rate of interest and time”);scanf(“%f%f%f”,&p,&r,&t);

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 15 Ph. 01672230170

Page 16: notes on c by vinayaka.docx

Vinayaka Solutions

a=p*pow((1+r/100),t); /* pow is power */ci=a-p;printf(“\n The compound interest =%f”,ci);getch();}

OutputEnter principal amount, rate of interest and time 5000 12 3The compound interest= 2024.640000

OperatorsAn operator is a symbol or letter used to indicate a specific operations on variables in a program. Operators act upon the data items called operands. Some operators require two operands while others act upon only one operand.e.g. + is an add operators

ExpressionAn expression is a combination of operands(constants, variables and numbers ) connected by operators and parenthesis. A simple expression is A+BEXPRESSIONA and B are the operands and + is an operator .

C language supports following type of operators.

Arithmetic Operators Logical (or Relational) Operators Bitwise Operators Assignment Operators Misc Operators

Arithmetic Operators:

There are following arithmetic operators supported by C language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 16 Ph. 01672230170

Page 17: notes on c by vinayaka.docx

Vinayaka Solutions

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denumerator B / A will give 2

% Modulus Operator and remainder of after an integer division

B % A will give 0

++ Increment operator, increases integer value by one

A++ will give 11

-- Decrement operator, decreases integer value by one

A-- will give 9

#include<stdio.h>#include<conio.h>main(){int a = 21;int b = 10;int c ;

c = a + b;printf("Line 1 - Value of c is %d\n", c ); c = a - b;printf("Line 2 - Value of c is %d\n", c ); c = a * b;printf("Line 3 - Value of c is %d\n", c ); c = a / b;printf("Line 4 - Value of c is %d\n", c ); c = a % b;printf("Line 5 - Value of c is %d\n", c ); c = a++; printf("Line 6 - Value of c is %d\n", c ); c = a--; printf("Line 7 - Value of c is %d\n", c );

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 17 Ph. 01672230170

Page 18: notes on c by vinayaka.docx

Vinayaka Solutions

}

Output

Line 1 - Value of c is 31Line 2 - Value of c is 11Line 3 - Value of c is 210Line 4 - Value of c is 2Line 5 - Value of c is 1Line 6 - Value of c is 21Line 7 - Value of c is 22

Logical (or Relational) Operators:

There are following logical operators supported by C language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

== Checks if the value of two operands is equal or not, if yes then condition becomes true.

(A == B) is not true.

!= Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 18 Ph. 01672230170

Page 19: notes on c by vinayaka.docx

Vinayaka Solutions

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

&& Called Logical AND operator. If both the operands are non zero then then condition becomes true.

(A && B) is true.

|| Called Logical OR Operator. If any of the two operands is non zero then then condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

#include<stdio.h>#include<conio.h>#include<math.h>main(){int a = 21;int b = 10;int c ;

if( a == b ) {printf("Line 1 - a is equal to b\n" ); } else {printf("Line 1 - a is not equal to b\n" ); } if ( a < b ) {printf("Line 2 - a is less than b\n" ); } else {printf("Line 2 - a is not less than b\n" ); } if ( a > b ) {printf("Line 3 - a is greater than b\n" ); } else {printf("Line 3 - a is not greater than b\n" );

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 19 Ph. 01672230170

Page 20: notes on c by vinayaka.docx

Vinayaka Solutions

} /* Lets change value of a and b */ a = 5; b = 20; if ( a <= b ) {printf("Line 4 - a is either less than or euqal to b\n" ); } if ( b >= a ) {printf("Line 5 - b is either greater than or equal to b\n" ); } if ( a && b ) {printf("Line 6 - Condition is true\n" ); } if ( a || b ) {printf("Line 7 - Condition is true\n" ); } /* Again lets change the value of a and b */ a = 0; b = 10; if ( a && b ) {printf("Line 8 - Condition is true\n" ); } else {printf("Line 8 - Condition is not true\n" ); } if ( !(a && b) ) {printf("Line 9 - Condition is true\n" ); }}

OUTPUT

Line 1 - a is not equal to bLine 2 - a is not less than bLine 3 - a is greater than bLine 4 - a is either less than or euqal to bLine 5 - b is either greater than or equal to bLine 6 - Condition is trueLine 7 - Condition is trueLine 8 - Condition is not trueLine 9 - Condition is true

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 20 Ph. 01672230170

Page 21: notes on c by vinayaka.docx

Vinayaka Solutions

B = 0000 1101

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

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

There are following Bitwise operators supported by C language

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in eather operand.

(A | B) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.

(~A ) will give -60 which is 1100 0011

<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 0000 1111

#include<stdio.h>main()

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 21 Ph. 01672230170

Page 22: notes on c by vinayaka.docx

Vinayaka Solutions

{

unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */int c = 0;

c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */printf("Line 6 - Value of c is %d\n", c );}

This will produce following result

Line 1 - Value of c is 12Line 2 - Value of c is 61Line 3 - Value of c is 49Line 4 - Value of c is -61Line 5 - Value of c is 240Line 6 - Value of c is 15

Assignment Operators:

There are following assignment operators supported by C language:

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assigne value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and

C += A is equivalent to C = C + A

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 22 Ph. 01672230170

Page 23: notes on c by vinayaka.docx

Vinayaka Solutions

assign the result to left operand

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator

C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator

C |= 2 is same as C = C | 2

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 23 Ph. 01672230170

Page 24: notes on c by vinayaka.docx

Vinayaka Solutions

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

#include<stdio.h>#include<conio.h>#include<math.h>main(){int a = 21;int c ;

c = a;printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a;printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a;printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a;printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

c /= a;printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200; c %= a;printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

c <<= 2;printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

c >>= 2;printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

c &= 2;printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2;printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

c |= 2;printf("Line 11 - |= Operator Example, Value of c = %d\n", c );

}

This will produce following result

Line 1 - = Operator Example, Value of c = 21Line 2 - += Operator Example, Value of c = 42Line 3 - -= Operator Example, Value of c = 21Line 4 - *= Operator Example, Value of c = 441Line 5 - /= Operator Example, Value of c = 21Line 6 - %= Operator Example, Value of c = 11Line 7 - <<= Operator Example, Value of c = 44

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 24 Ph. 01672230170

Page 25: notes on c by vinayaka.docx

Vinayaka Solutions

Line 8 - >>= Operator Example, Value of c = 11Line 9 - &= Operator Example, Value of c = 2Line 10 - ^= Operator Example, Value of c = 0Line 11 - |= Operator Example, Value of c = 2

Misc Operators

There are few other operators supported by C Language.

Operator Description Example

sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.

& Returns the address of an variable. &a; will give actaul address of the variable.

* Pointer to a variable. *a; will pointer to a variable.

? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

#include<stdio.h>#include<math.h>main(){int a; short b; double double c; char d[10];

printf("Line 1 - Size of variable a = %d\n", sizeof(a) );printf("Line 2 - Size of variable b = %d\n", sizeof(b) );printf("Line 3 - Size of variable c= %d\n", sizeof(c) );printf("Line 4 - Size of variable d= %d\n", sizeof(d) ); /* For character string strlen should be used instead of sizeof */printf("Line 5 - Size of variable d= %d\n", strlen(d) );}

This will produce following result

Line 1 - Size of variable a = 4Line 2 - Size of variable b = 2Line 3 - Size of variable c= 8Line 4 - Size of variable d= 10Line 5 - Size of variable d= 10

& and * Operators:

Try following example to understand & operators. Copy and paste following C program in test.c file and

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 25 Ph. 01672230170

Page 26: notes on c by vinayaka.docx

Vinayaka Solutions

compile and run this program.

main(){inti=4; /* variable declaration */int* ptr; /* int pointer */

ptr = &i; /* 'ptr' now contains the address of 'i' */

printf(" i is %d.\n", i);printf("*ptr is %d.\n", *ptr);}

This will produce following result

i is 4.*ptr is 4.

? : Operator

Try following example to understand ? : operators. Copy and paste following C program in test.c file and compile and run this program.

main(){int a , b;

a = 10; b = (a == 1) ? 20: 30;printf( "Value of b is %d\n", b );

b = (a == 10) ? 20: 30;printf( "Value of b is %d\n", b );}

This will produce following result

Value of b is 30Value of b is 20

Operators Categories:

All the operators we have discussed above can be categorised into following categories:

Postfix operators, which follow a single operand. Unary prefix operators, which precede a single operand. Binary operators, which take two operands and perform a variety of arithmetic and logical

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 26 Ph. 01672230170

Page 27: notes on c by vinayaka.docx

Vinayaka Solutions

operations. The conditional operator (a ternary operator), which takes three operands and evaluates either

the second or third expression, depending on the evaluation of the first expression. Assignment operators, which assign a value to a variable. The comma operator, which guarantees left-to-right evaluation of comma-separated

expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type) * &sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 27 Ph. 01672230170

Page 28: notes on c by vinayaka.docx

Condition

Vinayaka Solutions

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

CONTROL STATEMENTSControl statements are the statements which are used to control the flow of execution of the instructions written in the program. Instructions are executed sequentially(one after other). Such type of control structure is called sequence control structure. In this process no decision making process involved.

It is oftenly required to change the order of execution, repetition of statements. Such executions are controlled by individual control structures as per the requirements of the user.Types of control statements;

1. Decision or selection or Branching 2. Case control structures3. Looping control Structure or Repetition4. Jumping statements

Decision or selection or BranchingExecution of a group of instructions depending upon the result of decision.

1. If statement2. If-else statement3. Nested if else statement4. Else-if ladder5. Conditional operators(?:)

If StatementThe general form of if condition

If(condition)Statement block

If condition true then statement block be executed otherwise value is zero.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 28 Ph. 01672230170

Page 29: notes on c by vinayaka.docx

ifnum<0

Input num

Vinayaka Solutions

True

False

/* Check number entered is negative*/#include<stdio.h>#include<conio.h>main(){clrscr();intnum;printf(“\nEnter any number”);scanf(“%d”,&num);if(num<0) /* if num value is negative(lessthan 0)the condition true then the printf execute result */ printf(“\n Entered Number %d is negative”,num);getch();}

OutputEnter any number200 200 is more than 0 so the condition is false so the program exit without result

Second runEnter any number -10Entered Number -10 is negative

In second run the value -10 is less than 0 so the condition num<0 is true and the statement block printf executed and shows the output.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 29 Ph. 01672230170

Page 30: notes on c by vinayaka.docx

Vinayaka Solutions

true

false

As there is a single statement within statement block so we did not use braces but if there is multiple statement blocks then use braces as in next example.

/* program to calculate tax */#include<stdio.h>#include<conio.h>main(){clrscr();floatsalary,tax;printf(“\n Enter salary”);scanf(“%f”,&salary);if(salary>10000){ /* Braces starts here */tax=salary*0.20;printf(“\n Tax=%f”,tax);} /* Braces ends here */getch();}

OutputEnter salary15000Tax=3000.000000

If-else statementIf statement is used only for one true statement. If-else statement is used for true and false both statement blocksGeneral Format of if-else statementIf(condition)

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 30 Ph. 01672230170

Page 31: notes on c by vinayaka.docx

Condition

STATEMENT BLOCK 1STATEMENT BLOCK 2

Start

Inputa,b

Vinayaka Solutions

Statement block 1ElseStatement block2

True false

If more than one statements in statement block1 and block2 then use braces.

General formatIf(condition){Statement aStatement b Statement Block 1}Else{Statement a Statement Block 2Statement b}

Flow chart of program

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 31 Ph. 01672230170

Page 32: notes on c by vinayaka.docx

Vinayaka Solutions

True

False

/* Find the bigger no out of two numbers*/#include<stdio.h>#include<conio.h>main(){clrscr();inta,b;printf(“\n Enter two numbers”);scanf(“%d%d”,&a,&b);if (a>b)printf(“%d Number is big”,a);elseprintf(“%d Number is big”,b);getch();}OutPutEnter two numbers 10 2020 Number is big print the result of b integer because the if statement a>b false If 10>20 10 is less than 20 so condition is false it print b on screenSecond RunEnter two number 20 10

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 32 Ph. 01672230170

Page 33: notes on c by vinayaka.docx

Start

Inputn

if n%2==0

printnis even

Printn is odd

Stop

Vinayaka Solutions

20 Number is big print the result of b integer because the if statement a>b trueIf 20>10 20 is big than 10 so condition is true it print a on screen

Write a program Whether entered number is even or odd /*Number divisible by 2 is even otherwise odd*/#include<stdio.h>#include<conio.h>main(){clrscr();int n;printf(“\n Enter a number”);scanf(“%d”,&n);if (n%2==0) /* n is divisible % by 2 and the remainder =0 then it is even*/printf(“ Number %d is even”,n);elseprintf(“ Number %d is odd”,n);getch();} Flow Chart of program

Out put Enter a number28Number 28 is even

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 33 Ph. 01672230170

Page 34: notes on c by vinayaka.docx

Vinayaka Solutions

Second RunEnter a number 19Number 19 is odd

/*Calculate gross salary*/#include<stdio.h>#include<conio.h>main()clrscr();floatbasic,da,hra,ma,gross;printf(“\n Enter Basic salary”);scanf(“%f”,&basic);if(basic<=10000){da=basic*31/100;hra=basic*12/100;ma=250}Else{da=basic*35/100;hra=basic*15/100;ma=350}gross=basic+da+hra+ma;printf(“\nGross salary of Empolyee =%10.2f”,gross);getch();}

OutputEnter basic salary 9000Gross salary of Empolyee=13120.00

Second RunEnter basic salary 15000Gross salary of Empolyee=22850.00

Nested if –else statementIf we have an entire if-else construct within either the body of an if statement or the body of an else statement. This is called nested if else.General format.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 34 Ph. 01672230170

Page 35: notes on c by vinayaka.docx

1

2

Statement block3

Statement block2

Statement block1

Block1

Block2

Block 3

Block 4

2

31

Vinayaka Solutions

1st type 2nd typeIf (condition1) If (condition1){ {If(condition2) If(condition2)Statement block1 Statement block1

Else Else

Statement block2 Statement block2} }Else Else

{Statement block3 if (condition3)

Statement block3

Else

Statement block4

}

By using nested if find the biggest number of three given numbers

/*Biggest of 3 numbers*/#include<stdio.h>#include<conio.h>main()

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 35 Ph. 01672230170

Page 36: notes on c by vinayaka.docx

Vinayaka Solutions

{clrscr();inta,b,c;printf(“\n Enter three numbers”);scanf(“%d%d%d”,&a,&b,&c);if(a>b){If(a>c)Printf(“%d biggest number”,a);ElsePrintf(“%d biggest number”,c);}Else{If(b>c)Printf(“biggest no %d”,b);ElsePrintf(“biggest no %d”,c);}Getch();}

OutputEnter three numbers30 20 10Biggest no.=30Second runEnter three numbers10 100 50Biggest no=100Third runEnter three numbers 10 20 50Biggest no 50

Leap year program/*Leap year or not*/#include<stdio.h>#include<conio.h>main(){clrscr();int year;printf(“\n Enter the year”);scanf(“%d”,&year);if(year%100==0){If(year%400==0)Printf(“\n Year %d is leap”,year);ElsePrintf(“\n year %d is not leap”,year);

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 36 Ph. 01672230170

Page 37: notes on c by vinayaka.docx

Cond 1

Cond2

Cond3

Block1

Block2

Vinayaka Solutions

}Else{If(year%4==0)Printf(“\n year %d is leap”,year);ElsePrintf(“\n year %d is not leap”,year);}getch();}

OutputEnter the year 2000Year 2000 is leapSecond run Enter the year 1900Year 1900 is not leapThird RunEnter the year 2004Year 2004 is leap

The Else if ladderSometimes the nesting becomes complex in the sense that it becomes difficult to decide”which if does the else match”. So in these situations we use if else-if ladder.

The general structure of if else-if ladder isIf(condition1)Statement block1Else if(condition2)Statement block2Else if(condition3)Statement block 3Else if (condition n)Statement block nElseStatement block m

Flow chart

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 37 Ph. 01672230170

Page 38: notes on c by vinayaka.docx

Vinayaka Solutions

/* Program to print day of the week*/#include<stdio.h>#include<conio.h>main(){clrscr();int day;printf(“\n Enter day of week as number from 1 to 7=”);scanf(“%d”,&day);if(day=1)printf(“\n Day of week is Monday”);else if (day=2)printf(“\n Day of week is Tuesday”);else if (day=3)printf(“\n Day of week is Wednesday”);else if(day=4)printf(“\n Day of week is Thursday”);else if (day=5)printf(“\n Day of week is Friday”);else if (dy=6)printf(“\n Day of week is Saturday”);else if(day=7)printf(“\n Day of week is Sunaday”);elseprintf(“\n Wrong input”);getch();

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 38 Ph. 01672230170

Page 39: notes on c by vinayaka.docx

Vinayaka Solutions

}

OutputEnter day of week as number from 1 to 7=5Day of week is Friday

Leap Year problem with Logical Operators/*Leap year*/#include<stdio.h>#include<conio.h>main(){clrscr();int year;printf(“\n Enter the year”);scanf(“%d”,&year);if(((year%100==0)&&(year%400==0))||((year%100!=0)&&(year%4==0)))printf(“\n year%d is leap”,year);printf(“\n year %d is not leap year”,year);getch();}OutputEnter the year 2000Year 2000 is leapSecond run Enter the year 1900Year 1900 is not leapThird RunEnter the year 2004Year 2004 is leap

Conditional OperatorA conditional operator(? : ) help in performing simple conditional operations. It is called as ternary operator because it operators on three values. It will do the similar operation to if-else .General formE1?E2:E3 E1,E2,E3 are expressions.First E1 is tested, if E1 is true then E2 evaluated otherwise E3 is evaluated.

/* Find the bigger no out of two numbers*/#include<stdio.h>#include<conio.h>main(){clrscr();inta,b,big;

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 39 Ph. 01672230170

Page 40: notes on c by vinayaka.docx

Vinayaka Solutions

printf(“\n Enter two numbers”);scanf(“%d%d”,&a,&b);big=a>b?a:b; /* check a>b if a is big then goes to a otherwise go to b */printf(“%d Number is big”,big);getch();}OutPutEnter two numbers 10 2020 Number is big

/* Find the bigger no out of three numbers*/#include<stdio.h>#include<conio.h>main(){clrscr();inta,b,c,big;printf(“\n Enter three numbers”);scanf(“%d%d%d”,&a,&b,&c);big=a>b?(a>c?a:c): (b>c? b : c); /* check a>b if a is big then goes to check a>c otherwise go to (b>c) */printf(“%d Number is big”,big);getch();}OutPutEnter two numbers 10 2020 Number is big

Case control Structure(Switch Case)To select one of several different courses of action then the switch control structure is used. it is better construct than if –else if ladder. It can also be called as the replacement of multiple ifs.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 40 Ph. 01672230170

Page 41: notes on c by vinayaka.docx

Value of Expression

Constant1

Cons2

Cons3

Statement 1

Statement 2

Statement3

default

Break

Break

break

Vinayaka Solutions

The general form is given below.

Switch(expression){Case constant 1:Statement block 1Break;Case constant 2:Statement block2Break;Default:Statement block 3;}Where switch,case,default are the reserved words or keywords.

Programe;

Print day of weak.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 41 Ph. 01672230170

Page 42: notes on c by vinayaka.docx

Vinayaka Solutions

#include<stdio.h>#include<conio.h>main(){Clrscr();Int day;Printf(“Enter day in numbers 1 to 7”);Scanf(%d”,&day);Switch(day){Case1:Printf(“\nMonday”);Break;Case2:Printf(“\nTuesday”);Break;Case3:Printf(“\nWednesday”);Break;Case4:Printf(“\nThursday”);Break;Case5:Printf(“\nFriday”);Break;Case6:Printf(“\nSaturday”);Break;Case7:Printf(“\nSunday”);Break;Default:Printf(“\n Wrong input”);}Getch();}

Loop Control StructuresThe repetitive execution of a set of statements in a program is known as interactive loop.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 42 Ph. 01672230170

Page 43: notes on c by vinayaka.docx

Condition

Statement

Vinayaka Solutions

Three methods of looping

1. while statement2. for statement3. do-while statement

While Loop:It is repetitive control structure used in C. How many times a statement or a set of statements i.e. statement block will be executed.

N

Y

Program/* To display digits from 0 to n*/#include<stdio.h>#include<conio.h>Main()Clrscr();Int n, digit=0;Printf(“\n Enter last Digit”);Scanf(“%d”,&n); /*value of n from keyboard by user*/While(digit<=n) /* condition digit is less than and equal to n */{Printf(“%d\n”,digit); /* if condition is true the blocks executed otherwise goes to end*/Digit=digit+1;}Getch();}

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 43 Ph. 01672230170

Page 44: notes on c by vinayaka.docx

Condition

Body of loop

Increment/decrement

Vinayaka Solutions

For Loopfor loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers:

N

#include <stdio.h>

main(){ int i; int j = 10;

for( i = 0; i <= j; i ++ ) { printf("Hello %d\n", i ); }}

OutputHello 0Hello 1Hello 2Hello 3Hello 4Hello 5Hello 6Hello 7Hello 8Hello 9Hello 10

Print pattern using nested for loop.

#include<stdio.h>main(){

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 44 Ph. 01672230170

Page 45: notes on c by vinayaka.docx

Vinayaka Solutions

int n, c, k;  printf("Enter number of rows\n"); scanf("%d",&n);  for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) printf("*");  printf("\n"); }  Getch();}

Output***************

Draw a diamond pattren#include <stdio.h> int main(){ int n, c, k, space = 1;  printf("Enter number of rows\n"); scanf("%d", &n);  space = n - 1;  for (k = 1; k <= n; k++) { for (c = 1; c <= space; c++) printf(" ");  space--;  for (c = 1; c <= 2*k-1; c++) printf("*");  printf("\n"); }  space = 1;  for (k = 1; k <= n - 1; k++) { for (c = 1; c <= space; c++) printf(" ");  space++;  for (c = 1 ; c <= 2*(n-k)-1; c++) printf("*");  printf("\n"); }

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 45 Ph. 01672230170

Page 46: notes on c by vinayaka.docx

Statement block

condition

Vinayaka Solutions

  Getch();}

Output *

***

*****

***

*

DO-Whiledo ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once.

#include <stdio.h>

main(){ int i = 10;

do{ printf("Hello %d\n", i ); i = i -1; }while ( i > 0 );}

Output

Hello 10Hello 9Hello 8Hello 7Hello 6

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 46 Ph. 01672230170

Page 47: notes on c by vinayaka.docx

Vinayaka Solutions

Hello 5Hello 4Hello 3Hello 2Hello 1

Jumping Statements:

Jumping statements are used to transfer control from one part of the program to another part.1. The break statement2. The continue statement3. The goto statement

Break statement:

The break statement is always used inside of the switch statement. It can also be used in any of the loop statement for unconditional transfer of control from the loop to the statement immediately following the loop.In switch statement it is used as the last statement block of every case expect the last one. In while, for, do-while loops, it is always used in conjunction with if.

Entery

Statements

Break;

Statements

Break statement program

#include<stdio.h>#include<conio.h>Main(){int i;for(i=1;i<=10;i++){printf(“\n %d”,i);

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 47 Ph. 01672230170

Page 48: notes on c by vinayaka.docx

Vinayaka Solutions

if(i==3){Printf(“\n ok bye”);Break;}Printf(“\n Next”);}Getch();}OUTPUT1Next2Next3Ok bye

You can make use of break to come out of do...while loop at any time.

#include <stdio.h>

main(){ int i = 10;

do{ printf("Hello %d\n", i ); i = i -1; if( i == 6 ) { break; } }while ( i > 0 );}

Output

Hello 10Hello 9Hello 8Hello 7Hello 6

The Continue StatementThe continue statement is used inside the body of loop statement. It transfer the control back to the first statement or to the beginning of the loop.

Entry

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 48 Ph. 01672230170

Page 49: notes on c by vinayaka.docx

Vinayaka Solutions

Iterative loopContinue;

Continue Statement

For(i=1;i<=3;i++){Printf(“%d \n”,i)If(i==2)continue;printf(”Bottom of loop \n”)}Printf(“out of loop”);

Output1Bottom of loop23Bottom of loopOut of loop

goto statement The goto statement cause the control to be transferred to the statementwhose label is specified in the goto statement.

Demo of goto statementScanf(“%f”,&x);While(x<=50){If(x<0)goto error;Scanf(“%f”,&x);}error;printf(“Negative value error”);

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 49 Ph. 01672230170

Page 50: notes on c by vinayaka.docx

Vinayaka Solutions

FunctionsA function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required. Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program.The name of the function is unique in a C Program and is Global. It means that a function can be accessed from any location with in a C Program. We pass information to the function calledarguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.The general form of Function is <type><name>(arguments){Statement block}<type>----- type of value to be retruned by the function. If no value is retruned then void should be Used.<name>----user defined name of the function.Arguments--- is a list of parameters and can be omitted also by leaving the parameters empty.The opening and closing braces is known as function body.

Demo of Simple Function

main(){printf(“\n Hello,How are you?”);message(); /* Function message call*/printf(“\n Do not worry I am back in main”);}message() /*Function defination or Function defined here*/{Printf(“\nWhere are you moving out”);}

Output Hello, How are you?Where are you moving outDo not worry I am back in main

Structure of a Function

int sum(int x, int y)

{

int ans = 0; //holds the answer that will be returned

ans = x + y; //calculate the sum

return ans //return the answer

}

There are two main parts of the function. The function header and the function body.

Function Header

In the first line of the above code

int sum(int x, int y)

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 50 Ph. 01672230170

Page 51: notes on c by vinayaka.docx

Vinayaka Solutions

It has three main parts

1. The name of the function i.e. sum2. The parameters of the function enclosed in paranthesis3. Return value type i.e. int

Function Body

What ever is written with in { } in the above example is the body of the function.

Function Prototypes

The prototype of a function provides the basic information about a function which tells the compiler that the function is used correctly or not. It contains the same information as the function header contains. The prototype of the function in the above example would be like

int sum (int x, int y);

The only difference between the header and the prototype is the semicolon ; there must the a semicolon at the end of the prototype.

The retrun statementThe genreal form of retrun statement isretrun(exp);retrun statement immediately transfers the control back to the calling program.It retruns the value after retrun to the calling program.The retrun statement need not always be at the end of the called function.there is no restriction on the number of retrun statements. It can retrun only one value. E.g.Big(int a,int b){If(a>b) retrun(a);elseretrun(b);}If the valur of a is greater than b then a will be retruned otherwise b will retruned.Program/* calculate sum of 3 numbers*/#include<stdio.h>#include<conio.h>main(){int calsum(int, int, int);int n1,n2,n3,sum;printf(“\n Enter three numbers”);scanf(“%d%d%d”,&n1,&n2,&n3);sum=calsum(n1, n2, n3); /*Here function calsum call*/printf(“\n Sum is %d”,sum);getch();}int calsum(int a,int b,int c) /* here calsum is defined */{

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 51 Ph. 01672230170

Page 52: notes on c by vinayaka.docx

Vinayaka Solutions

int s;s=a+b+c;retrun(s); /* here the retrun function retrun the value of s*/}

OutputEnter three numbers 10 20 30Sum is 60

Program/*convert lower case to uppercase*/#include<stdio.h>#include<conio.h>main(){char change(char);char lower,upper;clrscr();printf(“\n Enter lowercase letter”);scanf(“%c”,&lower);upper=change(lower); /* function call*/printf(“\n The uppercase is %c”,upper);getch();}char change(char c) /*function defined*/if(c>=97&&c<=122)retrun(c-32);}OutputEnter lowercase letter dThe uppercase is D

PointersA pointer is a variable that contains the address of a variable or an array elements.int i=5any variable has three properties1. Name 2. Value 3. Location

i----------- vaiable name5-----------value2002-------location or address in memory

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 52 Ph. 01672230170

Page 53: notes on c by vinayaka.docx

Vinayaka Solutions

j=&i j is declare as pointer variable because it containsthe address of variable i. To declare pointer use the following notation.int *j;where * is a pointer symbol called as value at address symbol and j is a pointer variable. It means

i----variable j-----------------pointer variable5------value 20022002---address 4004-----addressSo we can print the value of I by using pointer variable also.

/* The value of I using pointer variable*/main(){int i=5, *j;j=&I;printf(“\n The value of i=%d”,i);printf(“\n The address of i=%u”,&i); /* %u is unsigned and gives the address */printf(“\n The address of i=%u”,j);printf(“\n The value of i=%d”,*j);}OutputThe value of i=5The address of i=2002The address of i=2002The value of i=5

ARRAYA class of 40 students with their marks in an examination. To make a program we need 40 variables. But with one variable which is called as array or subscripted variable to store 40 values.With simple variable method int s1,s2,s3,s4,----,s39,s40;with arrayint s[40];

An array in C Programming Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name.

An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a “string”, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can’t have an array of 10 numbers, of which 5 are ints and 5 are floats.Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name.An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a “string”, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can’t have an array of 10 numbers, of which 5 are ints and 5 are floats.Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 53 Ph. 01672230170

Page 54: notes on c by vinayaka.docx

Vinayaka Solutions

Arrays must be declared before they can be used in the program. An array can be visualised as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Look at the figure below :An Array of four elements:

+===================================================+

| elem1 | elem2 | elem3 | elem4 |

+===================================================+

The number of 8 bit bytes that each element occupies depends on the type of array. If type of array is ‘char’ then it means the array stores character elements. Since each character occupies one byte so elements of a character array occupy one byte each.

An array is defined as following :

<type-of-array> <name-of-array> [<number of elements in array>];

type-of-array: It is the type of elements that an array stores. If array stores character elements then type of array is ‘char’. If array stores integer elements then type of array is ‘int’. Besides these native types, if type of elements in array is structure objects then type of array becomes the structure.

name-of-array: This is the name that is given to array. It can be any string but it is usually suggested that some can of standard should be followed while naming arrays. At least the name should be in context with what is being stored in the array.

[number of elements]: This value in subscripts [] indicates the number of elements the array stores.

For example, an array of five characters can be defined as :

char arr[5];

data type subscript or index name of array

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 54 Ph. 01672230170

Page 55: notes on c by vinayaka.docx

Vinayaka Solutions

if one subscript is used to refer to an element of an array the array is known as one dimensional or linear array. If two subscripts are used then the array is known as two dimensional or matrix. The array which has more subscripts than two are known as multidimensional array.

int a[5][6]; two dimensional array due to two subscript [5][6] are used.The elements in array start with 0 not 1 and ends with one less than value of subscript. Since one integer value requires 2 bytes of memory, so array for s compiler allocates a contiguous block of 80bytes in memory.

0 1 2 3 39 s

2000 2002 2004 2078

2000,2002,2004…….. are the addresses of memory locations.

One Dimensional ArrayThe single element of an array can be accessed by array name followed by an index enclosed in brackets.All array elements are numbered starting from 0.e.g. int S[5]={10,20,30,40,50};

0 1 2 3 4 S 2000 2002 2004 2006 2008

First element S[0] and its value 10Second element S[1] and its value 20Fifth element S[4] and its value 50

Two Dimensional ArrayAn element can be accessed simply by array name followed by two index numbers enclosed in brackets.e.g.

int a[2][3]={10,20,30,40,50,60};To access first row and first coloumn a[0][0]=10To access first row and third coloumn a[0][1]=20To access first row and third coloumn a[0][2]=30Second row first coloumn a[1][0]=40Second row second coloumn a[1][1]=50Second row third coloumn a[1][2]=60Entering data into an arrayArray is a collection of values. We can enter data into array by using loop statement. For one dimensional array one loop used for two dimensional array two loops are used.e.g.one dimensional arrayProgram/*data entry into one dimensional array*/int S[10];for(i=0;i<=9;i++){

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 55 Ph. 01672230170

10 20 30 40 50

Page 56: notes on c by vinayaka.docx

Vinayaka Solutions

printf(“\n Enter marks”);scanf(“%d”,&S[i]);}

Two dimensional arrayProgram/* data entery into two dimensional array*/Int a[5][6];for(i=0;i<=4;i++){for(j=0;j<=5;j++) {Printf(“\n Enter data”);Scanf(“%d”,&a[i][j]);}}Output from an arrayAs data can be entered by using loop statement similar way output from an array is taken by using loop statement.One Dimensional array/* Demo of outputting one dimensional array*/printf(“\n Elements of an array are\n”);for(i=0;i<=9;i++)printf(“%d\t”,S[i]);Two Dimensional array/*demo of output from two dimensional*/Printf(“\n Elements of an array are\n”);for(i=0;i<=4;i++){for(j=0;j<=5;j++)printf(“%d\t”,a[i][j]);printf(“\n”);}

Program/*Print an array in reverse order*/#include<stdio.h>#include<conio.h>main(){Clrscr();Int n[10],i;Printf(“\n Enter the list of 10 numbers”);for(i=0;i<=9;i++) /* i<=9 because we enter 10values if we starts from 0 to 9 */scanf(“%d”,&n[i]);printf(“\n List in revers order is\n”);for(i=9;i>=0;i--)printf(“%d\t”,n[i]);getch();

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 56 Ph. 01672230170

Page 57: notes on c by vinayaka.docx

Vinayaka Solutions

}OutputEnter the list of 10 numbers10 20 30 40 50 60 70 80 90 100List in revers order is100 90 80 70 60 50 40 30 20 10

Two program given below are one with simple method second with array method

/*The average marks of 5 students using basic data type */#include<stdio.h>#include<conio.h>main(){Clrscr();int m1, m2,m3,m4,m5,avg;printf(“Enter the marks of 1st student”);scanf(“%d”,&m1);printf(“Enter the marks of 2 student”);scanf(“%d”,&m2);printf(“Enter the marks of 3 student”);scanf(“%d”,&m3);printf(“Enter the marks of 4 student”);scanf(“%d”,&m4); printf(“Enter the marks of 5 student”);scanf(“%d”,&m5);avg=(m1+m2+m3+m4+m5)/5;printf(“\n The average marks of a student=%d”,avg);getch();}

/* same program using array*/#include<stdio.h>#include<conio.h>main(){Clrscr();int m[5],i,s=0,avg;for(i=0;i<=5;i++);{Printf(“\n Enter the marks of %dstudent”,i+1);Scanf(“%d”,&m[i]);s=s+m[i];}avg=s/5;printf(“\n The average marks of a student=%d”,avg);getch();}

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 57 Ph. 01672230170

Page 58: notes on c by vinayaka.docx

Vinayaka Solutions

Memory allocation of the above two program is given belowm5 m4

m2 m[0] m[1] m[2] m[3] m[4]m1

m3 m1,m2,m3,m4,m5 store anywhere all elements are stored in contiguous memory.

Program#include<stdio.h>#include<conio.h>main(){Clrscr();int a[100],big,pos,i,n;printf(“\n Enter the size of the list”);scanf(“%d”,&n);printf(“\n Enter list of %d numbers”,n);for(i=0;i<n;i++){scanf(“%d”,&a[i]);big=a[0]; /* set the first value to big */pos=0; /*set position of big as 0 */for(i=1;i<=n;i++){If(a[i]>big){big=a[i];pos=i;}}pos++; /*increase position by 1 as array is counted from 0*/printf(“\n The largest number=%d is stored at position=%d”,big,pos);getch();}OutputEnter the size of the list 10Enter list of 10 numbers2 8 1 9 50 40 30 7 20 10The largest number=50 is stored at position=5

Police City Road, Near NRG Complex PremBasti, Gali no 7 Sunam Sangrur. Ph. 01676225500 58 Ph. 01672230170