Showing posts with label Cpp. Show all posts
Showing posts with label Cpp. Show all posts

C++ Functions:Defining, Declaring, Calling, Arguments

C++ Functions:Defining, Declaring, Calling, Arguments
A function can be referred to be a section which is defined by a name within which multiple task takes place. The best example of the function is the main() function which we declare before we start writing any C++ program. To make a code more simplified and well defined and quick executable it is divided into sub parts of several functions to perform a specific task.
    Declaring a function consists of several parts better classified as the return type, name, parameters. Return type specifies the value which is to be returned by the function after executing all its codes its types are: void, int, float,double, long, char, string, class;etc. Name as stated is the name of the function defined. Parameters to be explained can be stated as the values passed through the function so that they can be used in execution without any further definition. Then finally comes the body of the function. Body as the word itself defines is the set of code executed within the scope of function.

  For example if we define any user defined function as max:
     
// function returning the max between two numbers
 
int max(int num1, int num2)  {
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}
 
Function declaration just doesn't mean defining it in the main() function. Defining a function means defining its prototype its parametric form and also calling it in the main function. But a very important point is to be noted, the parameters of a function are not that important. A function can be without parameter it is not an error but a procedure. It is advised to do both function prototype as well as definition because a function is normally declared to perform at different platforms and to be in the safer side it should be declared at the top only.
   Calling a function means invoking a set of arguments or giving the whole access of program in different hand. The parameters declared in the main function are passed through the function storing its returned value(if available) in a third variable and displaying the result. The parameters are used to invoke the function at particular location.

#include 
using namespace std;
 
// function declaration
int max(int num1, int num2);
 
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int ret;
 
   // calling a function to get max value.
   ret = max(a, b);
 
   cout << "Max value is : " << ret << endl;
 
   return 0;
}
 
// function returning the max between two numbers
int max(int num1, int num2)  {
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}
A function can be called in three different ways call by value, pointer, reference:
Call By Value: This method copies the original value provided to the function. In case any changes to be made to the parameters the original values are also effected.
 Call By Pointer: This deals with the address of the parameters provided. Any change applied to the values are affected to the parameters only not to the originals variables.
Call By Reference: This procedure copies the value of parameters into a temporary variable and any change made while execution is affected to the temp variable and the original is remained unchanged.
       By default C++ uses call by value to declare any function. To change our preference we need to declare the parameter in different forms as per requirements.Else while execution the original variables will come up with changed value and the original value will be lost.

File:Basic informations and funtions,Input/output procedures through C++

File:Basic informations and funtions,Input/output procedures through C++


So far in C++ we have come across iostream headers for input output purposes defining cin, cout functions. But as mentioned previously those input values were temporary and couldn’t be used for future access. But it is never so that we cannot store the inputted values for future access in fact the can be stored as a whole sort of document. The procedure is popularly known as files one can define a file, can be a text document also. As we declared a separate header file for input output purposes in the previous section in the same way we need to declare a header file to use a file. The header file is better known as fstream. Basically fstream function is a predefined class type and hence its object needed to be defined in the main function as follows:
Void main(){
Fstream f1;
F1.open(ios::out);
………
}
The above mentioned file is to open a predefined file. Where open() is a function used to open a file. It’s a keyword one can mention to. Similarly, to read a file we need to use the keyword read(). Files lead to a lot of memory leaks and so we need to close this class. Again for it we need to use a different keyword that is close().Files are mainly used to store information inputted by user in a document form. As the data is inputted through the keyboard it reaches the memory from the memory it moves to the file it is to be stored in. When the value is called to be displayed the vice versa process takes place that is the value first moves to the memory then the memory directs it to the monitor or the display the data to user. This includes a lot of background process one of the most vital one is conversion high level language to machine level language when user gives the input and the vice versa that is machine level to high level when user asks for display. A very good example of abstraction of data. A file can be opened in many forms, some of them are as follows:
      1.       ios::in->to open a file in input mode
      2.       ios::out->to open a file in output mode
      3.       ios::binary->to open a file in binary mode
      4.       ios::ate->to set the pointer of the file at the end
      5.       ios::app->it will write the output in the file from the end of the data without deleting the previous ones
      6.       ios::trunc->it will delete all previous data present in file and rewrite in it

C++ program to learn the basics of using a file

