KEMBAR78
C Notes | PDF
0% found this document useful (0 votes)
14 views22 pages

C Notes

The document provides an overview of programming concepts in C, including tokens, operators, data types, control statements, loops, functions, structures, and unions. It explains various operators such as arithmetic, relational, logical, and bitwise, along with examples of control structures like loops and conditional statements. Additionally, it covers the use of pointers, arrays, and user-defined functions, emphasizing the importance of data organization and memory management in C programming.

Uploaded by

ayushtechie99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
14 views22 pages

C Notes

The document provides an overview of programming concepts in C, including tokens, operators, data types, control statements, loops, functions, structures, and unions. It explains various operators such as arithmetic, relational, logical, and bitwise, along with examples of control structures like loops and conditional statements. Additionally, it covers the use of pointers, arrays, and user-defined functions, emphasizing the importance of data organization and memory management in C programming.

Uploaded by

ayushtechie99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
PROGRA MMING IN C and Cy, > A token is the smallest element of a program that |(f tic operators are Sed to pee, is meaningfl in the compiler. Lees ations. Re ‘mathematical oper pet TMies if Operators ~~ eae ee 1 | Addition, Adds two values ——Sabiraction, Subtracts one vane] Yfoker} from another eS (os) |—— Multiplication, Multiplies ayo values [ee ae (wn) eo ae another > Identifier refers to name given to entities such as | |__| reraites divinicas Variables, functions, structures, array etc. % Remainder is Identifiers must be unique. rs Increment, increase the value of g > Keywords is reserved word, It can't use as a variable by | eS _ ——______ variable name and constant name. Decrement, Decreases the value ofa auto break case char variable by 1 const | double | else continue tional Operators default | do enum | exten = float for goto if Relational Operators are used to checks the at ae eT relationship between two operands. a ae ek | aah Operators | Meaning of Operator struct | switch | typedef | union Equal to unsigned | void volatile | while Roce > Constant is a name given to the variable. It can't z Greater than altered or changed during execution once < Less than defined. : >= | Greater than or equal to D String is a sequence of characters terminated SRM caer ui with a null character \0' strings are defined as an |__| array of characters. Example— | Logical Operators — g Logical operators are used to determine the loge between variable or values and return either 0 oI | Operators | Operators Meaning 3 Re ee Operators are used to perform the operations on && | Logical and, Retums true ifthe both variables and value. statements are true, " Logical or, Returns true if the on¢ ‘of the statements is true. t Logical Not, Reverse the result, Fetus false if the result is true. Bitwise Operators SAAS g % — | Percent . se eperaors are used to perform bit level ie ‘Apostrophe rat ~ ope = Caret = | Minus si -ators_| Meaning of Operators mE La oO Bitwise AND pee |e eae 1 Bitwise OR posit 1, | penis [mee a : bracket 3 itwise XOR (Exclusive OR) v Left > [closing angle Z__| Left Shit parenthesis bracket ss_| Right shin ) | rieht 7 | Question mark 2 Bitwise complement parenthesis ae = \derscore Left brace Assignment Operators ; me |e Assignment operators are used [tue sien_|_ J Risto are used to assign values : to variables. Comma i aa aoe ; Period 1_| Right brac Operators _| Meaning of Operators a te matenraat = ‘Simple Assignment ~ Multipli * 3 Semicolon ie 5” pats typed Ia C= There are seveeal dice Division Assignment ways to store data in C and they are all uniate %= Remainder Assignment Hon veastitelhcencTi® Floating Point» Union f+ Pointer z ‘Other Operators |, Double Floating b> Enum Reference int Geawtors [Meaning ofOpenos 1) Nea a SizcoR) | To rerum the actual sizeof Y || 5 Conerol Structure: LOOPS” loop is used to given variable ; repeat a block of code until the specified & “To return the address of any given Fcpdition is mst we ‘Control Statements * Pointer to @ variable 2: ‘Conditional expression of fenary operator Selection Iterative ——| Member selection operator Statement | [Statement operators linked related 2 How for oop works: > es initstatement For body Loop Update Expression /* Calculation of simple interest for 3 sets p, andr */ r ‘main(){ int p, n, count; ‘float r, si; for (count = 1; count <=3; count = count + 1): Print{("Enter values ofp, n ands"); scanf("%d %d %f", &p, en, dt); si=p*n*1/100; Printf("simple interest = Rs. %fin", si); Symtarnitycondition;inerement){ for for(init /jstatement of outer loop } t;condition;increment) { //statement of inside loop Flow-Chart of Nested for Loop [outer for loop] start [Outer for loop| —| Test False Condition pia bn inner for loop start as inner for loop > test of False condition Block of statement Update Expression of inner for loop Update expression of outer for loop e a Tos tee (es Consider the program Be ton. ees, jetatement of body Text Expression } Understand operati Understand operation of the while loop by input p, n,t [si = p*n*r/100] )o/While Loop- This loop will execute the se block once, before checking if the condition then it will repeat the loop as long as the | Syntax Syntax— #0, 1. If statement ifleondition) { statement execute if statement is true } if condition Statement just below if 2. If-else statement— if{condition) { ‘Jlexecute block if condition true jelset Hexecute if condition false ‘iftest expression) { “statement } else if “statement } else iff//statement 2 else {//statement Statement Syntax— \ ‘ispeific condition break; 1. Breal Loop body starts Condition to ] -, break from |e loop 2. Continue statement Syntax— Continue; Condition to continue next iteration xple- ? int main){ int myFirstindext] = , printi("%6 return 0; } piput = 25 > Array in Loop~ -sample— int maing) { intarr[]= (5, 10, 15, 17,20) inti=0; ; while (i<5) { Printh("%d", arti); its } return 0; 25, 40, 70, "70, 150) * myFirstindex(0), ui } wtput = 510 15 1720 Multidimensional Arrays— A multidimensional array is an array of arrays. yntax— data_type array name[sizel ][size2J....[sizeN]; Multi-dimension| Array ‘Two dimension Array hample— ‘Column 0 | Columni | Column 2 Row0| 2 3 4 [Rowt [5 6 8 int main(){ int matrix[2][3] = (1234 {5,6,,8}}; intijs iH){ for(i=0;j<3; 54) print"%d\n", matrix CDs gage stn for (i retum 0; Outputs . 2 Strings Strings are text/characters. used for storing Strings Initialize ‘Char of] = "ab" Char ¢[20) = "ab"; b,10} Char ef] = {' Char {6} = ('a'26', 0} Cll] C12) El fl fo Oy; Example— int main(){ char greetings[] = "Hello YCT"; printf(’%s", greetings); return 0; 3 Output = Hello YCT Meniory Address The memory address is the location of where the variable is stored on the computers. Memory address is in hexadecimal form. Pointers are used.to store the address of variables or memory location. ‘Syntax— datatype *var_name; Declare a pointer variable must be a * before its name. | How to pointer works var pee int var = I 72008 20 39 Example— maing( int a; irntf("%6d", &a); /iprint address of « retund; ) Output = Ox7MS06 7a 104 Note- Output can be assigned different address in different runs. Example int maing( int® PC, C; C=32; Printf{” Address of C:%ed\n", & ¢); Printf( "value of C:%d\n\n", C); PC=&C; Printf(" Address of pointer PC:%d\n"PC); Printf("Content of pointer PC:%d\n\n", *PC); c=; Printf{" Address of pointer PC:%d\n", Printf{"‘content of pointer PC:%din\ *PC=2; Printf{"Address of C:%d\n", &C); Printf("value of C: %d\n\n", C); return 0; ; 3 PC); * PO); ‘Output Address of C : 0x7£%448586Sec Value of C: 32 Address of pointer PC: Ox7#fd485P55ec ‘Content of pointer PC: 32 Address of pointer PC: Ox7fid485t65ec ‘Content of pointer PC: 11 Address of C: 0x7114485f65ec Value of C: 2 BE oneness Funetions- A function is a block of code which only runs when itis called, Syntax— void myFunct() { declaration “code to be executed( definition) 3 Library Functions 1 © Standart, defined in header Biles me _—* SS Tis ope of console cuiparis ioh | It is type of onsoe Cup conto | fit ee ow | It is a standard type of outputin wtdion | Itis OF out atap : Gh Ls) ei The function are react a ‘operations, i 1 The functio lated to err fh | The funi jon are related 10 eran om | functions tay | print) | The function send formatted Fe | seven. This tmnetionstotnnd in the ag header file. , Copel | Character type functions asserth | Program assertion functions User defined funetion— Working flow gr defined function #include void functionName(){ ee int main(){ fanctionName(); [asd ; } function names are identifiers and shoud : ® unique. User Defined Funetion 1. No arguments and no return value 2. No arguments and a retum value 3. Arguments and return value 4. Arguments and with retum value 1.No Arguments an Syntax- Void function name(){ dino return 'd no return value— q wens and No return value © 17d function_name(typel argument, {ype? angument2,...typeN argumentN) execute program retum; ) gaments and with return value“ Po retur_fype function_name(typel ‘arguments1, type2 arguments2___typeN arguement) { WVexecute program return value; Y (ebRecursion = [QS A fiction tat calls itself is known as a recursive function and technique is known as a recursioh. This technique provides a way to break complicated problems down into simple problems which are easier to solve, © Working of Recursion 8 Recursive Void recurse() call } ‘ recurse(); } int main(), ‘ recurse(); * ; ; Natural Numbers. > finclude intmainQ{ | int number, reel return n+ sum(n ~ 1); else return n; } > Output- Enter a positive integer:6 sum = 21 ' A structure or struct isa collection of variables (different types) under a single name. Structure using the struct keyword and declare each ofits members inside curly braces. Syntax— © strugt structureName { datatype member; datatype member2; if Example vord {ag or structure cnn a a Struct Person { char name (50];] Members or fields int CitNo; so of sate float salary; h (9 Symbol Access the structure members. Example struct myStructure{ ‘int myNum; char myLetter; | slanyNums 137i peas este aoe aan) BRB ceyworaappeaersiiitie I We use the typedef keyword to create an alia ame for data types, Example Hinclude #include typedef struct person { char name[S0}; int dtdNo; float salary; } person; int maing{ Person pl; Strepy(pI.name, "Rahul"; Pl. dtdNo=1010; Pl.salary = 9000; Printf("Name; %s\n", p1.name); Printf(” department No: %din", \pl.dtdNo); Printf{"salary:%.2f, p1 salary); return0; 3 Output— ‘Name: Rahul Department No. 1010 S Salary: 9000 ¥ uml comp real =525; Nested Structure— Nested struct within a struct. # include struct complex { int img; float real; B struct number { struct complex comp; int integer; j num; ba Poppet mnie | integes 5 Gane taaing ani campengy Imaginary Part : 9 Real Part : 5.25 Integer: 6 Structure and Pointers Poin. members are accessed using arroy Hinclude struct Point { int a, b; Output- > a! = Nh int main(){ struct Point pl = {1,2}; struct Point *p2 = &p1; print("%4d%d, p2 ra, pa py return 0; } Output: — 1,2 2 Structure and functions 5 ~ passed as function argument like at gga types. We cam pass individual meni a structure, and entre structure, Example— include struct student { char name[40}; int age; float salary; 8 void display(struct students); int main({ struct students S1; printf("Enter name:"); seanf(""6["\n]%*e", SI.name); rintf{"Enter age: "); scanfi"%d", &S1 age); Printf{"Enter salary; "); seanft"%6t", &SI.salary); display(S1); return 0; ve ta a Enter name: Rahul Enter age: 29 Enter salary: 9000 Displaying information Name : Rahul Age: 29 Salary : 9000 An Array of structures as function / arguments An array is a collection of similar data types. A group of structures of the exact definition is known as an array of structures, ple #include struct details { char name [10]; cchar sec [10] float per; void print_struct (struct details str_arr{)); int main) struct details student[3]={ {"Rahul", "A", 90.5}, {"Pramod", "B", 85.5}, {"Vibhav", "C", 98.5}, void print_struct(struct details str_arr[]) { inti; for(i=O; i<3; i++) printf{"Name:%s\n", str_arr[iJ.name); printf("Section:%s\n", str_arrfi]. see); printf("percentage: % .2fin",stt_art{i.per); printf("\n"); Union is user defined data type in C, which Stores a collection of different kinds of the data, Just like a structure. The keyword union is used to declare the union in C, Structure Union Strut Person ( Usion Person { chara: /sizeVoyte | ch Alot bie byte | oa: } obj: 4 obj: ‘memory allocation ‘sharing storage equal 10 ee gee T° [os 77 weir object) | YCFRLYCT, Syte 7 aitanion object) A byte Syntax Union UnionName { ‘/tmember definitions h Example— #include include union course{ char website [50]; char subject [50]; int price; kK ‘void main() { union course ¢; strepy(c.website,"yet.com"); printf("website: Yosin", e.website); strepy(c.subject, "The ¢ programming of Language”); a printf("Book Author: %s\n", ¢.subject); cprice = I © printf("Book Price: %adin", .price) inta; t char b; int main union test pl; pl.a=50; union test*p2 = & pl; printf("%6d %c", p2—> a, p2 > b) return 0; > Object Orichted Programming System— ‘ ors Class * Objects Encapsulation; Abstraction Inheritance Polymorphism ; Class— A class can be considered a container “ containing data variables and functions. * Human Being as a class~ e Body parts : Eyes ‘Nose Functions D Object Objects are the instances of the class, When a class is defined, no memory is allocated but when itis instantiated memory is allocated, Class person { ‘char name [30]; Sethe ead: | ‘a object take UP AEE IM memo, associated address Tike a rezopg 4 4 structure or union in C. ney Encaprlation- Keeping the gg. into single unit ikea capsule," "gy Consider a real life example of enc " company, there are different accounts section, finance section, etc. The finance section handles aig transaction and Keeps records of 41 be related to finance. . Ne D — Abstraction- It is a process of hin details from the user. Abstraction Data abstraction Control abstraction > 1 i a Example— ’ #include using namespace std.; class implement abstraction { private: inta, b; public; Void set (int x, inty){ anaes bey; } > void display(){ oUt << "ae" . using namespace std; class Yet public: ‘ © void fun(int x){ cout <<"value of X is” Example Operator Overloading Output— count:11 > In unary operator function no arguments should be passed. It works only with one class objects. In binary operator overloading function there should become argument to be passed. The operator overloading function must precede with friend keyword and declare a function class Scope, friend operator function takes two Parameter in a binary operator varies are Parameter in a unary operator ‘include using namespace std; class count{ private: int value; Public: count(): value(10) {} Void operator ++(){ +Hvalue; } Void display(){ cout<<"count < Default ‘Constructor A constr, Class CLASS_NAME { public: CLASS_NAME(Q) ‘aa } //other member functions i 2 Para-meterized Constructor j, a parameters in the constructor definijg: “ declaration. Syntax— class class Name 4 public: Class_Name(datatype variable) feces } 1 Example- #include using namespace std; class Rectangle{ Private: double length; double breadth; Public: Rectangle(double I,double b){ length = 1; breadth } double calculateArea() { return length * breadth; } B int maing Rectangle objl(10, 5); Rectangle obj2(13, 8) ‘cout<<"Area of Rectanglel:" ‘< using namespace std: class constructor{ Public: float area; constructor(){ arca=0; } constructor(int a, int b){ area =a*b; } void display(){ cout<<"Area:"< using namespace std; int count = 0; class Test{ public: Test(){ count; cout<<"\n No. of object created: \"< Syntax template #include template ‘Void swapp(swap & i, swap & j){ swap t; tis isi ist } int main, ' inte, char g,r; float x, y; ‘cout<<""n please irisert 2 integer values” cin eoe swapp(e, ); cout<<"\n Integer values after swapping” couts>p>>r; ‘swapp(g, 1); cout<<"\n character values after swapping:"; couts>x>>y, swapp(x, y); cout <<"\n the resultant float values after ‘Swapping:"; oUt < Class Template- A class template defines a family of classes. Syntax— template class name; template class vector { TV; public: vector(){ v= new T (size]; for(int J vector (T* a){ for(int i =0; iy{i] *y.vfij; return sum; } b int mainO{ int x[3] = {1, 2, 3}; int y[3] = {4, 5, 6}; vector v1; vector v2; VIE v2=yl intR= vita; cout<"Ra"< #include using namespace std; template void display (T'x){ cout<<"Template } void display(int x) { cout <<"Explicit display:"< Cateh(—exception_deelaration —) — (statement —j-»~ 2 Throw expressions You use a throw expression to indicate that your program has ‘encountered an exception. Syntax— a miei ea assignment_expression the type of assignment_expression can't be an incomplete type, abstract class type, or a pointer to an incomplete type other than the following types. ‘ void® const void * volatile void * const volatile void * The catch block that catches an exception must immediately follow the try block that throws the } extéption. The general form of these two blocks are throw exception; /block of statements — which detects and — throws an exception } Catch (type arg) { ---~ //block of statements that -- handles the exception ‘cout<<"\n we are inside the function\n"s if(x-y)!=0){ int R= 20-9); cout<<"Result+"< using namespace std; void divide(double x, double y){ cout<<"inside function\n"; try ifly==0.0) throw y; else COUt<<"Division="<> and << ;- We have used the objects cin and cout (pre defined in the ‘ostream file) for the input and output of data of various types. jin>>variable|>> variable2>>....>variabl This is the general format for reading data fom the keyword. arian ae ctr el ™ Ne and put() respectively to handle the single See te coarse: character inpuvoutput operations. using namespace std; 0) int main int size = 20; char city(20]; get(char*) get(void) Bet(char*) version assigns the input character to its argument fetums the input character. #include using namespace std; -<"Bnter City Name:\n"; cou cin>>city; cout<"City name," < finclude \ing namespace std; ‘/user defined manipulators stream & currency (ostream & output) { Output <<"Rs"; ‘return output; that define the file handling methods, Class Contents filebuf Its purpose is to set the file buffers to read and write, Contains ‘openprot constant used in the open() of file stream classes. Also contain close() and open() as members. fstreambase Provides operations common to the file stream. Serves as a base for ifstream ofstream Provides input operations. Contains open() with default input mode, Inherits the functions get), ind tellg0 getline(), read() seeke( tions from istream. Provides output operations. Constains open() with default output mode, Inherits put, seekp(), tellp() and ~—wrtie(), function from ostream, Provides support for simultaneous input and output operations. Contains open() with default input made. Inherits all the functions from istream and ostream classes through iostream, Opening and Closing a file The first method is usefull when we use only one file in the stream. The second method is used when we want to manage multiple files using one stream. Opening and closing a file “Using the constructor function of the class ‘Using the member function open() ofthe class, Opening files using constructor We know that a constructor is used to initialize an object while it is being created. Create a file stream object to manage the stream using the appropriate class, That is to say, the class ofstream is used to create the ‘output stream and the class ifstream to create the input stream. Initialize the file object with the desired filename. ffstream infile("data")://input only Example~ #include include cout<"Enter ifem name: char name[30]; ein>>names outf>> names outfe> cost; outfe>name; in>>cost; cout<<"\n"; cout<<"item name": < #include int main { ofstream fout; fout.open("Country"); fout<<"United States of America\n"; fout<<"United Kindom\n"; fout<<"south Korea\n" fout.close(); fout.open("Capital"); fout<<"Washinton\n"; fout<

You might also like