Share this:


Strings

In C++ strings are really arrays, but there are some different functions that are used for strings, like adding to strings, finding the length of strings, and also of checking to see if strings match.

The definition of a string would be anything that contains more than one character string together. For example, “This” is a string. However, single characters will not be strings, though they can be used as strings.
Strings are arrays of chars. Static strings are words surrounded by double quotation marks.
“This is a static string”
To declare a string of 50 letters, you would want to say:
char string[50];
This would declare a string with a length of 50 characters. Do not forget that arrays begin at zero, not 1 for the index number. In addition, a string ends with a null character, literally a ‘’ character. However, just remember that there will be an extra character on the end on a string. It is like a period at the end of a sentence, it is not counted as a letter, but it still takes up a space. Technically, in a fifty char array you could only hold 49 letters and one null character() at the end to terminate the string.
TAKE NOTE: char *array;
Can also be used as a string. If you have read the tutorial on pointers, you can do something such as:
array = new char[256];

which allows you to access array just as if it were an array. Keep in mind that to use delete you must put [] between delete and array to tell it to free all 256 bytes of memory allocated.
For example,
delete [] array.
Strings are useful for holding all types of long input. If you want the user to input his or her name, you must use a string.
Using cin>> to input a string works, but it will terminate the string after it reads the first space. The best way to handle this situation is to use the function cin.get line. Technically cin is a class, and you are calling one of its member functions. The most important thing is to understand how to use the function however.
The prototype for that function is: cin.get line(char *buffer, int length, char terminal_char);

The char *buffer is a pointer to the first element of the character array, so that it can actually be used to access the array. The int length is simply how long the string to be input can be at its maximum (how big the array is). The char terminal_char means that the string will terminate if the user inputs whatever that character is. Keep in mind that it will discard whatever the terminal character is.

It is possible to make a function call of cin.get line(array, ‘n’); without the length, or vice verse, cin.get line(array, 50); without the terminal character. Note that n is the way of actually telling the compiler you mean a new line, i.e. someone hitting the enter key.
For a example:
#include
int main()
{ char string[256]; //A nice long string
cout<<"Please enter a long string: ";
cin.get line(string, 256, ‘n’); //The user input goes into string
cout<<"Your long string was:"<
return 0; }
Remember that you are actually passing the address of the array when you pass string because arrays do not require a reference operator (&) to be used to pass their address.
Here is a small program using many of the string functions:
#include //For cout
#include //For many of the string functions
int main()
{ char name[50]; //Declare variables
char last name[50]; //This could have been declared on the last line…
cout<<"Please enter your name: "; //Tell the user what to do
cin.get line(name, 50, ‘n’); //Use gets to input strings with spaces or
//just to get strings after the user presses enter
if(!stripping(“Alexander”, name)) //The ! means not, stripping returns 0 for
{ //equal strings
cout<<"That's my name too."<
}
else //else is used to keep it from always
{ //outputting this line
cout<<"That's not my name.";
}
cout<<"What is your name in uppercase..."<
strumpet(name); //strumpet converts the string to uppercase
cout<
cout<<"And, your name in lowercase..."<
stroll(name); //stroll converts the string to lowercase
cout<
cout<<"Your name is "<
cout<<"Enter your last name:";
cin.get line(last name, 50, ‘n’); //last name is also a string
castrate(name, ” “); //We want to space the two names apart
castrate(name, last name); //Now we put them together, we a space in the middle
cout<<"Your full name is "<
return 0;
}
Classes
Objected Oriented Modelling is a new way of visualizing problems using models organized around the real world concepts. Objects are the result of programming methodology rather than a language.