C++ program to learn the basics of using a file
This is a program that would help you to learn about the basics of a file through c++. This would teach ue that how can we acess a file, of how can we open it, how can we cloase it, how can we acess the documents present in a file. Its easy to use just install a c++ compiler copy this program to a new notepad and save it as a .cpp file and copy it in the bin of c++ compiler. Its all done now just open compiler search for the file open it and run it.

#include<stdlib.h>
#include<conio.h>
#include<fstream.h>
#include<ctype.h>
void main()
{   clrscr();
    fstream f1("mydata.dat",ios::in);
    char ch;
    int cnt=0;
    char c;
    if(!f1)
    {  cout<<"\n cannot open";
       getch();
       exit(-1);
    }
    cout<<"\n the text document is :";
    while (!f1.eof())
    {  f1.get(c);
       cout<<c;
    }
    f1.close();
    f1.open("mydata.dat",ios::in);
    while (!f1.eof())
    {  f1.get(ch);
       if(isalpha(ch))
       cnt++;
    }
    cout<<"\n number of alphabets are:"<<cnt;
    f1.close();
    getch();
}

C++ program to copy selective text from one file to another

C++ program to copy selective text from one file to another
This is a c++ program with a complete different aspect, it doesn't belong to the common topics. This program can create a file, simultaneously it will clear our concept of opening and closing the same file. Also will help us to know to how to open a file in input mode with the command 'ios::out'. The second switch option is provided to us to just to see what does the file contains in it. This option can help us to learn a different aspect of how o open a file in output mode that is with 'ios::in'. this can also clarify our concept of how to open and read a file simultaneously. The third switch option is to create a complete new file which will contain the vowels of file1. The file1 is ran in a loop if the pointer encounters a vowel then the vowel will be copied to the file2. At the end of the loop both the files have to be closed. As a result the third one will clarify that how can we close two files simultaneously. Basically, the third option teaches us how to deal with two files all together. This was a short discussion on the program.So, without wasting much time lets start with the program. The program is as follows:
#include
#include
#include
#include
#include
void main()
{
clrscr();
int n,j;
fstream ofile,afile;
char str[100];
char ch,ch1;
do
{
cout<<"\n\t1.Create Text\n\t2.Read from File\n\t3.create another file";
cout << "\n 4.Exit  ";
cin>>ch;
switch(ch)
{
    case '1' :
ofile.open("smp.txt",ios::out);
cout<<"\n Enter The Text ";
gets(str);
ofile<<str;
ofile.close();
break;
    case '2' :
char tmp1;
afile.open("smp.txt",ios::in);
while(!afile.eof())
{
afile.get(tmp1);
if(isalpha(tmp1))
{
  if (islower(tmp1))
  {
  if (tmp1=='a'||tmp1=='e'||tmp1=='i'||tmp1=='o'||tmp1=='u')
  cout << "\n Lower case vowel "<<tmp1;
  else
  cout<<"\n Lower case consonants "<<tmp1;
  }
  if (isupper(tmp1))
  {
  if (tmp1=='A'||tmp1=='E'||tmp1=='I'||tmp1=='O'||tmp1=='U')
  cout << "\n Upper case vowel "<<tmp1;
  else
  cout<<"\n Lower case consonants "<<tmp1;
  }
}

}
afile.close();
break;
    case '3' : ofile.open("smp.txt",ios::in);
afile.open("smp1.txt",ios::out);
char c;
while(ofile)
{
ofile.get(c);
c = tolower(c);
if (c=='a'||c=='i'||c=='e'||c=='o'||c=='u')
afile.put(c);
}
ofile.close();
afile.close();

    case '4' : exit(0);
}
cout<<"\n\t DO U want to continue ";
cin>>ch1;
  }while(ch1=='Y'||ch1=='y');
getch();
}

C++ program that would create display and count words,vowel and digits present in a file

