FUNC.CPP

• 1: #include <iostream.h>


• 2: int Add (int x, int y) {4:


• 3: cout << "In Add(), received " << x << " and " << y << "\n";


• 4: return (x+y); }


• 5: int main() { cout << "I'm in main()!\n";


• 6: int a, b, c;


• 7: cout << "Enter two numbers: ";


• 8: cin >> a;


• 9: cin >> b;


• 10: cout << "\nCalling Add()\n";


• 11: c=Add(a,b);


• 12: cout << "\nBack in main().\n";


• 13: cout << "c was set to " << c;


• 14: cout << "\nExiting...\n\n";


• 15: return 0; }


Output: 


• I'm in main()!
 
• Enter two numbers: 3 5
 
• Calling Add()
 
• In Add(), received 3 and 5
 
• Back in main().
 
• c was set to 8
 
• Exiting... 

Demonstrating call to a function

1: #include <iostream.h>
 
• 2: // function Demonstration Function
 
• 3: // prints out a useful message
 
• 4: void DemonstrationFunction()
 
• 5: { cout << "In Demonstration Function\n"; }
 
• 6: // function main - prints outa message, then
 
• 7: // calls DemonstrationFunction, then prints
 
• 8: //out a second message.
 
• 9: int main() { cout << "In main\n" ;
 
• 10: DemonstrationFunction();
 
• 11: cout << "Back in main\n";
 
• 12: return 0; } 

Output for Function call : 

• In main
 

• In Demonstration Function
 

• Back in main  

Using cout

Cout is a function as like as printf. We use cout in c++ and printf in C. Cout is easy to use. 

1: #include <iostream.h>
 
• 2: int main()
 
• 3: { cout << "Hello there.\n";
 
• 4: cout << "Here is 5: " << 5 << "\n";
 
• 5: cout << "The manipulator endl writes a new line to the screen." <<endl;
 
• 6: cout << "Here is a very big number:\t" << 70000 << endl;
 
• 7: cout << "Here is the sum of 8 and 5:\t" << 8+5 << endl;
 
• 8: cout << "Here's a fraction:\t\t" << (float) 5/8 << endl;
 
• 9: cout << "And a very very big number:\t" << (double) 7000 * 7000 << endl;
 
• 10: cout << "Don't forget to replace Jesse Liberty with your name...\n";
 
• 11: return 0;}

Output using cout: 

Hello there.
 
•Here is 5: 5
 
• The manipulator endl writes a new line to the screen.
 
• Here is a very big number: 70000
 
• Here is the sum of 8 and 5: 13
 
• Here's a fraction: 0.625
 
• And a very very big number: 4.9e+07
 
• Don't forget to replace Jesse Liberty with your name...
 • Jesse Liberty is a C++ programmer! 

58. Evolution of C++

• C was extended to create C++ by Bjarne Stroustrup


• Features needed to facilitate object-oriented programming was provided in C++


• C++ is the predominant language for commercial software development


• C++ is a superset of C. The leap from C to C++ is very significant


• Any legal C program is a legal C++ program.


• To get the full benefit of C++, programmers need to learn a new way of
conceptualizing and solving programming problems

57. Four Pillars of Object-Oriented Programming

* Encapsulation 
* Data Hiding
* Inheritance
* Polymorphism


C++ Fully supports object-oriented programming.

Encapsulation: -Being a self contained unit.

Data hiding: -An object can be used without knowing about its internal data members.

Encapsulation and Data Hiding:

* C++ supports encapsulation and data hiding through
* The creation of user-defined types, called classes.
* A well-defined class acts as a 


  -  Fully encapsulated entity--it is used as a whole unit.
  - The actual inner workings of the class are hidden.
  - Users of a well-defined class do not need to know how the class works.
  - They just need to know how to use it.

Inheritance and Polymorphism: 

* Inheritance

 
  - a new object type, which is an extension of an excising type can be declared
  - This new subclass is said to derive from the existing type and is sometimes called a derived type.
  - C++ supports reuse through inheritance.

* Polymorphism

 
  - refers to the same name taking many forms.
  - C++ Supports the idea that different objects do "the right thing" through.
  - Function polymorphism and class  polymorphism

56. Difference between pointer and reference


POINTER
1.   Its not necessary to initialize the pointer at the time of declaration. Like
      Code:
     int a=10;
     int *p=&a; //it is not necessary
Another way is:
   Code:
   int a=10;
   int *p;
   p=&a;