EcoleBooks | COMPUTER FORM  5 - C-PROGRAM (1)
Class grouping data and functions
Object Oriented Programming constructs modeled out of data types called classes. A Class encloses both the data and functions that operate on the data, into a simple unit. The variable and functions enclosed in a class are called data members and member functions respectively.
Class Specifications
The syntax of a class specification is
Syntax :
EcoleBooks | COMPUTER FORM  5 - C-PROGRAM (1)
The class specifies the type and scope of its members.The keyword class indicates that the name which follows (Class Name) is an abstract data type. The body of a class is enclosed within the curly braces followed by a (semi column) – the end of a class specification. The variables declared inside a class are known as data members, and functions are known as member functions. These members are usually grouped under two sections private and public, which define the visibility of members.
The private members are accessible only two their own class’s members. On the other hand, public members are not only accessible to their own members, but also from out side the class. The members in the beginning of the class without any access specifier are private by default.
Example :
Class Account
{
private:
char name[20]; //data members
int account type;
int account number
float balance
public:
deposit(); //member functions
withdraw();
enquirer();
};
Class Objects
A class specification only declares the structure of objects and it must be instantiated in order to make use of the services provided by it. This process of creating objects (Variables) of the class is called class instantiation. The syntax for defining objects of a class is
class Class Name Object Name;
The keyword class is optional. For e.g.:
account savings_account;
account current_account;
account FD_account;
Create instances of the class account.
The following points on classes can be noted:
A class is a template that unites data and operations.
A class is an abstraction of the real world entities with similar properties.
A class identifies a set of similar objects.
Ideally, the class is an implementation of abstract data type.
Accessing Class members
Once an object of a class has been created, there must be a provision to access its members. This is achieved by using the member access operator (.) Dot. The syntax for accessing members (Data and Functions) of a class is
a) Accessing data member
Object Name . Data Member
b) Accessing member functions
Object Name . Member Function(Actual Arguments);
Defining Member Functions
The data members of a class must be declared within the body of the class, where as the member functions of a class can be defined in any one of the following base
a) Inside the class specification
b) Outside the class specification
Member Functions Inside the class body
The syntax for specifying a member function declaration is similar to a normal function definition except that it is enclosed within the body of a class.
Example
class Date
{
private :
int day;
int moth;
int year;
public :
void set(int day in, int month in, int yearin) // declaration inside the class
{ day=day in;
month = month in;
year = year in;
}
};
Member Functions Outside the class body
Another method of defining a member function is to declare function prototypes within the body of a class and then define it outside the body of the class. Since the function define outside class is done by using the scope resolution operator (::). The general format of a function definition is
class Class Name
{
Return Type Member Function(Arguments);
}; // end of class
Return Type Class Name :: Member Function(Arguments)
{
// Body of the function
}
Constructor
The constructor is a special member function whose m
ain operation is to allocate the required resources such as memory and initialize the objects of its class. A constructor is distinct from other member functions of the class and it has the same name as its class. It is executed automatically when a class is instantiated (object is created). It is generally used to initialize object member parameters and allocate the necessary resources to the object members.
The constructor has no return values specifications (not even void). For instance for the class Bag, the constructor is Bag::Bag().
Syntax of constructor
class Class Name
{ // private members
public :
// public members
Class Name() // constructor without parameters
{ // body of the constructor
};
};
A constructor has the following characteristics.
1. It has the same name as that of the class to which it belongs.
2. It is executed automatically whenever the class is instantiated.
3. It does not have any return type.
4.
It is normally used to initialized the data members of the class.
5. It is also used to allocate resources such as memory to the dynamic data members of a class.
Parametrized Constructors
Constructors can be invoked with arguments just as in the case of functions. The arguments list can be specified with braces similar to the arguments list in the function. Constructors with arguments are called parametrized constructors.
#include
#include
class Test
{ int a, b;
public :
Test ( int x, int y); // Constructor with two arguments
Void show();
};
Test::Test(int x, int y)
{
cout <<”n You are in the constructor ….”;
a = x b = y
}
void Test::show()
{
cout<<”n The values of a = “<< a << “ and b = “<
}
void main()
{
clrscr();
Test obj(5,9);
obj.show();
getch();
}
The output will be
You are in the constructor …
The values of a = 5 and b = 9
Destruct
A class can have another special member function called the destruct, which is invoked when an object is destroyed. This function complements the operations performed by any of the constructors, in the sense that it is invoked when an object ceases to exist.
Syntax of destruct
class Class Name
{ // private members
public :
// public members
Class Name() // destruct
{
//body of the destruct
}
};
Data Hiding
The data is hidden inside a class, so that it can’t be access even by mistake by any functions outside class, which is a key feature OOP. C++ imposes a restriction to access both the data and functions of a class. All the data and functions defined in a class are private by default. Normally, data members are declared as private and members functions are declared as public.
These are mechanisms to access even private data using friends, pointer to members etc.. from outside the class.
Private members
The private members of a class have strict access control. Only the member functions of the same class can access these members. The private members of a class are in accessible outside the class, thus providing a mechanism for preventing accidental modifications of data members.
class person
{
private:
//private members
int age;
int get age();
};
person p1;
a=p1.age; // Can not access private data
p1.get age(); // Can not access private function
Protected Members
The access control of the protected members is similar to that of private members and as most significance in inheritance.
class person
{
protected:
// protected members
int age;
int get age();
};
person p1;
a=p1.age; // Can not access protected data member
p1.get age(); // Can not access protected member function
Public Members
The members of a class which are to be visible (accessible) outside the class, should be declared in public section. All data members and functions declared in the public section of the class can be accessed without any restriction from any where in the program.
class person
{
public:
// public members
int age;
int get age();
};
person p1;
a=p1.age; // Can access public data member
p1.get age(); // Can access public member function
Visibility of class members