C++ program that would create display and count words,vowel and digits present in a file
So are u searching for a c++ based program that would work on the properties of files,you have visited the right place. This is a program that works on the switch case property which handles a set of data in the file simultaneously. Through this program we shall learn how to use the different functions of a file like opening closing or updating it. A very helpfull program to learn about a file in dept. This is a c++ based program that would help in creating a file in the first switch option means it will give you an option of writing text documents in the file. The second switch option is to count the number of vowels or words or digits present in the text presently written in a pre created file. The vowels, words or digits are encountered with the help of "if" case once they are encoutered these are stored in a seperate variable and displayed seperately. The third switch option is to display contents present in the file. This was all about the program so without wasting much time lets start with the program. The disscused program is as follows:
#include<fstream.h>
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<process.h>
void main()
{
clrscr();
int n,j;
fstream ofile,afile;
char str[100];
char ch,ch1;

do
{
cout<<"\n\t1.Create Text\n\t2.Count vowels/words/digits\n\t3.Show Text\n\t4.Exit";
cin>>ch;
switch(ch)
{
    case '1' :
ofile.open("smp.txt",ios::out);
cout<<"\n Enter The Text ";
gets(str);
ofile<<str;
ofile.close();
break;
    case '2' :
char tmp1;
int v=0,d=0,w=0;
afile.open("smp.txt",ios::in);
while(!afile.eof())
{
afile.get(tmp1);

if(tmp1=='a'||tmp1=='e'||tmp1=='i'||tmp1=='o'||tmp1=='u')
v++;
if(isdigit(tmp1))
d++;
if(tmp1==' '||tmp1=='.')
w++;

}
afile.close();
cout<<"\n No of Vowels: "<<v;
cout<<"\n No of digits: "<<d+1;
cout<<"\n No of words: "<<w;
break;
    case '3' :
char tmp2;
afile.open("smp.txt",ios::in);
ofile.open("spl.txt",ios::out);
while(!afile.eof())
{
afile.get(tmp2);
if(tmp2==' ')
{
ofile<<'#';
}
else
{
ofile<<tmp2;
}
}
afile.close();
ofile.close();

cout<<"\nFormatted text:\t";
afile.open("spl.txt",ios::in);
while(afile)
{
afile.get(ch);
cout<<ch;
}
afile.close();
break;
    case '4' : exit(0);
}
cout<<"\n\t DO U want to continue ";
cin>>ch1;
  }while(ch1=='Y'||ch1=='y');
getch();
}

A program to give input and output in a file using switch cases

A program to give input and output in a file using switch cases
This is a c++ program created through switch case in which the user gets a switching option of creating a file and displaying the elements of the file. This program uses the funtions to open and cloase a file. Through this program a student can clarify his\her difficulties in defining a file. In this program new header files too are used such as process.h, fstream.h and few more. File is actually a very essential part of c++ so this can be clarified by this simple and basic program. A student can enhance his\her knowledge in file concept. So friends without wasting much of our time lets start with the program the program is as follows:

#include<fstream.h>
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
int n,j;
fstream ofile,afile;
char str[100];
char ch,ch1;

do
{
cout<<"\n\t1.Enter Text\n\t2.Show Text\n\t3.Exit";
cin>>ch;
switch(ch)
{
    case '1' :
ofile.open("smp.txt",ios::out);
cout<<"\nEnter The Text ";
gets(str);
ofile<<str;
ofile.close();
char tmp[20];
afile.open("smp.txt",ios::in);
ofile.open("vwl.txt",ios::out);
while(!afile.eof())
{
afile.getline(tmp,20,' ');
if(tmp[0]=='a'||tmp[0]=='e'||tmp[0]=='i'||tmp[0]=='o'||tmp[0]=='u')
{
ofile<<tmp;
ofile<<' ';
}
}
afile.close();
ofile.close();

break;
    case '2' : cout<<"\nFormatted text:\t";
afile.open("vwl.txt",ios::in);
while(afile)
{
afile.get(ch);
cout<<ch;
}
afile.close();
break;
    case '3' : exit(0);
}
cout<<"\n\t DO U want to continue ";
cin>>ch1;
  }while(ch1=='Y'||ch1=='y');
getch();
}

Program to generate report card of a student using functions like setw and gotoxy

Program to generate report card of a student using functions like setw and gotoxy
This is a c++ program that will take input of employees datails such as name, number and salary. Using switch case this will generate a report card of the student in tabular form. In this program we will learn about a new function "setw()" due to this a new header file is also introduced that is "process.h". this could teach one a good concept of how to create a report card of a student with proper arrangment. Without disscusing much lets work on the program, the program comes as follows:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<iomanip.h>
class employee
{
int eno;
char name[30];
float salary;
public :
void input()
{
cout << "Enter Employee Number ";
cin >>eno;
cout << "Enter name ";
gets(name);
cout << "Enter salary ";
cin >>salary;
}
void show()
{
cout << eno << setw(20)<<name<<setw(20)<<salary<<endl;
}
float rt_sal()
{
return salary;
}
}emp[10];
main()
{
int n,ch,i,j;
char choice;
do
{
clrscr();
cout << "1. For enter "<<endl;
cout << "2. For tabular report"<<endl;
cout << "3. For exit";
cin >> ch;
switch(ch)
{
case 1: cout << "Enter how many employees ";
cin >>n;
for(i=0;i<n;i++)
{
emp[i].input();
}

break;
case 2:
employee temp;
for (i=0;i<n;i++)
{
for(j=i;j<n-1;j++)
{
if (emp[j].rt_sal()>emp[j+1].rt_sal())
{
temp = emp[j];
emp[j]=emp[j+1];
emp[j+1]=temp;
}
}
}
gotoxy(6,6);
cout <<"Employee Number ";
gotoxy(26,6);
cout <<"Name";
gotoxy(46,6);
cout <<"Salary"<<endl;
int r = 8;
for(i=0;i<n;i++)
{
emp[i].show();
r++;
}

break;
case 3: exit(0);

}
cout << "\n Do U want to continue";
cin>>choice;
}while(choice == 'Y' ||choice =='y');

}

