Saturday, October 30, 2010

C++ programming:program to accept your name and print initials:how to display initials:name initials sample in C

In this tutorial, you will find a C++ program which accepts a name and prints initials for example if the input is "Vidhu Vinod Chopra", program will print "V.V.Chopra".
Following is a C++ program to accept a name and then print its initials. For Example If the input is "Mohandas Karamchand Gandhi"
This program will display M.K.Gandhi
Program Explanation:
Logic:
first print the first character by cout<<arr[0] and a dot by cout<<"." Then a loop runs till end of string and if it finds space, the next character is printed and a dot is printed. So in the above exmple if we input Mohandas Karamchand Gandhi, the output is M.K.G. Now a loop runs in array to go back till it finds a space. Then the statement cout<<\b\b" at line 22 erases 2 characters backside. It erases "G." Now a loop again runs from next character of the the last space till the end of the string. In our example it starts from G and prints Gandhi.
Line 9: input through gets() because cin does not input space


  1. #include<iostream.h>
  2. #include<stdio.h>
  3. #include<conio.h>
  4. void main()
  5. {
  6. clrscr();
  7. char arr[40];
  8. cout<<"Enter The Name "<<endl;
  9. gets(arr);
  10. cout<<arr[0]<<".";
  11. for(int i=0;arr[i]!='\0';i++)
  12. {
  13. if(arr[i]==' ')
  14. {
  15. cout<<arr[i+1]<<".";
  16. i++;
  17. }
  18. }
  19. if(arr[i]=='\0')
  20. {
  21. for(;arr[i]!=' ';i--);
  22. cout<<"\b\b";
  23. i++;
  24. for(;arr[i]!='\0';i++)
  25. {cout<<arr[i];}
  26. }
  27. getch(); 
  28. }


Output

Enter The Name
Mohandas Karamchand Gandhi
M.K.Gandhi 

how to use functions in C++: program using function to perform division,subtraction,multiply,sum of two numbers

Functions implement modularity which in turn implements a well structured programming. Modularity ensures better control of the program. Modularity is close to the real world so every OOP has modularity in it.

Consider a scenario:
  • 1. A manager in a mobile store alone manages all the operations i.e. marketing, inventory control, stock, accounting etc. The manager finds himself struggling with the store operations. The store has a bad reputation. The business is suffering
  • 2. A manager in a mobile store has individual supervisors for each operation i.e. marketing, inventory control, stock, accounting etc. The manager controls only the supervisors and the supervisors in turn control the operations. The mobile store is running smooth. The store has a good reputation. The business is flourishing
It is clear from above scenarios that a well structured organization runs smooth. In the same way a well structured program runs smooth and ensures efficiency.
If you are developing a calculator program. Rather than doing all the operations i.e. addition, subtraction, multiplication, division etc. in main() function only, make separate functions for each operation. It will have the benefits like:
  • 1. Program has modularity
  • 2. If a particular operation is wrong, you have to debug that function only.
  • 3. It is easy to understand the functions.
  • 4. Control is better
How to use functions in C++
Before making a function the following things should be decided
  • 1. Does the function return any value or return nothing means void
  • 2. Does the function have any arguments or parameters
  • 3. Meaningful name of the function
  • 4. The working of the function
A typical function to return the sum of two integer numbers can be like this:
int add(int,int);
The picture will be clearer by the programs in this tutorial.
Now remember these points that a function appears 3 times in a program. For example
  • 1. Function Prototype: A Function Prototype means an indication to compiler that a particular function will be used later in the program.
  • 2. Function Call: A Function Call means to call a function to work
  • 3. Function Definition: A Function Definition means the actual working of the function
There can be the following categories of the functions:
  • 1. Function without arguments and without return value
  • 2. Function with arguments and without return value
  • 3. Function with arguments and with return value
These things will be clearer by the programs in this tutorial.
Look at the following programs:

A program to show Functions without arguments and without return value

/* the following program has 4 functions with no arguments and no return type*/
  