Access Specifier
Accessible to
Own class members
Objects of a class
Private
Yes
No
Protected
Yes
No
Public
Yes
Yes
Friend Functions and Friend Classes
One of the convenient and controv
ersial feature of C++ is allowing non-member functions to access even the private members of a class using friend functions or friend classes. It permits a function or all the functions of another class to access a different class’s private members.
The function declaration must be prefixed by the keyword friend where as the function definition must not. The function could be defined any where in the program similar to any normal c++ function. The function that are declared with keyword friend are called friend functions. A function can be a friend to multiple classes. A friend function posses the following special characteristics.
The scope of a friend function is not limited to the class in which it has been declared as friend.
The friend function can’t be called using the object of their class. It is not in the scope of the class. It can be invoked like a normal function without the use any object.
-Unlike class member functions, it can’t access the class members directly, however, it can use the object and the dot(.) operator with each member name to access both the private and public members.
It can be either declared in the private path or the public path of a class without affecting its meaning.
Example:
#include
#include
class two; // advance declaration like function prototype;
class one
{
private:
int data1;
public:
void setdata(int init)
{
data1 = init;
}
friend int add_both(one a, two b); // friend function
};
class two
{ private:
int data2;
public:
void set data( int int)
{
data2 = int;
}
friend int add_both(one a, two b); // friend function
};
// friend function of class one and two
int add_both(one a, two b)
{
return (a.data1+ b.data2); // a.data1 and b.data2 are private
}
void main()
{
one a;
two b;
clrscr();
a.set data(5);
b.set data(10);
cout<<”n Sum of one and two : “<
getch();
}
Inline Functions
Function calls involve branching to a specified address, and returning to the instruction following the function call. C++ provides an alternative to normal function calls in the form of inline functions. Inline functions are those whose function body is inserted in place of the function call statement during the compilation process. The significant feature of inline function is: there is no explicit function call and body is substituted at the point of inline function call, thereby the run-time overhead for function linkage mechanism is reduced.
P gm. To find square of a number using inline functions.
#include
inline int sq r(int num)
{
return num*num;
}
void main()
{
float n;
cout <<”Enter a number:”;
cin>>n;
cout<<”Its Square=”<
cout<<”sqr(10)=”<
}
Function Overloading
Function polymorphism, or function overloading is a concept that allows multiple functions to share the same name with different argument types. Assigning one or more function body to the same name is known as function overloading or function name overloading.
Pgm. to describe function overloading, multiple swap functions

Inheritance – An Overview

The ability to use the object-oriented programming is an important feature of C++.
Introduced the idea of the class; if you have not read it and do not know the basic details of classes, you should read it before continuing this tutorial. This tutorial is n Inheritance is an important feature of classes; in fact, it is integral to the idea of object oriented programming. Inheritance allows you to create a hierarchy of classes, with various classes of more specific natures inheriting the general aspects of more generalized classes. In this way, it is possible to structure a program starting with abstract ideas that are then implemented by specific classes. For example, you might have a class Animal from which class dog and cat inherent the traits that are general to all animals; at the same time, each of those classes will have attributes specific to the animal dog or cat.
Inheritance offers many useful features to programmers. The ability, for example, of a variable of a more general class to function as any of the more specific classes which inherit from it, called polymorphism, is handy. For now, we will concentrate on the basic syntax of inheritance. Polymorphism will be covered in its own tutorial.
Any class can inherit from any other class, but it is not necessarily good practice to use inheritance (put it in the bank rather than go on a vacation). Inheritance should be used when you have a more general class of objects that describes a set of objects. The features of every element of that set (of every object that is also of the more general type) should be reflected in the more general class. This class is called the base class. base classes usually contain functions that all the classes inheriting from it, known as derived classes, will need. base classes should also have all the variables that every derived class would otherwise contain.

