0% found this document useful (0 votes)
15 views

Internship Report C and C++

Internship papers of c and c++

Uploaded by

raj929504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
15 views

Internship Report C and C++

Internship papers of c and c++

Uploaded by

raj929504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 31
ACKNOWLEDGEMENT | have taken efforts in this industrial training. However, it would not have been possible without the kind support and help of many individuals and organizations, I would like to extend my sincere thanks to all of them. A Special thanks to computer science department for giving me the opportunity to pursue my industrial training in the institute. I would like to express my special gratitude and thanks to industry persons for giving us such attention and time. NAME. — :-SAHIL KUMAR ROLL NO. :- 22EE64LE ABSTRACT lam a student of Government Engineering College, bhojpur and studying in EE 3" semester. As a part of our degree we have undergone in a training process for 8 weeks. Present is the age of computers and technologies. Practical knowledge has its own importance. Without practical knowledge one cannot be specialized in one’s field. We have automated the practical knowledge of institutes and their working in the project. CONTENTS S.No Content Page No. 1 Brief history of C 5 2 Data types in C 6 3 Operations in C 9 4 Types of loop 11 5 C-Functions 12 6 Pointers 7 File Handling in C 14 8 OOP-Introduction 16 9 Constructor and 18 Destructor 10 Inheritance 23 11 Polymorphism 26 12 Exception Handling in 29 C++ 13 Templates in C++ 30 14 File Handling in C++ 31 Brief History of C Programming Language 9C is a general-purpose programming language which features economy of expression, modern control flow and data structures, and a rich set of operators. C is not a "very high level" language, nor a "big" one, and is not specialized to any particular area of application. But its absence of restrictions and its generality make it more convenient and effective for many tasks than supposedly more powerful languages. > The history of C programming language is quite interesting. C was originally designed for and implemented on the UNIX operating system on the DEC PDP-Il, by Dennis Ritchie. C is the result of a development process that started with an older language called BCPL. BCPL was developed by Martin Richards, and it influenced a language called B, which was invented by Ken Thompson. B led to the development of C in the 1970s. >For many years, the de facto standard for C was the version supplied with the UNIX operating system. In the summer of 1983 a committee was established to create an ANSI (American National Standards Institute) standard that would define the C language. The standardization process took six years (much longer than anyone reasonably expected). ‘The ANSI C standard was finally adopted in December 1989 Uy u u woe 5 Constants and Variables in C language Constant > As the name suggests the name constants is given to such variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc. Every constant has some range. The integers that are too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under the signed bit, the range of an int varies. from -128 to +127 and under the unsigned bit, int varies from 0 to 255. Variables in c In programming, a variable is a container (storage area) to hold data. To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location Data types in C Lanquage > Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we can use in our program. These datatypes have different storage capacities. C language supports 2 different type of data types: 1. Primary data types: These are fundamental data types in C namely integer(int), floating point(float), character(chan) and void. Ld Derived data types: Derived data types are nothing but primary datatypes but a little twisted or grouped together like array, stucture, union and pointer. These are discussed in details later. Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x can hold only integer values. Every variable which is used in the program must be deciared as what data-type itis. Integer type: > Integers are used to store whole numbers. Size and range of Integer type on 16-bit machi Type Sizo(bytes) Range intor cigned int 2 32,768 10 92767 unsigned int 2 01065595 ‘short int or signed short int 1 +128 10 127 unsigned short int 1 00255 Jong into signed long int 4 -2,A47 483,648 to 2,147 483,647 unsigned long int 4 0 to 4,294,967,205 Floating point type Floating types are used to store real numbers. Size and range of Integer type on 16-bit machine Type Size(bytes) Range Float 4 346-35 10 3.46435 Double 8 1.7308 t0 1.764308 Jong double 10 346-4932 to 11644932 Character type: Character types are used to store characters value. Size and range of Integer type on 16-bit machine Type Size(bytes) Range char or signed char 1 12810 127 unsigned char 1 010.255 void typi void type means no value. This is usually used to specify the type of functions which returns nothing. We will get acquainted to this datatype as we start leaming more advanced topics in C language, like functions, pointers ete. C Programming Operators > C Arithmetic Operators An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables). > Clncrement and Decrement Operators programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators ate unary operators, meaning they only operate on a single operand. > C Assignment Operators ‘An assignment operator is used for assigning a value to a variable. The most common assianment operator is= > C Relational Operators A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. > C Logical Operators ‘An expression containing logical operator retums either 0 or 1 depending upon whether expression results true oF false. Logical operators are commonly used in decision making in C programming. Operator Meaning Example Logical AND. True only talloperands are ‘ite =5 and d'=2 then, expression ((¢==5) 88 aa te (@5)) equals 100. Logical OR. True only ifeither one operand te = 5 and d =2 then, expression ((e==5) || fT is true (45) equals to 1 ! Logical NOT. True only ifthe operand is 0 C Bitwise Operators During computation, mathematical operations like: addition, subtraction, multiplication, civision, etc are converted to bi-level which makes processing faster and saves power. Bitwise operators are used in C programming to perform bit-ievel operations. Operators Meaning of operators & Bitwise AND 1 Bitwise OR “ Bitwise exclusive OR - Bitwise complement << Shift left > ‘Shift right ‘Operator ‘Associativity 00> == Teft tonight Fan (ype aire0F Right ole T% Left right + Left to right 5, j<3, k=3 ) ‘exp3 — increment/decrement (Example: ++i, j-, +k) while (condition) { statements; }where, condition might be a>5, i<10 do { statements; } while (condition);where, condition might be a>5, i<10 Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. a Instead of declaring individual variables, such as number0, numbert, .... and number99, you dectare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. C - Functions A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat void main() { int num: num = square(4); print#(“%ed" pum) } imt square(int nt) { int x = nl * nt: return(x): R } What are Pointers? A pointer is a variable whose value is the address of another variable, ie., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is — type *var-name; Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations — int /* pointer to an integer */ double /* pointer to a double */ float /* pointer to a float */ char /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. address of "a" <_ _LSOe | 7 ptr — pointer name 10 address of pointer ()1o concatenate two strings, memepy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc. Basics of File Handling in C ‘So far the operations using C program are done on a prompt / terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are: Creation of a new file (fopen with attributes as “a” or “at” or “w" or “w++") Opening an existing file (fopen) Reading from file (fscanf or fgetc) Writing to a file (fprintf or fputs) Moving to a specific location in a file (fseek, rewind) Closing a file (fclose) 7. FILE *filePointer; 8.So, the file can be opened as ON PwNVs 9. filePointer = fopen(“fileName.txt”, “w”) opening a file FILE * filePointer; filePointer = fopen(“fileName.txt”, “r”); fscanf(filePointer, "%s %s Xs %d", stri, str2, str3, year); writing a file FILE *filePointer ; filePointer = fopen(“fileName.txt”, “w”); fprintf(filePointer, "%s %s %s %d", "We", "are", " » 2012); “ Why C++? + Popular and relevant (used in nearly every application domain): — end-user applications (Word, Excel, PowerPoint, Photoshop, Acrobat, Quicken, games) operating systems (Windows 9x, NTT, XP; IBM’s K42; some Apple OS X) large-scale web servers/apps (Amazon, Google) central database control (Israel's census bureau; Amadeus; Morgan- Stanley financial modeling) communications (Alcatel; Nokia; 800 telephone numbers; major transmission nodes in Germany and France) numerical computation / graphics (Maya) device drivers under real-time constraints + Stable, compatible, scalable C vs. C++ + C++ is C incremented (orig., “C with classes”) + C++ is more expressive (fewer C++ source lines needed than C source lines for same program) + C++ is just as permissive (anything you can do in C can also be done in C++) + C++ can be just as efficient (most C++ expressions need no run-time support; ‘C++ allows you to — manipulate bits direetly and interface with hardware without regard for safety or ease of comprehension, BUT hide these details behind a safe, clean, elegant interface) + C++ is more maintainable (£000 tines of code ~ even brute forve, spaghetti code will work; 100,000 lines of code — need good structure, or new errors will be introduced as quickly as old errors are removed) What is object-oriented? + Encapsulation “black box” — internal data hidden Ge= + Inheritance espe related classes share implementation and/or interface + Polymorphism ability to use a class without knowing its type “C++ is an object-oriented language” C+ provides mechanisms that support object-oriented style of programming What is OOPS? Object Oriented Programming is a programming concept that works on the principle that objects are the most important part of your program. It allows users create the objects that they want and then create methods to handle those objects. Manipulating these objects to get results is the goal of Object Oriented Programming. Object Oriented Programming popularly known as OOP, is used in a modern programming language like Java 1) Class 2) Object 3) Inheritance 4) Polymorphism 5) Encapsulation 16 1) Class The class is a group of similar entities. It is only an logical component and not the physical entity. For example, if you had a class called “Expensive Cars’ it could have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be price or speed of these cars. While the methods may be performed with these cars are driving, reverse, braking etc. 2) Object An object can be defined as an instance of a class, and there can be multiple instances of a class in a program. An Object contains both the data and the function, which operates on the data. For example - chair, bike, marker, pen, table, car, eto. 3) Inheritance Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the parent object. It's creating a parent-child relationship between two classes. It offers robust and natural mechanism for organizing and structure of any software. 4) Polymorphism Polymorphism refers to the ability of a variable, object or function to take on multiple forms. For example, in English, the verb run has a different meaning if you use it with a /aptop, a foot race, and business. Here, we understand the meaning of run based on the other words used along with it.The same also applied to Polymorphism. 5) Encapsulation Encapsulation is an OOP technique of wrapping the data and code. In this OOPS concept, the variables of a class are always hidden from other classes. It can only be accessed using the methods of their current class. For example - in school, a student cannot exist without a class. wv Constructors and Destructors in C++ Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. While defining a contructor you must remeber that the name of constructor will be same as the name of the class, and contructors will never have a retum type. Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator. Constructor Destructor vs. 1 L Types of Constructors in C++ Constructors are of three types: 4. Default Constructor 2. Parametrized Constructor 3. Copy COnstructor Default Constructors Default constructor is the constructor which doesn't take any argument. it has no parameter. ‘Syntax: class_name(parameter1, parameter2, ...) i Parameterized Constructors These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument. Copy Constructors These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object. We will study in detail later. Destructors in C++ Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope. Destructor will not have any argument The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it. a References Reference: alternate name for an object (alias) #9t 5; int ga = ‘There is no (Now use ‘a’ as *b’) null reference No reference to sntba= L; a temporary int<6a; Syntax confusing int* c = 6a; Basically a const \ dereferenced pointer eet address of” with no operations (not a reference) Confusing syntax int a, b; * means + multiplication, or intc=a*b; . * pointer, or int* d = &a; + dereference pointer i = *d; int e = *d; & means + get address of, or ints £ = a; . + reference Same symbol, different meanings! vss yy Pass by X by pointer value pase \ by void £(int-a, int* b, inte) reference ‘ // changes to a are W07 reflected outside the function // changes to b and c AR reflected outside the function nain() ‘ DOES int a,b, ¢: does NOT make a copy £(a, &b, c); make acopy Lo +f tt J PBP and PBR are different syntax for the sante functionality Argument passing / return + Pass / return by value calls copy constructor ~ performance penalty for structs and classes (emporary objects) + Pass / return by reference or pointer does not call copy constructor pays inputs by const reference never pass inputs by “plain” reference void update(inté a); update(2); // error pass outputs by pointer int x= 1; next(x); // should not change x int x= 1; next(éx); // may change x — ok to return a ref, or const ref an C++ function mechanisms Overloaded function names ~ Cleaner and safer print (int); print (float) ; But beware print (int); print (int#) ; print (0); Default parameters void print (int a, int D0, int o=0); + Operator overloading Matrix operator+=(const Matrixé other) ; + Implicit conversion operator operator int() const (} // converts to int Provides convenient syntax, but potentially dangerous so use sparingly Namespaces + Namespace expresses logical grouping + using declaration — Don’t use global using except for transition to older code — Ok in namespace for composition — Ok in function for notational convenience + Namespaces are open + Unnamed namespaces restrict code to local translation unit + Aliases (namespace ShortName = LongName; ) C++ Inheritance Inheritance + Subclass derived from base class + Two classes should pass the “ISA” test: derived class is a base class shape ( Circle : public shape { + Class hierarchy: means of building classes incrementally, using building blocks (subclass becomes base class for someone else) + Facilitates code reuse In C++, inheritance is @ process in which one object acquires all the properties and behaviors of its parent ‘object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class. In C++, the class which inherits the members of another class Is called derived class and the class whose members are inherited is called base class. The derived class is the specialized class for the base class. Advantage of C++ Inheritance Code reusability: Now you can reuse the members of your parent class. So, there is no need to define the member again. So, less code is required in the class. Types of Inheritance C++ supports five types of inheritance: © Singl © Multiple inheritance © Hierarchical inheritance © Multilevel inheritance © Hybrid inheritance heritance C++ Single Inheritance ‘Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base dass. ‘Where 'A" is the base class, and 'B" is the derived class. C++ Multilevel Inheritance Multilevel inheritance is a process of deriving a class from another derived class. ‘Multiple inheritance Is the process of deriving a new class that inherits the attributes from two or more asses, C++ Multiple Inheritance C++ Hybrid Inheritance Hybrid inheritance is a combination of more than one type of inheritance. C++ Hierarchical Inheritance Hierarchical inheritance is defined as the process of deriving more than one class from a base class. Polymorphism in C++ Polymorphism + Polymorphism — “ability to assume different forms” — one object acts like many different types of objects (eg, Shape*) ~ getting the right behavior without knowing the type — manipulate objects with a common set of operations + Two types: ~ Run-time (Virtual functions) ~ Compile-time (Templates) ‘The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call o a member function will cause a different function to be executed depending on the type of abject that invokes the function. Polymorphism Compile Tim Run Time Virtual functions + Function of derived class is called even if you have only a pointer to the base class File.h File. cpp class Shape void Funel () { { virtual void Draw(); Circle mycire; vi Func? (smycirc) ; y class Circle : public Shape { void Func2(Shape* s) virtual void Draw(); { Me s->Draw() ; // calls Circle::Draw() y Virtual Function A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don’t want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. ar How a virtual function works Shape vtable Circle vtable shape member variables vtable ptr circle member vari variables _ vaEN Pure virtual function + Pure virtual function Function intentionally undefined Same penalty as regular virtual function + Abstract class class Shape { virtual void Draw() = 0 on ~ Contains.at least one pure virtual function — Cannot instantiate; must derive from base class and override pure virtual function — Providesan interface (Geparates interface from implementation) + Advice: virtual functions should always be pure virtual — Le, “Make non-leafelasses abstract” (Scott Meyers, Item 29) ~ Also, “Don'tderive from concrete classes” (Herb Sutter, p. 137) + More advice: Make virtual functions private (Herb Sutter, p. 134). This separates the override implementation details from the public interface. Pure Virtual Functions It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. Exceptions ¢ Error handling in C: — Half of code is error handling — Dangerous: Easy for programmer to forget to check return value void Fune() ( int ret; ret = OpenDevice(); if (ret I= 0) error("Unable to open device”); ret = SetParams(); if (ret != 0) error(*Unable to set params”); One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: a) Synchronous, b) Asynchronous(Ex:which are beyond the program’s control, Disc failure etc.). C++ provides following specialized keywords for this purpose. tty. represents a block of code that can throw an exception. caich: represents a block of code that is executed when a particular exception is thrown. throw. Used to throw an exception. Also used to list the exceptions that a function throws, but doesn't handle itself. Exceptions (cont.) + Error handling in C++: — try-catch blocks safer — separate “real code” from error handling code void Funct) ( try opendevice () + Setparans () } catch (const MyExceptions e) { @-ReportToUser () 7 } catch Gd ¢ abort (2); ) ) void OpenDevice() « » if (bad) throw MyException (“Cannot open device”) ; Templates in C++ ‘A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software ‘company may need sort!) for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. (C++ adds two new keywords to support templates: template’ and typename’. The second keyword can always be replaced by keyword ‘class’. How templates work? ‘Templates are expanded at compiler time. This is like macros. The difference is, compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of same function/class. Compile interally generates snl aks below code ‘template int mviotint x tat y) 7 return (x > y)? x ys ? Temymaxi x, Ty) ci return («> y)? xy) > int nain|) ae ( cout << myfaxcint>(3, 7) <£ endl cout << maxcchare("0', ©°) << endl; return o: Compiler internally generates > tnd adds below code char myttex(char x, char y) gturn (x > y)? x: 5 Streams — flush, fprintf, fscanf, sprintf, sseanf ~ fgets, gete = CH ~ cout, File Handling through C++ Classi In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream header file ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write fromito files. Now the first step to open the particular file for read or write operation. We can open file by 1. passing file name in constructor at the time of object creation 2. using the open method For e.g. Open File by using constructor ifstream (const char” filename, ios_base:openmode mode = ios_base::in); ifsiream fin(tilename, openmode) by default openmode = ios::in ifstream fin(‘filename’); Open File by using open method Calling of default constructor ifstream fin; aL fin.openttilename, openmode) fin.open(‘filename’); les istream ostream —____ lostream Ifstream ofstream co fstream END OF REPORT 32

You might also like