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 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 of 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 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.getline. 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.

ecolebooks.com

The prototype for that function is: cin.getline(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.getline(array, ‘n’); without the length, or vice versa, cin.getline(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 example:

#include using namespace std;int main(){    char string[256]; // A nice long string    cout << "Please enter a long string: ";    cin.getline(string, 256, 'n'); // The user input goes into string    cout << "Your long string was:" << endl << string;    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 #include using namespace std;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.getline(name, 50, 'n'); // Use getline to input strings with spaces or    // just to get strings after the user presses enter    if (!strcmp("Alexander", name)) // The ! means not, strcmp returns 0 for    { // equal strings        cout << "That's my name too." << endl; // Tell the user if it's my name    }    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..." << endl;    for (int i = 0; name[i] != ''; i++) // Convert to uppercase        name[i] = toupper(name[i]);    cout << name << endl;    cout << "And, your name in lowercase..." << endl;    for (int i = 0; name[i] != ''; i++) // Convert to lowercase        name[i] = tolower(name[i]);    cout << name << endl;    cout << "Your name is " << strlen(name) << " letters long" << endl; // strlen - length of the string    cout << "Enter your last name:";    cin.getline(last_name, 50, 'n'); // last name is also a string    strcat(name, " "); // We want to space the two names apart    strcat(name, last_name); // Now we put them together, with a space in the middle    cout << "Your full name is " << name; // Outputting it all...    return 0;}

Classes

Object Oriented Modelling is a new way of visualizing problems using models organized around real world concepts. Objects are the result of programming methodology rather than a language.

BxrF353ZhG2o8Hs IbeMp4IaQaCEwwiDlZvn27rRocZDDsq30Bt9AULe3fTLsA29HLVHIi7VMvoeE14Crm2y5iSbTFWi1ADFqujY7pksMsHmeNQyoLwCU5TvexET5VlrE1xksYw

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 variables and functions enclosed in a class are called data members and member functions respectively.

Class Specifications

The syntax of a class specification is

Syntax :

5JE VeB5x8QvEnob8PqagJsqJI DOnMx81afxvsjqX F22bCZvwx9au12Rjv2EKLEbSEyowKm8cc2dop98DCrdWWaebmsoOsiCupcjO6AaFjGglC5Nis2Y9KFUEwbpQMgHalll4

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 semicolon – 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 to their own class’s members. On the other hand, public members are not only accessible to their own members, but also from outside the class. The members at 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:    void deposit(); // member functions    void withdraw();    void 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 ClassName ObjectName;

The keyword class is optional.

For example:

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

ObjectName.DataMember

b) Accessing member functions

ObjectName.MemberFunction(ActualArguments);

Defining Member Functions

The data members of a class must be declared within the body of the class, whereas the member functions of a class can be defined in any one of the following bases:

  1. Inside the class specification
  2. 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 month;    int year;public:    void set(int day_in, int month_in, int year_in) // 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 defined outside class is done by using the scope resolution operator (::). The general format of a function definition is

class ClassName{    ReturnType MemberFunction(Arguments);}; // end of classReturnType ClassName::MemberFunction(Arguments){    // Body of the function}

Constructor

The constructor is a special member function whose main 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 value specification (not even void). For instance, for the class Bag, the constructor is Bag::Bag().

Syntax of constructor

class ClassName{     // private memberspublic:    // public members    ClassName() // 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 initialize 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 argument list can be specified with braces similar to the argument list in the function. Constructors with arguments are called parametrized constructors.

#include using namespace std;class Test{    int a, b;public:    Test(int x, int y); // Constructor with two arguments    void show();};Test::Test(int x, int y){    cout << "nYou are in the constructor ….";    a = x; b = y;}void Test::show(){    cout << "nThe values of a = " << a << " and b = " << b;}int main(){    Test obj(5, 9);    obj.show();    return 0;}

The output will be:

You are in the constructor …

The values of a = 5 and b = 9

Destructor

A class can have another special member function called the destructor, 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 destructor

class ClassName{    // private memberspublic:    // public members    ~ClassName() // destructor    {         // body of the destructor    }};

Data Hiding

The data is hidden inside a class, so that it can’t be accessed even by mistake by any functions outside the class, which is a key feature of 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 member 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 inaccessible 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; // Cannot access private datap1.get_age(); // Cannot access private function

Protected Members

The access control of the protected members is similar to that of private members and is most significant in inheritance.

class person{protected:    // protected members    int age;    int get_age();};person p1;a = p1.age; // Cannot access protected data memberp1.get_age(); // Cannot access protected member function

Public Members

The members of a class which are to be visible (accessible) outside the class, should be declared in the public section. All data members and functions declared in the public section of the class can be accessed without any restriction from anywhere in the program.

class person{public:    // public members    int age;    int get_age();};person p1;a = p1.age; // Can access public data memberp1.get_age(); // Can access public member function

Visibility of class members

Access SpecifierAccessible to
Own class membersObjects of a class
PrivateYesNo
ProtectedYesNo
PublicYesYes

Friend Functions and Friend Classes

One of the convenient and controversial features 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 whereas the function definition must not. The function could be defined anywhere in the program similar to any normal C++ function. The functions that are declared with keyword friend are called friend functions. A function can be a friend to multiple classes. A friend function possesses 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 of 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 part or the public part of a class without affecting its meaning.

Example:

#include using namespace std;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 setdata(int init)    {        data2 = init;    }    friend int add_both(one a, two b); // friend function};// friend function of class one and twoint add_both(one a, two b){    return (a.data1 + b.data2); // a.data1 and b.data2 are private}int main(){    one a;    two b;    a.setdata(5);    b.setdata(10);    cout << "nSum of one and two : " << add_both(a, b);    return 0;}

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.

Program to find square of a number using inline functions.

#include using namespace std;inline int sqr(int num){    return num * num;}int main(){    int n;    cout <> n;    cout << "Its Square = " << sqr(n) << endl;    cout << "sqr(10) = " << sqr(10);    return 0;}

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 bodies to the same name is known as function overloading or function name overloading.

Inheritance – An Overview

The ability to use object-oriented programming is an important feature of C++.

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 inherit 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 indiscriminately. 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 derived classes 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 ideas.

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 BigAnimal, 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 BigAnimal. 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();};class Cat : public Animal{public:    int fur_color;    void Purr();    void fish();    void Mark_territory();};

For those of you familiar with cats, each 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 object 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 a 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 is an art in that it requires enormous intuitive power and a science for it takes a pragmatic approach.

Here is a rough outline of a general problem solving approach.

  1. Write out the problem statement including information on what you are to solve and 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 and solve the real problem.
  3. Draw and label a sketch. Define and name all variables and/or symbols. Show numerical values of variables, if known.
  4. Identify and Name
    • relevant principles, theories & equations
    • system & subsystems
    • dependent & independent variables
    • known & unknowns
    • inputs & outputs
    • 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 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 subtasks 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.

Where is C useful?

C’s ability to communicate directly with hardware makes it a powerful choice for system programmers. In fact, popular operating systems such as Unix and Linux are written entirely in C. Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is also used to develop any kind of application, including complex business ones. The following is a partial list of areas where C language is used:

  • Embedded Systems
  • Systems Programming
  • Artificial Intelligence
  • Industrial Automation
  • Computer Graphics
  • Space Research

Why you should learn C?

  • C is simple.
  • There are only 32 keywords so C is very easy to master. Keywords are words that have special meaning in C language.
  • C programs run faster than programs written in most other languages.
  • C enables easy communication with computer hardware making it easy to write system programs such as compilers and interpreters.

WHY WE NEED DATA AND A PROGRAM

Any computer program has two entities to consider, the data, and the program. They are highly dependent on one another and careful planning of both will lead to a well planned and well written program. Unfortunately, it is not possible to study either completely without a good working knowledge of the other. For that reason, this tutorial will jump back and forth between teaching methods of program writing and methods of data definition. Simply follow along and you will have a good understanding of both. Keep in mind that, even though it seems expedient to sometimes jump right into coding the program, time spent planning the data structures will be well spent and the quality of the final program will reflect the original planning.

How to run a simple C program

  1. Copy Turbo C/C++ in computer.
  2. Open c:tcbintc.exe.
  3. A window appears.
  4. Select File > New to open a new file.
  5. Type the following program on editor:
#include void main(){    printf("hello");}
  1. Compile the program by pressing ALT+F9.
  2. Run the program by pressing CTRL+F9.

Note:

  1. C is case sensitive.
  2. Always terminate statements with semicolon.
  3. A program starts with main().

Explanation of program

#include is known as compiler directive. A compiler directive is a command to compiler to translate the program in a certain way. These statements are not converted into machine language but only perform some other task.

main() is a function which is the starting point for compiler to start compilation. So a function must contain a main() function.

DETECTION AND CORRECTION OF ERRORS

Syntactic errors and execution errors usually result in the generation of error messages when compiling or executing a program. Errors of this type are usually quite easy to find and correct. There are some logical errors that can be very difficult to detect. Since the output resulting from a logically incorrect program may appear to be error free. Logical errors are often hard to find, so in order to find and correct errors of this type is known as logical debugging. To detect errors test a new program with data that will give a known answer. If the correct results are not obtained then the program obviously contains errors even if the correct results are obtained.

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 special 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.

Linear Programming

Linear program is a method for straightforward programming in a sequential manner. This type of programming does not involve any decision making. General model of these linear programs is:

  1. Read a data value
  2. Compute an intermediate result
  3. Use the intermediate result to compute the desired answer
  4. Print the answer
  5. Stop

Structured Programming

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 BASIC are designed with features that encourage or enforce a logical program structure.

Structured programming frequently employs a top-down design 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 submodule, 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.

Advantages of Structured Programming

  1. Easy to write: Modular design increases the programmer’s productivity by allowing them to look at the big picture first and focus on details later. Several programmers can work on a single, large program, each working on a different module. Studies show structured programs take less time to write than standard programs. Procedures written for one program can be reused in other programs requiring the same task. A procedure that can be used in many programs is said to be reusable.
  2. Easy to debug: Since each procedure is specialized to perform just one task, a procedure can be checked individually. Older unstructured programs consist of a sequence of instructions that are not grouped for specific tasks. The logic of such programs is cluttered with details and therefore difficult to follow.
  3. Easy to Understand: The relationship between the procedures shows the modular design of the program. Meaningful procedure names and clear documentation identify the task performed by each module. Meaningful variable names help the programmer identify the purpose of each variable.
  4. Easy to Change: Since a correctly written structured program is self-documenting, it can be easily understood by another programmer.

Structured Programming Constructs

It uses only three constructs –

  • Sequence (statements, blocks)
  • Selection (if, switch)
  • Iteration (loops like while and for)

Sequence

  • Any valid expression terminated by a semicolon is a statement.
  • Statements may be grouped together by surrounding them with a pair of curly braces.
  • Such a group is syntactically equivalent to one statement and can be inserted wherever one statement is legal.

Selection

The selection constructs allow us to follow different paths in different situations. We may also think of them as enabling us to express decisions.

The main selection construct is:

if (expression)    statement1else    statement2

statement1 is executed if and only if expression evaluates to some non-zero number. If expression evaluates to 0, statement1 is not executed. In that case, statement2 is executed.

If and else are independent constructs, in that if can occur without else (but not the reverse). Any else is paired with the most recent else-less if, unless curly braces enforce a different scheme. Note that only curly braces, not parentheses, must be used to enforce the pairing.

Iteration

Looping is a way by which we can execute some set of statements more than one time continuously. In C there are mainly three types of loops used:

  • while Loop
  • do while Loop
  • For Loop

The control structures are easy to use because of the following reasons:

  1. They are easy to recognize.
  2. They are simple to deal with as they have just one entry and one exit point.
  3. They are free of the complications of any particular programming language.

WEBSITE DEVELOPMENT

Modular Design of Programs

One of the key concepts in the application of programming is the design of a program as a set of units referred to as blocks or modules. A style that breaks large computer programs into smaller elements called modules. Each module performs a single task; often a task that needs to be performed multiple times during the running of a program. Each module also stands alone with defined input and output. Since modules are able to be reused they can be designed to be used for multiple programs. By debugging each module and only including it when it performs its defined task, larger programs are easier to debug because large sections of the code have already been evaluated for errors. That usually means errors will be in the logic that calls the various modules.

Languages like Modula-2 were designed for use with modular programming. Modular programming has generally evolved into object-oriented programming.

Programs can be logically separated into the following functional modules:

  1. Initialization
  2. Input
  3. Input Data Validation
  4. Processing
  5. Output
  6. Error Handling
  7. Closing procedure

Basic attributes of modular programming:

  1. Input
  2. Output
  3. Function
  4. Mechanism
  5. Internal data

Control Relationship between modules:

The structure charts show the interrelationships of modules by arranging them at different levels and connecting modules in those levels by arrows. An arrow between two modules means the program control is passed from one module to the other at execution time. The first module is said to call or invoke the lower level modules. There are three rules for controlling the relationship between modules.

  1. There is only one module at the top of the structure. This is called the root or boss module.
  2. The root passes control down the structure chart to the lower level modules. However, control is always returned to the invoking module and a finished module should always terminate at the root.
  3. There can be more than one control relationship between two modules on the structure chart, thus, if module A invokes module B, then B cannot invoke module A.

Communication between modules:

  1. Data: Shown by an arrow with empty circle at its tail.
  2. Control: Shown by a filled-in circle at the end of the tail of arrow.

Module Design Requirements

A hierarchical or module structure should prevent many advantages in management, developing, testing and maintenance. However, such advantages will occur only if modules fulfill the following requirements.

a) Coupling: In computer science, coupling is considered to be the degree to which each program module relies on other modules, and is also the term used to describe connecting two or more systems. Coupling is broken down into loose coupling, tight coupling, and decoupled. Coupling is also used to describe software as well as systems. Also called dependency.

Types of Programming Language

Low Level Language

First-generation language is the lowest level computer language. Information is conveyed to the computer by the programmer as binary instructions. Binary instructions are the equivalent of the on/off signals used by computers to carry out operations. The language consists of zeros and ones. In the 1940s and 1950s, computers were programmed by scientists sitting before control panels equipped with toggle switches so that they could input instructions as strings of zeros and ones.

Advantages

  • Fast and efficient
  • Machine oriented
  • No translation required

Disadvantages

  • Not portable
  • Not programmer friendly

Assembly Language

Assembly or assembler language was the second generation of computer language. By the late 1950s, this language had become popular. Assembly language consists of letters of the alphabet. This makes programming much easier than trying to program a series of zeros and ones. As an added programming assist, assembly language makes use of mnemonics, or memory aids, which are easier for the human programmer to recall than are numerical codes.

Assembler

An assembler is a program that takes basic computer instructions and converts them into a pattern of bits that the computer’s processor can use to perform its basic operations. Some people call these instructions assembler language and others use the term assembly language. In other words, an assembler is a computer program for translating assembly language — essentially, a mnemonic representation of machine language — into object code. A cross assembler produces code for one processor, but runs on another.

As well as translating assembly instruction mnemonics into op codes, assemblers provide the ability to use symbolic names for memory locations (saving tedious calculations and manually updating addresses when a program is slightly modified), and macro facilities for performing textual substitution — typically used to encode common short sequences of instructions to run inline instead of in a subroutine.

High Level Language

The introduction of the compiler in 1952 spurred the development of third-generation computer languages. These languages enable a programmer to create program files using commands that are similar to spoken English. Third-level computer languages have become the major means of communication between the digital computer and its user. By 1957, the International Business Machine Corporation (IBM) had created a language called FORTRAN (Formulas Translate). This language was designed for scientific work involving complicated mathematical formulas. It became the first high-level programming language (or “source code”) to be used by many computer users.

Within the next few years, refinements gave rise to ALGOL (Algorithmic Language) and COBOL (Common Business Oriented Language). COBOL is noteworthy because it improved the record keeping and data management ability of businesses, which stimulated business expansion.

Advantages

  • Portable or machine independent
  • Programmer-friendly

Disadvantages

  • Not as efficient as low-level languages
  • Need to be translated

Examples: C, C++, Java, FORTRAN, Visual Basic, and Delphi.

Interpreter

An interpreter is a computer program that executes other programs. This is in contrast to a compiler which does not execute its input program (the source code) but translates it into executable machine code (also called object code) which is output to a file for later execution. It may be possible to execute the same source code either directly by an interpreter or by compiling it and then executing the machine code produced.

It takes longer to run a program under an interpreter than to run the compiled code but it can take less time to interpret it than the total required to compile and run it. This is especially important when prototyping and testing code when an edit-interpret-debug cycle can often be much shorter than an edit-compile-run-debug cycle.

Interpreting code is slower than running the compiled code because the interpreter must analyze each statement in the program each time it is executed and then perform the desired action whereas the compiled code just performs the action. This run-time analysis is known as “interpretive overhead”. Access to variables is also slower in an interpreter because the mapping of identifiers to storage locations must be done repeatedly at run-time rather than at compile time.

COMPILER

A program that translates source code into object code. The compiler derives its name from the way it works, looking at the entire piece of source code and collecting and reorganizing the instructions. Thus, a compiler differs from an interpreter, which analyzes and executes each line of source code in succession, without looking at the entire program. The advantage of interpreters is that they can execute a program immediately. Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter.

Every high-level programming language (except strictly interpretive languages) comes with a compiler. In effect, the compiler is the language, because it defines which instructions are acceptable.

Fourth Generation Language

Fourth-generation languages attempt to make communicating with computers as much like the processes of thinking and talking to other people as possible. The problem is that the computer still only understands zeros and ones, so a compiler and interpreter must still convert the source code into the machine code that the computer can understand. Fourth-generation languages typically consist of English-like words and phrases. When they are implemented on microcomputers, some of these languages include graphic devices such as icons and onscreen push buttons for use during programming and when running the resulting application.

Many fourth-generation languages use Structured Query Language (SQL) as the basis for operations. SQL was developed at IBM to develop information stored in relational databases. Examples of fourth-generation languages include PROLOG, an Artificial Intelligence language.

UNIT-2

FEATURES OF ‘C’

C-Language keywords

CUjNAgHRmOMbjQj JcWfwkEoM3Ty7yxVDigTGb45o9F PYVdQlWkqGlcuND64z6Fb9u42WJp4ucpZKi NpJUDfruqIZwJ5r3NH9Zw3QqCogUmJq4ZypVrS0IC9bo1TgpeqSthNw

Data Types

A C language programmer has to tell the system beforehand, the type of numbers or characters he is using in his program. These are data types. There are many data types in C language. A C programmer has to use appropriate data type as per his requirement.

C language data types can be broadly classified as

  • Primary data type
  • Derived data type
  • User defined data type

Primary data type

All C Compilers accept the following fundamental data types

1.Integerint
2.Characterchar
3.Floating Pointfloat
4.Double precision floating pointdouble
5.Voidvoid

The size and range of each data type is given in the table below

DATA TYPERANGE OF VALUES
char-128 to 127
int-32768 to +32767
float3.4e-38 to 3.4e+38
double1.7e-308 to 1.7e+308

Integer Type:

Integers are whole numbers with a machine dependent range of values. A good programming language has to support the programmer by giving control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values.

Floating Point Types:

Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory space.

Void Type:

Using void data type, we can specify the type of a function. It is a good practice to avoid functions that do not return any values to the calling function.

Character Type:

A single character can be defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.

Size and Range of Data Types on 16 bit machine.

TYPESIZE (Bits)Range
Char or Signed Char8-128 to 127
Unsigned Char80 to 255
Int or Signed int16-32768 to 32767
Unsigned int160 to 65535
Short int or Signed short int8-128 to 127
Unsigned short int80 to 255
Long int or signed long int32-2147483648 to 2147483647
Unsigned long int320 to 4294967295
Float323.4e-38 to 3.4e+38
Double641.7e-308 to 1.7e+308
Long Double803.4e-4932 to 3.4e+4932

Variable:

Variable is a name of memory location where we can store any data. It can store only single data (Latest data) at a time. In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function.

A declaration begins with the type, followed by the name of one or more variables. For example,

DataType Name_of_Variable_Name;

int a,b,c;

Variable Names

Every variable has a name and a value. The name identifies the variable, the value stores data. There is a limitation on what these names can be. Every variable name in C must start with a letter; the rest of the name can consist of letters, numbers and underscore characters. C recognizes upper and lower case characters as being different. Finally, you cannot use any of C’s keywords like main, while, switch etc as variable names.

Examples of legal variable names include:

x result out file best-yet

x1 x2 out_file best_yet

power impetus gamma hi_score

It is conventional to avoid the use of capital letters in variable names. These are used for names of constants. Some old implementations of C only use the first 8 characters of a variable name.

Local Variables

Local variables are declared within the body of a function, and can only be used within that function only.

Syntax:

void main(){    int a,b,c;}void fun1(){    int x,y,z;}

Here a,b,c are the local variables of void main() function and they can’t be used within fun1() Function. And x, y and z are local variables of fun1().

Global Variable

A global variable declaration looks normal, but is located outside any of the program’s functions. This is usually done at the beginning of the program file, but after preprocessed directives. The variable is not declared again in the body of the functions which access it.

Syntax:

#include int a,b,c;void main(){}void fun1(){}

Here a,b,c are global variables and these variables can be accessed (used) within the whole program.

Constants

C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.

  • Octal constants are written with a leading zero – 015.
  • Hexadecimal constants are written with a leading 0x – 0x1ae.
  • Long constants are written with a trailing L – 890L.

Character constants are usually just the character enclosed in single quotes; ‘a’, ‘b’, ‘c’. Some characters can’t be represented in this way, so we use a 2 character sequence.

Zpxs LUT5CObAn2wsW28icypt5BKEjh2wOPsgpy8KiMT7G18Qgp7VfRDEDLGWJW5dFskx4H3DjEaR340KRfZBM0ctoLbvbYoLEKvufwmY AZQS8m3qE ZTub1lBi1cLchncpFs8

In addition, a required bit pattern can be specified using its octal equivalent.

’44’ produces bit pattern 00100100.

Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes e.g. “Brian and Dennis”. The string is actually stored as an array of characters. The null character ” is automatically placed at the end of such a string to act as a string terminator.

Constant is a special type of variable which cannot be changed at the time of execution. Syntax:

const int a=20;




');}
Bc0138c3d2dab0944d91d638547c2715

subscriber

Leave a Reply

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

Accept Our Privacy Terms.*