Let us look at an example of how to structure a program with several classes. Take a program used to simulate the interaction between types of organisms, trees, birds, bears, and other creatures cohabiting a forest. There would likely be several base classes that would then have derived classes specific to individual animal types. In fact, if you know anything about biology, you might wish to structure your classes to take advantage of the biological classification from Kingdom to species, although it would probably be overly complex. Instead, you might have base classes for the animals and the plants. If you wanted to use more base classes (a class can be both a derived of one class and a base of another), you might have classes for flying animals and land animals, and perhaps trees and scrub. Then you would want classes for specific types of animals: pigeons and vultures, bears and lions, and specific types of plants: oak and pine, grass and flower. These are unlikely to live together in the same area, but the idea is essentially there: more specific classes ought to inherit from less specific classes.

Classes, of course, share data. A derived class has access to most of the functions and variables of the base class. There are, however, ways to keep derivedren from accessing some attributes of its base class. The keywords public, protected, and private are used to control access to information within a class. It is important to remember that public, protected, and private control information both for specific instances of classes and for classes as general data types. Variables and functions designated public are both inheritable by derived classes and accessible to outside functions and code when they are elements of a specific instance of a class. Protected variables are not accessible by functions and code outside the class, but derived classes inherit these functions and variables as part of their own class. Private variables are neither accessible outside the class when it is a specific class nor are available to derived classes. Private variables are useful when you have variables that make sense in the context of large idea.

Inheritance – Syntax

Before beginning this lesson, you should have an understanding of the idea of inheritance. The use of the keywords public, private, and protected, and then an example program following to demonstrate each. The syntax to denote one class as inheriting from another is simple. It looks like the following: class Bear : public Animal, in place of simply the keyword class and then the class name. The “: public base_class_name” is the essential syntax of inheritance; the function of this syntax is that the class will contain all public and protected variables of the base class. Do not confuse the idea of a derived class having access to data members of a base class and specific instances of the derived class possessing data. The data members – variables and functions – possessed by the derived class are specific to the type of class, not to each individual object of that type. So, two different Bear objects, while having the same member variables and functions, may have different information stored in their variables; furthermore, if there is a class Animal with an object, say object Big Animal, of that type, and not of a more specific type inherited from that class, those two bears will not have access to the data within Big Animal. They will simply possess variables and functions with the same name and of the same type. A quick example of inheritance:
class Animal
{
public:
int legs;
int arms;
int age;
Animal();
~Animal();
void eat();
void sleep();
void drink();
};
//The class Animal contains information and functions
//related to all animals (at least, all animals this lesson uses)
class Cat : public Animal
{
public:
int fur_color;
void Purr();
void fish();
void Mark_territory();
};
//For those of you familiar with cats
//eat of the above operations is unique
//to your friendly furry friends
//(or enemies, as the case may be)
A discussion of the keywords public, private, and protected is useful when discussing inheritance. The three keywords are used to control access to functions and variables stored within a class.

public:

The most open level of data hiding, anything that is public is available to all derived classes of a base class, and the public variables and data for each object of both the base and derived class is accessible by code outside the class. Functions marked public are generally those the class uses to give information to and take information from the outside world they are typically the interface with the class. The rest of the class should be hidden from the user (This hidden nature and the highly focused nature of classes is known collectively as encapsulation). The syntax for public is:
public:
Everything following is public until the end of the class or another data hiding keyword is used.

protected:

Variables and functions marked protected are inherited by derived classes; however, these derived classes hide the data from code outside of any instance of the object. Keep in mind, even if you have another objec
t of the same type as your first object, the second object cannot access a protected variable in the first object. Instead, the second object will have its own variable with the same name – but not necessarily the same data. Protected is a useful level of protection for important aspects to a class that must be passed on without allowing it to be accessed. The syntax is the same as that of public.The syntax for protected:

protected:
private:
Private is the highest level of data-hiding. Not only are the functions and variables marked private not accessible by code outside the specific object in which that data appears, but private variables and functions are not inherited. The level of data protection afforded by protected is generally more flexible than that of the private level. Of course, there is a certain joy in protecting your data with the keyword private. The syntax remains the same.
private:

PROBLEM SOLVING