#include<iostream.h>
#include<conio.h>
void add();  //function prototype of add() 
void subtract(); //function prototype of subtract()
void multiply(); //function prototype of multiply()
void division(); //function prototype of division()
void main()
{
clrscr();
int choice;
char ans;
cout<<"\nWant to see Menu Y or y for yes\n";
cin>>ans;
while(ans=='y'||ans=='Y')
{
cout<<"\nMENU\n";
cout<<"1. Add\n";
cout<<"2. Subtract\n";
cout<<"3. Multiply\n";
cout<<"4. Division\n";
cout<<"\Enter the Choice 1-4\n";
cin>>choice;
switch(choice)
{ case 1: add(); //function call to add()
   break;
  case 2: subtract(); //function call to subtract()
   break;
  case 3: multiply(); //function call to multiply()
   break;
  case 4: division(); //function call to division()
   break;
  default:cout<<"\nSorry Wrong Choice Try Again\n";
}
cout<<"\nWant to see Menu Y or y for yes\n";
cin>>ans;
}
getch();
}
void add()  //function definition of add()
{
int a,b;
cout<<"\nEnter two numbers a and b\n";
cin>>a>>b;
cout<<"Sum of the numbers a and b is"<<a+b;
}
void subtract()  //function definition of subtract()
{
int a,b;
cout<<"\nEnter two numbers a and b\n";
cin>>a>>b;
cout<<"a-b is"<<a-b;
}
void multiply()  //function definition of multiply()
{
int a,b;
cout<<"\nEnter two numbers a and b\n";
cin>>a>>b;
cout<<"Product of the numbers a and b is"<<a*b;
}
void division()  //function definition of division()
{
int a,b;
cout<<"\nEnter two numbers a and b\n";
cin>>a>>b;
cout<<"a/b is"<<a/b;
}

A program to show Functions with arguments and without return value

/* the following program has 4 functions with arguments and no return type*/
  
#include<iostream.h>
#include<conio.h>
void add(int,int);
void subtract(int,int);
void multiply(int,int);
void division(int,int);
void main()
{
clrscr();

int choice;
char ans;
cout<<"\nWant to see Menu Y or y for yes\n";
cin>>ans;
while(ans=='y'||ans=='Y')
{
int a,b;
cout<<"\nEnter two numbers a and b\n";
cin>>a>>b;
cout<<"\nMENU\n";
cout<<"1. Add\n";
cout<<"2. Subtract\n";
cout<<"3. Multiply\n";
cout<<"4. Division\n";
cout<<"\Enter the Choice 1-4\n";
cin>>choice;
switch(choice)
{ case 1: add(a,b);
   break;
  case 2: subtract(a,b);
   break;
  case 3: multiply(a,b);
   break;
  case 4: division(a,b);
   break;
  default:cout<<"\nSorry Wrong Choice Try Again\n";
}
cout<<"\nWant to see Menu Y or y for yes\n";
cin>>ans;
}
getch();
}
void add(int a,int b)
{
cout<<"Sum of the numbers a and b is: "<<a+b;
}
void subtract(int a,int b)
{
cout<<"a-b is: "<<a-b;
}
void multiply(int a,int b)
{
cout<<"Product of the numbers a and b is: "<<a*b;
}
void division(int a,int b)
{
cout<<"a/b is: "<<a/b;
}

A program to show Functions with arguments and with return value

/* the following program has 4 functions with arguments and return type */ 
#include<iostream.h>
#include<conio.h>
int add(int,int);
int subtract(int,int);
int multiply(int,int);
int division(int,int);
void main()
{
clrscr();
int choice;
char ans;
cout<<"\nWant to see Menu Y or y for yes\n";
cin>>ans;
while(ans=='y'||ans=='Y')
{
int a,b,c;
cout<<"\nEnter two numbers a and b\n";
cin>>a>>b;
cout<<"\nMENU\n";
cout<<"1. Add\n";
cout<<"2. Subtract\n";
cout<<"3. Multiply\n";
cout<<"4. Division\n";
cout<<"\Enter the Choice 1-4\n";
cin>>choice;
switch(choice)
{ case 1: c=add(a,b);
   cout<<"Sum of the numbers a and b is: "<<c;
   break;
  case 2: c=subtract(a,b);
   cout<<"a-b is: "<<c;
   break;
  case 3: c=multiply(a,b);
   cout<<"Product of the numbers a and b is: "<<c;
   break;
  case 4: c=division(a,b);
   cout<<"a/b is: "<<c;
   break;
  default:cout<<"\nSorry Wrong Choice Try Again\n";
}
cout<<"\nWant to see Menu Y or y for yes\n";
cin>>ans;
}
getch();
}
int add(int a,int b)
{
return a+b;
}
int subtract(int a,int b)
{
return a-b;
}
int multiply(int a,int b)
{
return a*b;
}
int division(int a,int b)
{
return a/b;
}

If anyone wants more clarification, he or she can post comments in this article. I will clarify the doubts.
Thanks for reading this article. 

Arrays in C++ programming:program that will store numbers or values in array? turbo c program how to accept 10 integer