2.   You can create the array of pointer.
3.   You can assign NULL to the pointer like
   Code:
   int *p=NULL; //valid
4.   You can use pointer to pointer.

REFERENCE:

1.   Its necessary to initialize the Reference at the time of declaration. Like
      Code:
      int &a=10
      int &a; //Error here but not in case of pointer.
2.   You can not create the Array of reference.
3.   You can not assign NULL to the reference like.
    Code:
    int &a=NULL; //Error
4.   You can not use reference to reference.

55. Difference between C and C++

Ø  In case of C, the data is not secured while the data is secured(hidden) in C++
Ø  C is a low-level language while C++ is a middle-level language
Ø  C is function-driven while C++ is object-driven
Ø  C++ supports function overloading while C does not
Ø  We can use functions inside structures in C++ but not in C.
Ø  The NAMESPACE feature in C++ is absent in case of C
Ø  The standard input & output functions differ in the two languages
Ø  C++ allows the use of reference variables while C does not

54.Difference between class and structure

1.   Classes are usually used for large amounts of data, whereas structs are usually used for smaller amount of data.
2.   Classes could be inherited whereas structures no
3.   A structure couldn't be Null like a class.
4.   A structure couldn't have a destructor such as class.
5.   A structure can't be abstract, a class can.
6.   You can't use sizeof with classes but you can with structures.
7.   The structure can't contain a volatile field wheatears the class does.
8.   classes support polymorphism, whereas structures do not.

51. Inline function

Inline functions are an imperative feature of C++ and are frequently used with classes. Inline functions are functions where the call is made to inline functions. The actual code then gets placed in the calling program. In a program when we call a function the program jumps to the address of the function and when it reaches the end of the function it comes back. This jumping actually involves much more and takes time. But when an inline function is called the compiler will replace the call with the function code. So in reality in that place there will be no function call, only the code of the function. No jumping needed to different addresses. The general format of inline function is as follows:

inline datatype function_name(arguments)

Example:
The following code creates and calls an inline function:
#include<iostream.h>
inline int average(int a, int b)
{
   return (a + b) / 2;
}
void main()

{
   int result = average(12, 14);

   cout << "The average of number 12, 14 is " << result << "\n";
   getch();

}
It is most important to know that the inline specifies is a request, not a command, to the compiler. If, for various reasons, the compiler is unable to fulfill the request, the function is compiled as a normal function.

50. What is macros in C

A macro is a fragment of code which has been given a name. When we use the name of macro in program, it is replaced by the contents of the macro. You may define any valid identifier as a macro, even if it is a c keyword. There are two types of macros. One is object-like macros and another is function-like macros. Object-like macros do not take parameters; function-like macros do. The generic syntax for declaring an identifier as a macro of each type is:
For object-like macros:
 #define <identifier> <replacement token list>
For example:
#include<stdio.h>
#include<conio.h>
#define sum a+b
void main()
{
Clrscr();
int a=5,b=10,c;
c=sum; //if we give the semicolon (;)when we define the macro; then we cannot give the semicolon when we write the name of identifier. If we give the semicolon when we define the macro, then we give the semicolon when we write the name of identifier in program
printf(“The sum of a+b is: %d”,c);
getch();}
For function-like macros:
#define <identifier> (<parameter list>) <replacement token list>
For example:   
#include<stdio.h>
#include<conio.h>
#define square(x) x*x;
Void main()
{
Clrscr();
int i=2,j;
j=square(i) //Here is no semicolon because I give the semicolon when I define the macros.
printf(“The value of j is: %d”,j);
getch();
}
 The #undef directive removes the definition of a macro.
Written by arnob;

49. Reverse an integer by using Recursion