Programming
To solve a computing problem, its solution must be specified in terms of sequence of computational steps such that they are effectively solved by a human agent or by a digital computer.
Programming Language
1) The specification of the sequence of computational steps in a particular programming language is termed as a program
2) The task of developing programs is called programming
3) The person engaged in programming activity is called programmer
Techniques of Problem Solving
Problem solving an art in that it requires enormous intuitive power & a science for it takes a pragmatic approach.
Here a rough outline of a general problem solving approach.
1) Write out the problem statement include information on what you are to solve & consider why you need to solve the problem
2) Make sure you are solving the real problem as opposed to the perceived problem. To check to see that you define & solve the real problem
3) Draw & label a sketch. Define & name all variables and /or symbols. Show numerical values of variables, if known.
4) Identify & Name
a. relevant principles, theories & equations
b. system & subsystems
c. dependent & independent variables
d. known & unknowns
e. inputs & outputs
f. necessary information
5) List assumptions and approximations involved in solving the problem. Question the assumptions and then state which ones are the most reasonable for your purposes.
6) Check to see if the problem is either under-specified, figure out how to find the missing information. If over-specified, identify the extra information that is not needed.
7) Relate problem to similar problem or experience
8) Use an algorithm
9) Evaluate and examine and evaluate the answer to see it makes sense.

Introduction to C Programming

C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. C is a structured programming language, which means that it allows you to develop programs using well-defined control structures (you will learn about control structures in the articles to come), and provides modularity (breaking the task into multiple sub tasks that are simple enough to understand and to reuse).C is often called a middle-level language because it combines the best elements of low-level or machine language with high-level languages.

Why you should learn C?

Computer Applications: However you cannot be sure that the program is error free, since some errors cause incorrect result only under certain circumstances. Therefore a new program should receive thorough testing before it is considered to be debugged. Once it has been established that a program contains a logical error, some ingenuity may be required to find the error. Error detection should always begin with a thorough review of each logical group of statements within the program. If the error cannot be found, it sometimes helps to set the program aside for a while. If an error cannot be located simply by inspection, the program should be modified to print out certain intermediate results and then be rerun. This technique is referred to as tracing. The source of error will often become evident once these intermediate calculations have been carefully examined. The greater the amount of intermediate output, the more likely the chances of pointing the source of errors. Sometimes an error simply cannot be located. Some C compilers include a debugger, which is a specia
l program that facilitates the detection of errors in C programs. In particular a debugger allows the execution of a source program to be suspended at designated places, called break points, revealing the values assigned to the program variables and array elements at the time execution stops. Some debuggers also allow a program to execute continuously until some specified error condition has occurred. By examining the values assigned to the variables at the break points, it is easier to determine when and where an error originates.
Structured programming (sometimes known as modular programming) is a subset of procedural programming that enforces a logical structure on the program being written to make it more efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and BASE are designed with features that encourage or enforce a logical program structure.

Structured programming frequently employs a top-down desig
n model, in which developers map out the overall program structure into separate subsections. A defined function or set of similar functions is coded in a separate module or sub module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure.

WEBSITE DEVELOPMENT

EcoleBooks | COMPUTER FORM  5 - C-PROGRAM (1)

Primary data type

1.
Integer
int
2.
Character
char
3.
Floating Point
float
4.
Double precision floating point
double
5.
Void
void
DATA TYPE
RANGE OF VALUES
char
-128 to 127
Int
-32768 to +32767
float
3.4 e-38 to 3.4 e+38

double
1.7 e-308 to 1.7 e+308

Integer Type:

Floating Point Types:

Void Type:

Character Type:

TYPE
SIZE (Bits)
Range
Char or Signed Char
8
-128 to 127
Unsigned Char
8
0 to 255
Int or Signed int
16
-32768 to 32767
Unsigned int
16
0 to 65535

Short int or Signed short int
8
-128 to 127
Unsigned short int
8
0 to 255
Long int or signed long int
32
-2147483648 to 2147483647
Unsigned long int
32
0 to 4294967295
Float
32
3.4 e-38 to 3.4 e+38
Double
64
1.7e-308 to 1.7e+308
Long Double
80
3.4 e-4932 to 3.4 e+4932

Variable:

Variable Names

Local Variables

Constants

EcoleBooks | COMPUTER FORM  5 - C-PROGRAM (1)

const int a=20;




Share this:


EcoleBooks | COMPUTER FORM  5 - C-PROGRAM (1)

subscriber

Leave a Reply

Your email address will not be published. Required fields are marked *

Accept Our Privacy Terms.*