Array Basics in C++ programming language:
Arrays are extremely important for every computer programming language including C++. There are situations when we need arrays in every programming language. In this chapter I will explain the basics of arrays in C++ programming language.
When we need an array?
When many variables are required of same data type and they all need to be treated the same way. For example: To store the first 10 even numbers we can declare an array of size 10.
Why we need array?
In the above example: rather than declaring 10 different integers, we can declare an array with no headache of memorizing 10 different variable names.
What is an array?
Array is a collection of variables of same data type under a single name.
How we use array?
There are different kinds of arrays: 1D, 2 D, 3D [D=Dimensions] for each data type. But here I am going to explain 1D array for integer or float data type. Char data type arrays have a different approach. I will explain them in the different chapters.
For example: if we need to store the first 10 even numbers, we can declare an array of integers like this:

rather than creating 10 variables like int a,b,c,d,e,f,g,h,I,j;
In memory 10 integers are declared in sequential memory locations:
In an array subscript or index always starts with ZERO. The subscripts are used by the compiler to locate the array item. For example to refer to the values 2,4,6,…,20 the compiler refers them in this way:
arr[0], arr[1], arr[2],… arr[9]
Try this code in C++ compiler.
//Program to store first 10 even numbers and print them
#include<iostream.h>
void main()
{
int arr[10], i,val;
/* In the following loop i is used to run the loop 10 times. i is initialized with ZERO because subscript starts with ZERO. val is used to store values starting from 2 and incrementing by 2 each time.*/
for(i=0,val=2; i<=9;i++,val=val+2)
arr[i]=val;
for (i=0;i<=9;i++)
cout<<arr[i]<<endl;
}
The Output of this program is:
2
4
6
8
10
12
14
16
18
20
The above C++ program is run in turbo c compiler.
The integer and float arrays have the same concept. The only difference is of their data types. integers store whole numbers while floats store decimal numbers.
Character arrays have a different concept which I have explained in this article:



character or char arrays as data structures in c: string reverse program and palindrome program using c programming

c programming arrays ---> data structures in c: char arrays in c programming
C programming arrays:
Arrays are important data structures in C.
Arrays are very much useful in situations when we need to store many variables of same data type and treat them similarly. For understanding c programming arrays and arrays as data structures in c, read the hub “Array Basics in C programming”
I am explaining here only character arrays in c programming.
What is an array?
An array is collection of similar type of data items.
And a character array is called a string.
Character arrays in C programming have a different concept from integer arrays or float arrays in C. Character arrays are declared in the same way as integer or float arrays but one thing that is different in character arrays is that a NULL character (‘\0’) is appended automatically at the end of the character array.
char arr[10];
the above statement declares a character array named arr with 10 continuous memory locations each occupying 1 byte because the base size of a character data type is 1 Byte. So the above array takes 10 Bytes in memory.
Now a string (group of character or a character array is called a string) is input in array by the following statement.
cin>>arr;
In the above input statement the string does not contain any whitespace because cin>> ends the string where a whitespace is encountered. If whitespaces are to be input then the following statement can be used
gets(arr);
do not forget to include stdio.h file to let the gets() function work
Suppose if the user inputs “HELLO” from the keyboard. The actual storage in memory would be :

c programming arrays: arrays as data structures in c : sample programs

A NULL Character(‘\0’) or string terminator is automatically appended after the last character of the string. It (‘\0’) marks the end of the string. This does not happen in integer or float arrays in C++.
Example 1:

c programming arrays: char arrays as data structures in c: sample program to reverse a string and count number of characters in string

/* program to input a string then count number of characters in string and

print the reverse of the string*/

#include<stdio.h> //for printf , scanf and other functions

#include<conio.h> //for clrscr() and getch()functions

void main()

{

clrscr();

char arr[10];

printf("Enter A String\n");

gets(arr);

for(int i=0;arr[i]!='\0';i++);//empty loop which does not have a body

printf("Length of the string is %d", i);

//now reverse print of the string

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

printf("%c",arr[i]);

getch();

}

c programming arrays: char arrays as data structures in c: sample program 1 output

OUTPUT:
Enter A String
MADAM
String is palindrome
Example 2:

c programming arrays: char arrays as data structures in c: sample program to check a string is palindrome or not

/*Program to input a string then check whether string is palindrome or not
A palindrome string is same as its reverse like RADAR, NITIN, MADAM */

#include<stdio.h>  //for printf, scanf,gets  and other functions
#include<conio.h>  //for clrscr() and getch()functions
void main()
{
clrscr();

char arr[10];
int i,j,flag=1;
printf("\n Enter A String\n");

gets(arr);

for(i=0;arr[i]!='\0';i++);//empty loop which does not have a body
for(j=0,i--;i>=0;i--,j++)//i moves backward and j moves forward
{
 if(arr[i]!=arr[j])
 {
  flag=0;
  break;
 }
}
if(flag==1)
printf("String is palindrome");
else
printf("String is not palindrome");

getch();
}

c programming arrays: char arrays as data structures in c: sample program 2 output