A program to clarify the use of files how to open how to close

A program to clarify the use of files how to open how to close
This is a c++ program made using files to generate a report of enggineering student. In this program it will take input of students full info like name, roll and marks.this program includes the concept of opening and cloasing of file. This program also includes a few extra header files and also the concept of switch case too. The program is as follows:
#include<fstream.h>
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<ctype.h>
class student
{
char name[30];
int rollno;
int marks;
public:
void input()
{
cout<<"\nEnter Name: ";
gets(name);
cout<<"Enter Rollno.: ";
cin>>rollno;
cout<<"enter marks";
cin>>marks;
}
void display()
{
cout<<"\n"<<name<<"\t"<<rollno<<"\t"<<marks<<"\t";
if(marks>=96)
cout<<"computer sc.";
else if(marks>=91&&marks<=95)
cout<<"Electronics";
else if(marks>=86&&marks<=90)
cout<<"Mechanical";
else if(marks>=81&&marks<=85)
cout<<"Electrical";
else if(marks>=76&&marks<=80)
cout<<"Chemical";
else if(marks>=71&&marks<=75)
cout<<"Civil";
else
cout<<"none";

}

};
void main()
{
clrscr();
student s;
int n,i,j;
fstream ofile,afile;

char ch,ch1;

do
{
cout<<"\n\t1.Add records\n\t2.Show Records\n\t3.Exit\n";
cout<<"Enter your choice: ";
cin>>ch;
switch(ch)
{
    case '1' :
ofile.open("st.dat",ios::app|ios::binary);
cout<<"\nEnter no. of records to be Entered: ";
cin>>n;
for(i=0;i<n;i++)
{
s.input();
ofile.write((char*)&s,sizeof(student));
}
ofile.close();
break;
    case '2' : cout<<"\nName\tRollno\tMarks\tStream";
afile.open("st.dat",ios::in);
while(afile)
{
afile.read((char *)&s,sizeof(student));
if (!afile)
break;
s.display();
}
afile.close();
break;
    case '3' : exit(0);
}
cout<<"\n\t DO U want to continue <Y/N>: ";
cin>>ch1;
  }while(tolower(ch1)!='n');
getch();

}

C++ program to generate an array and to work on it

C++ program to generate an array and to work on it
This is a c++ program which will teach us how to generate an 2D array. This program uses switch case with options such as enter, sort, search , display. This is a simple concept based program just to explain how to work with an array. The header files used are also quite basic. Program is as follows:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[20],n,i,j,temp;
char ch;

do
{
cout<<"\n\t1.Enter Array\n\t2.Sort Array\n\t3.Search\n\t4.Display\n\t5.Exit";
cin>>ch;
switch(ch)
{
case   '1':
cout<<"\nEnter no. of Elements (<=20): ";
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
break;
case   '2':
cout<<"\nThe Array is Now Sorted";
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
break;

case   '3':
cout<<"\nThe element to be searched";
int el;
cin>>el;
int first=0,last=n-1,mid=0,flag=0;
while(first<=last&&flag==0)
{
mid=(first+last)/2;
if(a[mid]==el)
{
flag=mid;
}
else if(a[mid]<el)
{
first=mid+1;
}
else
{
last=mid-1;
}

}
if(flag>0)
cout<<"\nThe Element is Found at: "<<++flag<<" in the sorted array";
else
cout<<"\n No such Element";
break;
case '4':
cout<<"\n";
for(i=0;i<n;i++)
cout<<a[i]<<ends;



}

}while(ch!='5');
}