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

Notes for the Doucmentation

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

Notes for the Doucmentation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Array:-

An array is a collection of a fixed number of values of a single type. For example: if you want to store
100 integers in sequence, you can creaate an array for it.

int a[100];

#include<stdio.h>

int main(){

int i;

int a[] = {2, 3, 4};

for(i = 0 ; i < 3 ; i++){

printf("%d\t",a[i]);

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

#include<stdio.h>

int main()

int arr[4];

int i, j;

printf("Enter array element\n");

for(i = 0; i < 4; i++)

scanf("%d", &arr[i]); //Run time array initialization

printf("Display array details\n");

for(j = 0; j < 4; j++)

printf("%d\n", arr[j]);

}
----------------------------

#include<stdio.h>

main(){

int i,j,s;

printf("Enter array size");

scanf("%d", &s);

int arr[s];

printf("Enter array element");

for(i = 0; i < s; i++)

scanf("%d", &arr[i]); //Run time array initialization

for(j = 0; j < s; j++)

printf("%d\n", arr[j]);

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

#include<stdio.h>

int main()

int marks[10], i, n, sum = 0, average;


printf("Enter n: ");

scanf("%d", &n);

for(i=0; i<n; ++i)

printf("Enter number%d: ",i+1);

scanf("%d", &marks[i]);

sum += marks[i];

average = sum/n;

printf("Total is = %d", sum);

printf("Average = %d", average);

return 0;

Example 4:- multidimentional array

#include<stdio.h>

main()

int arr[3][4];

int i, j;

printf("Enter array element\n");

for(i = 0; i < 3;i++){

for(j = 0; j < 4; j++) {

scanf("%d", &arr[i][j]);
}

printf("Array display details. .\n");

for(i = 0; i < 3; i++) {

for(j = 0; j < 4; j++) {

printf("%d \t", arr[i][j]);

printf("\n");

Example 5:-

#include<stdio.h>

int main()

float a[2][2], b[2][2], c[2][2];

int i, j;

printf("Enter elements of 1st matrix\n");

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

printf("Enter a%d%d: ", i+1, j+1);

scanf("%f", &a[i][j]);
}

printf("Enter elements of 2nd matrix\n");

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

printf("Enter b%d%d: ", i+1, j+1);

scanf("%f", &b[i][j]);

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

c[i][j] = a[i][j] + b[i][j];

printf("\nSum Of Matrix:");

for(i=0; i<2; ++i)

for(j=0; j<2; ++j)

printf("%.1f\t", c[i][j]);

if(j==1)

printf("\n");

return 0;
}

================================

A palindrome number is a number that is same after reverse:-

#include<stdio.h>

int main()

int n,r,sum=0,temp;

printf("enter the number=");

scanf("%d",&n);

temp=n;

while(n>0)

r=n%10;

sum=(sum*10)+r;

n=n/10;

if(temp==sum)

printf("palindrome number ");

else

printf("not palindrome");

return 0;

Fibonacci Series in C

#include<stdio.h>
main(){

int n1=0,n2=1,n3,i,number;

printf("Enter the number of elements:");

scanf("%d",&number);

printf("\n%d %d",n1,n2);

for(i=2;i<number;++i) {

n3=n1+n2;

printf(" %d",n3);

n1=n2;

n2=n3;

#include<stdio.h>

int main(){

int n,i,m=0,k=0;

printf("Enter the number to check prime:");

scanf("%d",&n);

m=n/2;

for(i=2;i<=m;i++) {

if(n%i==0) {

k=1;

printf("Number is not prime");

}
}

if(k==0) {

printf("Number is prime");

==========================

An array is a variable that can store multiple values.

#include<stdio.h>

void smallnum(int[],int);

void main(){

int i, arr[10];

printf("Enter 10 integers:\n");

for(i=0;i<10;i++)

scanf("%d", &arr[i]);

smallnum(arr, 10);

void smallnum(int arr1[], int n){

int i;

int min=arr1[0];
for(i=0;i<n;i++) {

if(arr1[i] < min){

min=arr1[i];

printf("\nThe smallest number is: %d", min);

The body of do...while loop is executed at least once. Only then, the test expression is evaluated.

#include<stdio.h>

void main()

int num;

char rep;

do

printf("Enter a number: ");

scanf("%d", &num);

if (num > 10)

printf("The number is greater than 100, enter another number. \n");

continue;

printf("The square of the number is ");


printf("%d \n", num * num);

printf("Do you want to enter another number(y/n)?");

rep = getche();

printf("\n");

} while (rep != 'n');

#include<stdio.h>

int main()

int i, j, num[5], temp;

printf("Enter marks of five students:\n");

for(i = 0; i <= 4; i++) {

scanf("%i", &num[i]);

for(i = 0; i <= 4; i++) {

for(j = i+1; j <= 4; j++){

if(num[i] < num[j]) {

temp = num[j];

num[j] = num[i];

num[i] = temp;
}

else{

continue;

printf("The marks in descending order are:\n");

for(i = 0;i <= 4; i++){

printf("%i \n", num[i]);

#include<stdio.h>

main(){

char sentence[85], character;

int ctr;

ctr = 0;

printf("Enter text. Press Enter at the end.\n");

do{

character = getchar();

sentence[ctr] = character;

ctr++;

} while(character != '\n');

sentence[ctr] = '\0';

printf("%s \n", sentence);

==========
#include<stdio.h>

main()

int num,i,j,k;

printf("ENTER THE NUMBER OF ROWS: ");

scanf("%d",&num);

for(i=1;i<=num;i++) // * (i,j) used for base code * //**

for(k=1;k<=num-i;k++){ // * use the (K) variable is space * //**

printf(" ");

for(j=1;j<=2*i;j++)

printf("*");

printf("\n");

//// next shape code //*

for(i=num-1; i>0;i--)

for(k=1;k<=num-i;k++){

printf(" ");

for(j=1;j<=2*i;j++)
{

printf("*");

printf("\n");

Functions in C:- (C function is a self-contained block of statements that can be executed repeatedly
whenever we need it.)

The function provides modularity.

The function provides reusable code.

In large programs, debugging and editing tasks is easy with the use of functions.

The program can be modularized into smaller parts.

Separate function independently can be developed according to the needs.

Two types of functions:-

a)Built-in(Library) Functions:

The system provided these functions and stored in the library. Therefore it is also called Library
Functions.

e.g. scanf(), printf(), strcpy, strlwr, strcmp, strlen, strcat etc.

To use these functions, you just need to include the appropriate C header files.

b)User Defined Functions:

These functions are defined by the user at the time of writing the program.

Part of Function:

1)Function Prototype (function declaration)


2)Function Definition

3)Function Call

Function Prototype:

syntax -

dataType functionName (Parameter List)

Example-

int addition();

Function Definition:-

Syntax -

returnType functionName(Function arguments){

//body of the function

Example:-

int addition()

Calling function in C:-

#include<stdio.h>
int addition();

int main()

int answer;

answer = addition();

printf("The addition of the two numbers is: %d\n",answer);

return 0;

int addition()

int num1 = 10, num2 = 5;

return num1+num2;

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

Type - Call by Value

Description:-

The actual parameter is passed to a function.

New memory area created for the passed parameters, can be used only within the function.

The actual parameters cannot be modified here.

Type - Call by Reference

Description:-

Instead of copying variable; an address is passed to function as parameters.


Address operator(&) is used in the parameter of the called function.

Changes in function reflect the change of the original variables.

1) Call by value

#include<stdio.h>

int addition(int num1, int num2);

int main(){

int answer;

int num1 = 10;

int num2 = 5;

answer = addition(num1,num2);

printf("%d\n""%d\n",num1,num2);

printf("The addition of two numbers is: %d\n",answer);

printf("%d\n""%d\n",num1,num2);

return 0;

int addition(int num1,int num2){

num1=55;

num2=33;

return num1 + num2;

}
-----------------------------------------------

Call by Reference:-

#include<stdio.h>

int addition(int *num1, int *num2);

int main()

int answer;

int num1 = 10;

int num2 = 5;

printf("%d\n""%d\n",num1,num2);

answer = addition(&num1,&num2);

printf("The addition of two numbers is: %d\n",answer);

printf("%d\n""%d\n",num1,num2);

return 0;

int addition(int *a,int *b)

*a=33;

*b=22;

return *a + *b;

}
------------------------------

1) with argument return type --int total(int i,int j)

2) without argument return type--int total()

3) with argument no return type-- void total(int i,int j)

4) without argument no return type -- void total()

1)No arguments passed and no return Value:-

#include <stdio.h>

void checkPrimeNumber();

int main()

checkPrimeNumber();

return 0;

void checkPrimeNumber()

int n, i, flag=0;

printf("Enter a positive integer: ");

scanf("%d",&n);

for(i=2; i <= n/2; ++i)


{

if(n%i == 0)

flag = 1;

if (flag == 1)

printf("%d is not a prime number.", n);

else

printf("%d is a prime number.", n);

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

2)No arguments passed but a return value

#include <stdio.h>

int getInteger();

int main()

int n, i, flag = 0;

n = getInteger();

for(i=2; i<=n/2; ++i)

if(n%i==0){

flag = 1;

break;

}
}

if (flag == 1)

printf("%d is not a prime number.", n);

else

printf("%d is a prime number.", n);

return 0;

int getInteger()

int n;

printf("Enter a positive integer: ");

scanf("%d",&n);

return n;

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

3)Argument passed but no return value

#include <stdio.h>

void checkPrimeAndDisplay(int i);

int main()

int n;
printf("Enter a positive integer: ");

scanf("%d",&n);

checkPrimeAndDisplay(n);

return 0;

void checkPrimeAndDisplay(int n)

int i, flag = 0;

for(i=2; i <= n/2; ++i)

if(n%i == 0){

flag = 1;

break;

if(flag == 1)

printf("%d is not a prime number.",n);

else

printf("%d is a prime number.", n);

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

1)Argument passed and a return value

#include <stdio.h>
int checkPrimeNumber(int n);

int main()

int n, flag;

printf("Enter a positive integer: ");

scanf("%d",&n);

flag = checkPrimeNumber(n);

if(flag == 1)

printf("%d is not a prime number",n);

else

printf("%d is a prime number",n);

return 0;

int checkPrimeNumber(int n)

int i;

for(i=2; i <= n/2; ++i)

if(n%i == 0)

return 1;

return 0;

}
C Pointers

The pointer in C language is a variable which stores the address of another variable.

Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

int n = 10;

int *p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.

#include<stdio.h>

main(){

int number=50;

int *p;

p=&number;

printf("Address of p variable is %x \n",p);

printf("Value of p variable is %d \n",*p);

=====================================

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use %u to display the
address of a variable.

#include<stdio.h>

int main(){

int number=50;

printf("value of number is %d, address of number is %u",number,&number);

return 0;

===================================

Pointer Program to swap two numbers without using the 3rd variable.

#include<stdio.h>

int main(){

int a=10,b=20,*p1=&a,*p2=&b;

printf("Before swap: *p1=%d *p2=%d",*p1,*p2);

*p1=*p1+*p2;

*p2=*p1-*p2;

*p1=*p1-*p2;

printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);

return 0;

===================================

#include<stdio.h>

main ()

{
int a = 10;

int *p;

int **pp;

p = &a; // pointer p is pointing to the address of a

pp = &p; // pointer pp is a double pointer pointing to the address of pointer p

printf("address of a: %x\n",p); // Address of a will be printed

printf("address of p: %x\n",pp); // Address of p will be printed

printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be
printed

printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer
stoyred at pp

===================================

=============================Files in C:-

C files I/O functions handle data on a secondary storage device, such as a hard disk.

C fopen function is used to open an existing file or create a new file.

syntax:-

FILE *fopen( const char * filePath, const char * mode );

1)r -Opens an existing text file.

2)w - Opens a text file for writing if the file doesn't exist then a new file is created.

3)a - Opens a text file for appending(writing at the end of existing file) and create the file if it
does not exist.

4)r+ - Opens a text file for reading and writing.

5)w+ - Open for reading and writing and create the file if it does not exist. If the file exists then
make it blank.

6)a+ - Open for reading and appending and create the file if it does not exist. The reading will start
from the beginning, but writing can only be appended.
Example.1

#include<stdio.h>

int main()

FILE *fp;

fp = fopen("fileName.txt","w");

return 0;

Ex.2

#include<stdio.h>

main() {

FILE *fp;

fp = fopen("test.txt", "w+");

fprintf(fp, "This is testing for fprintf...\n");//fprintf() write data into the file

fputs("This is testing for fputs...\n", fp);

fclose(fp);

Ex.3

#include<stdio.h>

int main( )

FILE *fp ;

char ch ;
fp = fopen("test.txt","r") ;

while ( 1 )

ch = fgetc ( fp ) ;

if ( ch == EOF )

break ;

printf("%c",ch) ;

fclose (fp ) ;

Ex.5

#include<stdio.h>

int main(){

FILE *fp;

char text[300];

fp=fopen("myfile2.txt","r");

printf("%s",fgets(text,200,fp));

fclose(fp);

C++ PROGRAMMING

C++ Polymorphism

Polymorphism is an important concept of object-oriented programming. It simply means more than


one form. That is, the same entity (function or operator) behaves differently in different scenarios.
C++ Function Overloading

In C++, we can use two functions having the same name if they have different parameters (either
types or number of arguments).

#include <iostream>

using namespace std;

int sum(int num1, int num2) {

return num1 + num2;

double sum(double num1, double num2) {

return num1 + num2;

int sum(int num1, int num2, int num3) {

return num1 + num2 + num3;

int main() {

cout << "Sum 2 = " << sum(5.5, 6.6) << endl;

cout << "Sum 1 = " << sum(5, 6) << endl;

cout << "Sum 3 = " << sum(5, 6, 7) << endl;

return 0;

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

C++ Operator Overloading:-


In C++, we can overload an operator as long as we are operating on user-defined types like objects or
structures.

We cannot use operator overloading for basic types such as int, double, etc.

Operator overloading is basically function overloading, where different operator functions have the
same symbol but different operands.

And, depending on the operands, different operator functions are executed.

// C++ program to overload ++ when used as prefix

#include <iostream>

using namespace std;

class Count {

private:

int value;

public:

// Constructor to initialize count to 5

Count() : value(5) {}

// Overload ++ when used as prefix

void operator ++() {

value = value + 1;

void display() {

cout << "Count: " << value << endl;


}

};

int main() {

Count count1;

// Call the "void operator ++()" function

++count1;

count1.display();

return 0;

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

C++ Function Overriding:-

In C++ inheritance, we can have the same function in the base class as well as its derived classes.

// C++ program to demonstrate function overriding

#include <iostream>

using namespace std;

class Base {

public:

virtual void print() {

cout << "Base Function" << endl;

};
class Derived : public Base {

public:

void print() {

cout << "Derived Function" << endl;

};

int main() {

Derived derived1;

// Call print() function of Derived class

derived1.print();

return 0;

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

C++ Virtual Functions:-

In C++, we may not be able to override functions if we use a pointer of the base class to point to an
object of the derived class.

Using virtual functions in the base class ensures that the function can be overridden in these cases.

Thus, virtual functions actually fall under function overriding.

// C++ program to demonstrate the use of virtual functions

#include <iostream>

using namespace std;


class Base {

public:

virtual void print() {

cout << "Base Function" << endl;

};

class Derived : public Base {

public:

void print() {

cout << "Derived Function" << endl;

};

int main() {

Derived derived1;

// pointer of Base type that points to derived1

Base* base1 = &derived1;

// calls member function of Derived class

base1->print();

return 0;

Scope Resolution:-

In C++, scope resolution operator is ::

// access a global variable

// using :: when there is a local


// variable with same name

#include<iostream>

using namespace std;

int x; // Global x

int main() {

int x = 10; // Local x

cout << "Value of global x is " << ::x;

cout << "\nValue of local x is " << x;

return 0;

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

Ex.2

// to define a function outside a class

#include<iostream>

using namespace std;

class A {

public:

// Only declaration

void fun();

};

// Definition outside class using ::

void A::fun() {

cout << "fun() called";

int main() {

A a;

a.fun();

return 0;

C++ virtual function:-


A C++ virtual function is a member function in the base class that you redefine in a derived class. It is
declared using the virtual keyword.

It is used to tell the compiler to perform dynamic linkage or late binding on the function.

There is a necessity to use the single pointer to refer to all the objects of the different classes.

A 'virtual' is a keyword preceding the normal declaration of a function.

When the function is made virtual, C++ determines which function is to be invoked at the runtime
based on the type of the object pointed by the base class pointer.

Rules of Virtual Function:-

1) Virtual functions must be members of some class.

2) Virtual functions cannot be static members.

3) They are accessed through object pointers.

4) They can be a friend of another class.

5) A virtual function must be defined in the base class, even though it is not used.

6) The prototypes of a virtual function of the base class and all the derived classes must be identical.
If the two functions with the same name but different prototypes, C++ will consider them as the
overloaded functions.

7) We cannot have a virtual constructor, but we can have a virtual destructor

Consider the situation when we don't use the virtual keyword.


// CPP program to illustrate

// concept of Virtual Functions

#include<iostream>

using namespace std;

class base {

public:

virtual void print()

cout << "print base class\n";

void show()

cout << "show base class\n";

};

class derived : public base {

public:

void print()

cout << "print derived class\n";

void show()

cout << "show derived class\n";

};
int main()

base *bptr;

derived d;

bptr = &d;

// Virtual function, binded at runtime

bptr->print();

// Non-virtual function, binded at compile time

bptr->show();

return 0;

C++ Files

* The fstream library allows us to work with files.

* To use the fstream library, include both the standard <iostream> AND the <fstream> header file:

Example

#include <iostream>

#include <fstream>

* There are three objects included in the fstream library,

which are used to create, write or read files:


Object/Data Type Description

ofstream Creates and writes to files

ifstream Reads from files

fstream - A combination of ofstream and ifstream:

creates, reads, and writes to files

Create and Write To a File:-

To create a file, use either the ofstream or fstream object, and specify the name of the file.

To write to the file, use the insertion operator (<<).

Example 1

#include <iostream>

#include <fstream>

using namespace std;

int main() {

ofstream MyFile("e://ajai333.txt");

MyFile << "Files can be tricky, but it is fun enough!";

MyFile.close();

===================

#include <iostream>

#include <fstream>

using namespace std;


int main() {

ofstream MyFile;

MyFile.open("e://ajai333.txt", ios::app);

MyFile << "i am going to multi national software company at chennai";

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

Example 2

#include <iostream>

#include <fstream>

using namespace std;

int main() {

string myText;

ifstream MyReadFile("D://filename.txt");

while (getline (MyReadFile, myText)) {

cout << myText;

MyReadFile.close();

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

There are some mode flags used for file opening. These are:
1). ios::app: append mode

2). ios::ate: open a file in this mode for output and read/write controlling to the end of the file

3). ios::in: open file in this mode for reading

4). ios::out: open file in this mode for writing

5). ios::trunk: when any file already exists, its contents will be truncated before file opening

General Functions used for FileHandling:-

1). open(): To create a file

2). close(): To close an existing file

3). get(): to read a single character from the file

4). put(): to write a single character in the file

5). read(): to read data from a file

/* File Handling with C++ using ifstream & ofstream class object*/

/* To write the Content in File*/

/* Then to read the content of file*/

#include <iostream>

/* fstream header file for ifstream, ofstream,

fstream classes */

#include <fstream>

#include <iostream>

using namespace std;

int main() {

ofstream fout;

string line;

// by default ios::out mode


fout.open("d://sample.txt");

while (fout) {

getline(cin, line);

if (line == "-1")

break;

fout << line << endl;

fout.close();

ifstream fin;

// by default open mode = ios::in mode

fin.open("d://sample.txt");

// Execute a loop until EOF (End of File)

while (fin) {

// Read a Line from File

getline(fin, line);

// Print line in Console

cout << line << endl;

fin.close();

return 0;

=========================================================

========================================================

Exception Handling:-

The two most common types of errors are:

Logical errors
Syntactic errors

An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an attempt to
divide by zero.

throw - A program throws an exception when a problem shows up. This is done using a throw
keyword.

catch - A program catches an exception with an exception handler at the place in a program where
you want to handle the problem. The catch keyword indicates the catching of an exception.

try - A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Ex.1

#include<iostream>

using namespace std;

int main()

try {

throw 6;

catch (int a) {

cout << "An exception occurred!" << endl;

cout << "Exception number is: " << a << endl;

Ex.2
#include<iostream>

using namespace std;

void division(int var1, int var2)

if (var2 == 0) {

throw "Division by Zero not allowed.";

cout<<var1/var2;

int main()

int a = 30;

int b = 0;

double d = 0;

try {

division(a, b);

catch (const char* e) {

cout << e << endl;

return 0;

===============

#include<iostream>
using namespace std;

void division(int var1, int var2)

if (var2 == 0) {

throw 22;

cout<<var1 / var2;

int main()

int a = 30;

int b = 0;

try {

division(a, b);

catch (char* er) {

cout << er << endl;

catch (...) {

cout << "Default Exception\n";

return 0;

You might also like