OUTPUT:
Enter A String
MADAM
String is palindrome

Pointers in C++:Pointers and array:program to reverse a string using pointers


Pointers in C++

Pointers in C++
Pointers in C++ are important concepts as pointers deal with memory addresses. If used wisely, pointers can enhance the efficiency of a program manifold but if used carelessly the program can run to crash. So the programmer should be very careful while using pointers in C++.
What is a pointer?
A pointer is a variable which contains memory address.
For example:
int var=10;
int *ptr; // a pointer of integer type named ptr is declared. See the syntax.
ptr=& var // ptr now holds the address of var using ‘&’ operator. ‘&’ operator is ‘address of’ operator
65524 is the address of var variable. ptr holds this address. 75678 is the address of ptr variable.
Remember a pointer can contain address only for that data type variable which is the type of the pointer itself.
For example:
int var1=2;
float var2=23.54;
int *ptr;
ptr=&var2; //Wrong! ptr is of int type and var2 is of float type
ptr=&var1; //Right. ptr is of int type and var1 is also int type
‘&’ and ’*’ operators
‘&’ is ‘address of’ operator which takes the address of its operand as we have seen in the above examples.
‘*’ operator is ‘value at address’ operator. ‘*’ operator takes any address as its operand and gives the value at that address. ‘*’ is also called ‘indirection operator’.
For example:
int var=10;
int *ptr; // a pointer of integer type named ptr is declared. See the syntax.
ptr=& var; // ptr now holds the address of var using ‘&’ operator. ‘&’ operator is ‘address of’ operator
65524 is the address of var variable. ptr holds this address. 75678 is the address of ptr variable.
Now see the following statements:
cout<<var; //prints 10
cout<<&var; // prints 65524
cout<<ptr; // prints 65524
cout<<&ptr; // prints 75678
cout<<*(&var); // prints 10
cout<<*ptr; // prints 10
In the last two statements ‘*’ operator is used to print value.
Pointer Arithmetic :
Only addition and subtraction is possible in pointers. The calculation is done as following:
int var=10;
int *ptr;
ptr=& var;
From the previous diagram, 65524 is the address of var variable. ptr holds this address. 75678 is the address of ptr variable.
If we write
ptr =ptr+3;
it means add 3 times the the size of integer because ptr is of integer type.
So ptr will contain 65524+3x2
ptr will contain 65530.
If ptr is a float pointer and has address 65545
And we write
ptr= ptr-5;
it means subtract 5 times the size of float because ptr is of float type
ptr=65545-5x4
ptr=65525
Pointers and Arrays
 An array itself is a pointer which holds the address of its first cell. In an array all the elements are stored in contiguous memory locations.
Look at the following program

array and pointer

#include<iostream.h>
void main()
{
int  arr[5]={23,45,65,44,89};
 cout<<arr<<"\n";
 cout<<arr+2<<"\n";
 cout<<*arr<<"\n";
 cout<<*(arr+2)<<"\n";
}  



In the above program an integer array named arr is created and initialized with 5 integer numbers.
The statements will give the output as:
cout<<arr<<"\n";             will print 65524
 cout<<arr+2<<"\n";       will print 65528
 cout<<*arr<<"\n";         will print 23
 cout<<*(arr+2)<<"\n"; will print 65
Now let us see another example.
Following is a program to accept a string and print the string in reverse using pointer. It also counts the length of the string.

pointer and string

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 char str[10];
 cout<<"\nEnter A String\n";
 cin>>str;
 char *ptr;
 int len=0;
 for(ptr=str;*ptr!='\0';ptr++,len++);
 cout<<"String Length Is: "<<len<<"\n";
 cout<<"\Reverse String: ";
 for(--ptr;ptr>=str;ptr--)
 cout<<*ptr;
 getch();
}

OUTPUT:
Enter A String
hello
String Length Is: 5
Reverse String: olleh
Program Explanation:
First Loop: ptr is initialized with str which gives the address of first cell of str. ptr is forwarded by the statement ptr++. The loop runs till ptr does not find ‘\0’. In an array the memory locations are contiguous so ptr forwards to the next cell. A variable len is used to store the length of the string. Each time the loop runs, len is increased by 1. This is an empty loop. When the loop terminates ptr holds the address of the cell containing ‘\0’. len contains the string length.
Second Loop: ptr is initialized with the address of the last character. It runs till the first character of the string. It is moved backwards. Each time loop runs the characters are printed in the reverse order on the screen.
So we have seen that pointers in C++ are very useful. Pointers in C++ are also used for dynamic memory allocation.
“new” operator is used for dynamic memory allocation. See the syntax.
int *ptr = new int;
and this ptr can be released from memory using delete operator. see the syntax.
delete ptr;