#include<stdio.h>
#include<conio.h>
int re (int,int,int*,int);
void main()
{
clrscr();
int i,j=0,n[5],k=0,m;
printf("Enter a number: ");
scanf("%d",&i);
m=re(i,j,n,k);
for(j=0;j<m;j++)
printf("%d",n[j]);
getch();
}
re(int i,int j,int *n,int k)
{
if(i==0) return k;
j=i%10;
n[k]=j;
i=i/10;
re(i,j,n,k+1);
program written by arnob;
48. Writer a C program which store students name, id and gpa. and make a serach option that when we enter a name for search, if the name is there then show that students name,id and gpa. If the name is not there then show NOT FOUND!.



#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
char name[40];
char id[20];
char gpa[5];
}stu[100];
void main()
{
clrscr();
int i=0,j,n;
char name[40];
printf("How many students informatio: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the name: ");
scanf("%s",stu[i].name);
printf("\nEnter the id: ");
scanf("%s",stu[i].id);
printf("\nEnter the gpa: ");
scanf("%s",stu[i].gpa);
clrscr();
}
printf("\nEnter the search name: ");
scanf("%s",name);
for(i=0;i<n;i++)
{
clrscr();
j=strcmp(name,stu[i].name);
if(j==0)
{
printf("\nName :");
puts(stu[i].name);
printf("\nId :");
puts(stu[i].id);
printf("\nGPA :");
puts(stu[i].gpa);
break;
}
}
if(j!=0)
printf("Not found !");
getch();
}

program written by arnob;

47. Find the hight and second hight number by using RECURSION

/* Find the hight number by using recursion */

#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int n,a[100],i,j;
printf("How many nmber you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number",i+1);
scanf("%d",&a[i]);
}
int hight(int,int,int,int*);
j=hight(n,0,0,a);
printf("The hight number is %d",j);
return 0;
}

int hight(int n,int i,int m,int *a)
{
if(i>n) return m;
if(m<a[i])
m=a[i];
hight(n,i+1,m,a);
}


/* Find the second hight number by using recursion */

#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int n,a[100],i;
printf("How many nmber you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number",i+1);
scanf("%d",&a[i]);
}
int hight(int,int,int,int,int*);
hight(n,0,0,0,a);
printf("The second hight number is %d",a[1]);
return 0;
}

int hight(int n,int i,int j,int k,int *a)
{
if(i>n-1) return 0;

for(j=i+1;j<n;j++)
if(a[i]<a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
}
hight(n,i+1,j,k,a);
}


written by anrob.

46. Find the even number from a array by using RECURSION

Question: Get input a array frmon user and find the hight number. You can only use one array and can not use any globel variable.

Ans: If you can use more then one array then you can easyle find the hight number by only using for loop. But you can not use more then one array. So you can solve this problem by using recursion.

/*program for find the even number */

#include<stdio.h>
#include<conio.h>

int main()
{
clrscr();
int a[100];n,i;
printf("How many number you want to input: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d number: ");
scanf("%d",&a[i]);
}
void chk_evn(int,int,int*,int*)
chk_evn(0,0,&n,a);
for(i=0;i<n;i++)
printf("%d",a[i]);
return 0;
}

void chk_evn (int i,int j,int *n,int *a)
{
if(i==n){*n=j;return n;}
if(a[i]%2==0)
a[j++]=a[i];
chk_evn(i+1;j,n,a);
}

program written by arnob

45. Passing 2-D Array to a Function by using pointer

There are two ways in which er can pass a 2-D array to a function by using pointer. These are illustrated in the following program.

/*Two ways of accessing a 2-D array*/
#include<alloc.h>
void main()
{
int a [3][4]={
               1,2,3,4,
               5,6,7,8,
               9,0,1,6
             };
clrscr();
display(a,3,4);
show(a,3,4);
}

display(int *q,int row, int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d",*(q+i*col+j));
printf("\n");
}
printf("\n");
}

show(int (*q)[4],int row, int clo)
{
int i,j;
int *p;

for(i=0;i<row;i++)
{
p=q+i;
for(j=0;j<col;j++)
printf("%d",*(p+j));
printf("\n");
}
printf("\n");
}

And here is the output...

1234
5678
9016

1234
5678
9016

In the display() finction we have collected the base address of the 2-D array being passed to it in an ordinary int pointer. Thenthrough the two for loops using the ex[ression *(q+i*col+j) we have reached the appropriate element in the array. Suppose i is equal to 2 and j is equal to 3, then we wish to reach the element give this element or not. The exprewssion *(q+i*col+j) becomes *(4001+2*4+3). This turns out to be *(4001+11). Since 4001 is address of an integer, *(4001+11) turns out to be *(4023). Value at this address is +. This is indeed same as a[2][3]. A more general formula for accessing each array element would be:

*(base address + row *no of columns +column no)

In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration
int (*q)[4];

To begin with, q hods the base address of the xeroth 1-D array, i.e 4001. This address is then assigned to p, an int pointer, and then using this pointer all elements of the xeroth 1-D array are accessed. Next thime through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D arry. This is because, q is a pointer to zeroth 1-D array and adding 1 to it would given us the address of the next 1-D array. This address is once again assigned to p, and using it all elements of the next 1-D arraY are accessed. 

Arnob

44. Array of pointer

The way there can be an array of ints or an array of floats, similarly there can be an array of pointers. Since a pointer vcariable always contains an address, an array of pointers would be nothing but a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses. All rules that apply to an ordinary array apply in toto to the array of pointers as well. I think a program would clarify the concept.

/*Array of pointer*/
#include<stdio.h>
void main( )
{
int *arr[4]; /* array of integer pointers */
int i=31,j=5,k=19,l=17,m;

arra[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
for (m=0;m>3;m++)
printf("\n%u",*(arr[m]));
}

And here is the putput...
31
5
19
71

Here is another program...

#include <stdio.h>
#include <conio.h>
main() {
  clrscr();
  int *array[3];
  int x = 10, y = 20, z = 30;
  int i;
  array[0= &x;
  array[1= &y;
  array[2= &z;
  for (i=0; i< 3; i++) {
    printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),
        array[i]);
  }
  getch();
  return 0;
}

output......


Taken from "Understanding Pointers IN C"

43. Pointer to an array

The way we can have a pointer to an integer or a pointer to a float, can we also have a pointer to an array? The answer is yes. The Declaration of a pointer to an integer is int *p; but the declaration of a pointer to an array is int (*q)[4]; That means q is a pointer to an array of 4 integer. Pointer to an array, use in two dimensional arrays. When we increase a pointer to an integer it points the next element, but when we increase the pointer to an array it skip those element which you give in the bracket. In this declaration int (*q)[4]; it skip 4 element. Let us use this pointer to an array in a program. Here it is…

/*Program for pointer to an array*/

#include<stdio.h>
#include<conio.h>

void main( )
{
int a[][4]= {
              5,7,5,9
              4,6,3,1
              2,9,0,6
            };
int *p;
int (*q)[4];

p=(int*)a;
q=a

printf(“\n %u %u”,p,q);
p++;
q++;
printf(“\n %u %u”,p,q);
getch();\
};

And here is the output…

65500 65500
65502 65508

To begin with both p and q contain the same address 65500. However, p is an integer pointer, whereas q is a pointer to an array of 4 integers. Hence on incrementing p it points to the next integer, whereas, q starts pointing to the next 1-D array of 4 integers. Pointer to an array is vary useful while passing a 2-D array to a function, as we would see in the next section.

Written by Arnob
Ref: “Understanding Pointers In C”

42. Dynamic Memory Allocation

In this tutorial you will learn about C Programming - Dynamic Memory Allocation. Suppose we have a program which can store 100 student’s marks. If you need to store 75 students’ marks in this program you can, but some memory are not uses. But if you need store 110 students’ marks in this program you can not do it. You need increase array size. So it is big problem when any body use this program because he or she can not increase the array size. If we have a way that when the program runs in that time we give the array size, then that problem can not come. Yes we have a way that when we run the program we give the student number then the program make array size in its own. The way is dynamic memory allocation. In this system we can use two functions they are malloc and calloc. They both do the same work. They are often known as “Dynamic memory allocation functions”. Let us now see a program, which uses the concept of dynamic memory allocation.

/*Program for dynamic memory allocation */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int n,avg,I,*p,sum=0;

printf(“\n Enter the number of student: ”);
scanf(“%d”,&n);

p=(int*) malloc (n*2)
if(p==NULL)
{
printf(“\n Memory allocation unsuccessful”);
exit();
}
for(i=0;i<n;i++)
scanf(“%d”,(p+i));

for(i=0;i<n;i++)
sum=sum+*(p+i);

avg=sum /n;
printf(“Average marks=%d”,avg);
getch();
}
Note: here (n*2) means that the number of (student * 2). We want to convert the student number in byte. The number of student is integer so we multiply with 2(integer =2 byte). If it is float then we multiply with 4(float=4 byte).

Here, we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc( ). malloc( ) returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p since malloc( ) returns a void pointer we have telecasted it into an integer pointer. IN the first for loop using simple pointer arithmetic we have stored the marks entered from keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks.

The calloc( ) functions works exactly similar to malloc( ) except for the fact that is needs tow arguments. For example,
Int *p
P=(int*) calloc (10,2);

Here 10 mean the number of student. And 2 indicates that we wish to allocate memory for storing integers.


Written by Arnob.
Reference: “Understanding Pointers In C”

free counters