Showing posts with label c tutorial for beginners. Show all posts
Showing posts with label c tutorial for beginners. Show all posts

Thursday 17 October 2013

Do While In C++

Do While C:


In this C tutorial for beginners, we are going to discuss the third repetition structure known as do…while loop in c. In for loop, initially the loop condition is checked and then the statement is executed according to the loop condition. But if you want to execute the statement initially(first) and then check the loop condition then we use do…while loop.

Syntax:

do
       statement;
while (expression);



Do while loop in C++



Statement can be either a simple or compound statement. If it is a compound, enclose it between braces. In C++, do and while are reserved keywords.

Mechanism:

The statement executes first and then the expression is evaluated. If the expression is true then statement executes again else the loop will terminate.
A popular use of c do…while loop is that it can be used for input validation. Suppose that a user prompts to enter a test score which must be greater or equal to zero and less than fifty. SO, entries other than that should be invalid. For this we use do…while loop in c.

e.g:

int score;
do
{
    cout << “Enter a score between 0 and 50\n”;
    cin>>score;
    cout<<endl;
}
while (score < 0 || score > 50);

Final words:

In this c tutorial for beginners we discussed do while loop in detail. This is an important structure frequently used in C++. 
You can study and easily understand it here.


For Loop In C++

For Loop In C++:


The while loop discussed in our previous tutorial is a general form which can be implemented in a different form of repetitions. In this C tutorial for beginners, we are going to study second repetition structure known as for loop c. In C++, for loop is a specialized form of while loop. Its primary purpose is to simplify the writing of counter-controlled loops.
In while loop, you had to declare a counter variable and write an extra code to increment the counter in a while loop and the length continues as you increase the number of counters. But in for loop, you can do this all in just one line and that’s the reason why for loop is called a counted or indexed for loop.

Syntax:

for ( initial statement; loop condition; update statement)
      statement;



For loop in C++


in C++, for is a reserved keyword. The initial statement, loop condition and update statement enclosed in parenthesis control the body of the for loop statement.

The following are some common points regarding for loop:

  1. If the loop condition is initially false then the loop body doesn’t execute.
  2. The update statement alter the value of loop control variable which ultimately sets the loop condition to false until or unless the update statement is converging towards loop condition.
  3. C++ allows you to fractional values for loop control variables of the double type.
  4. A semicolon at the end of the for statement would make it an infinite loop
                     e.g: for ( int i=0; i<10; i++);
  5. In the for loop, if the loop condition is omitted then it is assumed to be true.
  6. If we omit all three statements in for loop then it would be legal but it would be an infinite for loop.
                    e.g: for( ; ; )
                                cout << “Hello World\n”;

Example:

for(int i=0;i<10;i++)
      cout<<i<<"  ";

this program will print numbers from 0 to 9 on console.It is a common example of c for loop.

Final words:

For loop is the most frequently used loop in programming languages.
It has been explained with detail  in this c tutorial for beginners.

While Loop In C++

While Loop In C++:

In C++, there are times when it becomes necessary to repeat a set of statements several times. One way is to write the code in the program over and over but that would make the code very long and it would become a messy code. Just imagine that if you have to repeat a set of statements 100 times then you have to write that 100 times again and imagine where the length of the code would go.
Fortunately, we have a way that finishes all this fuss and that is repetition structures. There are three repetition structures but in this C tutorial for beginners, we are going to study c while loop.

General form:

while (expression)
    statement




while loop in C++


In C++, while is a reserved keyword. The statement is a simple or compound statement. The expression acts as a decision maker and it is usually a logical expression. The body of the c while loop is between parenthesis.
The expression provides an entry condition. If the condition is true then the program enters into the while loop else the loop doesn’t execute. If the value is true then the while loop c will keep on going until the expression value becomes false or any break statement executes. But if the expression value never changes into false and there is no break statement then the while loop becomes an infinite loop. Infinite loop means that it will keep on executing.

Designing while loops:

There are many ways to design a while loop in c. Below are some cases that gives us the idea of the usefulness of this structure.

Counter-controlled while loops in c:

Suppose that we want to execute a simple or compound statement known number of times then we used an int variable which acts as counter and initialize it with zero and increment its value till the number of times we want to execute the statement. 

Below is an example:

int counter=0;
while(counter < size)            //size is the number of times 

                                           //we want to executes this while 
                                           //loop
    {
        .
        .
        counter++;
        .
        .   
    }

Sentinel-controlled while loop in c:

Sometimes, we don’t know that how many pieces of data need to be read but you know that there is a value on which this loop will terminate. Such special value is called sentinel. In this case, you read one value before the loop and then while loop will execute. 

Below is the example of this type of loop:


cin>>variable;                //taking the input before the loop
while (variable != sentinel)        //test the loop control //variable and sentinel is the terminating value that you know
{
    cin>>variable
    .
    .
    .
}

Flag-controlled while loop:

Flag controlled while loop uses a bool variable to control the loop. This loop looks like the one shown below:

bool found = false;
while (!found)
{
    If (expression)
        found = true;
    .
    .
}

Final words:

C while loop with its different types has been discussed in this c tutorial for beginners. By studying the given examples one can easily understand how to use while loop in c.

Preprocessor Directives In C

Preprocessor directives in C:

In C++, we don’t have large number of operations. Only small number of operation like arithmetic and assignment operations are available. But to run a C++ program many type of functions are required. C++ has a collection of libraries. We use them to get access to many interesting and important operations. Every library has a unique name and is referred to by a header file.

Examples:

The function needed to perform input/output (I/O) are contained in the header file iostream.
For performing useful mathematical operations like power, absolute and sine, we use a header file named cmath
If you want to use these functions, you need to tell the computer where to find the necessary code as you know computer is dumb. You use c pre-processor directives and the names of header files to tell the computer the locations of the code provided in libraries.
Preprocessor directives c
are commands supplied to the preprocessor that cause the preprocessor to modify the text of a C++ program before it is compiled. All preprocessor commands begin with #.

Syntax:

#include <header file name>

Example:

  • #include<iostream>
  • #include<cmath>


Note: These headerfiles are defined at the start so that you can use them throughout the program.



Namespace:

In earlier tutorials, we learnt about cin and cout. These functions are defined in iostream but within a namespace. The name of this namespace is std. We’ll discuss the namespace in detail in further tutorials. For now, we’ll stick to basics.

We declare it by writing:

using namespace std;

If we don’t use it then every time we have to introduce cout and cin like the one defined below throughout the program.
std::cin
std::cout

Final Words:

Preprocessor directives in c are very important.Without them the programming must have been very difficult.In this c tutorial for beginners we discussed them in detail so that our viewers can understand them easily.

Break And Continue Statements

Break And Continue Statements:

In this C tutorial for beginners, we are going to discuss a very useful facility of C++ which are break and continue statements.

Break statement in C:

Previously, we have seen that break statement was used in a switch structure. Similarly, you can use break statement in while, for and do…while loops. When a break statement executes in a repetition structure, it immediately exits from the repetition structure. There are times when our requirement is met but the loop still doesn’t finish so, we use this break statement condition. This make our code efficient and less time consuming.

It is used for two purposes:

  • To exit early from the loop.
  • To skip the remainder of the switch structure.
The use of break in c can eliminate the use of many (flags) variables. However, the break statements in c should be used very carefully as the excessive use of it will make your code an ugly code. Use it just when you’re sure that what you wanted from the code has been achieved.

Example of break in c:

 int sum=0, num=0;
cin >> num;
while(cin)
{
    if (num<0)
    {
        cout << “Negative number found\n”;
        cin>>num;
        break;
}
    sum+=num;
    cin>>num;
}

Continue statement in c:

Continue statement in c is used in while, for and do…while loop. When continue statement executes, it skips all remaining statements in loop for that certain iteration and proceeds with the next iteration of the loop. 

Let’s take an example of continue in c:


int sum=0, num=0;
cin >> num;
while(cin)
{
    if (num<0)
    {
        cout << “Negative number found\n”;
        cin>>num;
        continue;
}
    sum+=num;
    cin>>num;
}

In this program, if the num is negative then it doesn’t execute the further statements and proceeds with the further iteration else it does.

Final words:

 In this c tutorial for beginners of shapes in c we discussed about break and continue statements in detail.
These are very important and commonly used conditions in C++. You can understand and learn it here.

Sunday 6 October 2013

Control Structures ( if else c)

Control Structures (If else statement):

If-else and else-if c are very important conditions in C++. In this c tutorial for beginners  we are going to focus on control structures of if and if…else.

Control structures are really useful because they allow us to decide between different conditions. 
In C++, there are two types of structures:
  •  Control structure
  •  switch structure.

This tutorial discusses how if and if…else statement can be used to create one-way, two-way and multiple selections. The switch structure will be discussed in coming tutorials.

One-way selection:

If we want to decide between a single condition like “It will rain today”. There are two possibilities that it will rain today or it will not rain today. To decide between these two conditions, we use one way selection (if statement).

Syntax:

If (expression)
    Statement;

If is a reserved keyword. This syntax starts with if and futher is an expression in a parenthesis. So, if the expression value is true then statement will execute otherwise, it won’t. The expression in the parenthesis is also called decision maker. The expression is usually a logical expression. The statement following the expression is also called action statement.

If else (one way selection)


Example:

If (score >= 90)
Grade = ‘A’;    //if the expression is true then grade  is   assigned to value A otherwise not.

Two-way selection:

There are situations where we have two choose between to alternatives. For example, if a student’s attendance in his/her semester is greater or equal to 80 % then he/she will pass the course else he/she will fail. For this, we use two way selection. For this selection, C++ provides use if…else statement.

Syntax:

If (expression)
    Statement1;
else
    Statement2;

Let’s see how this structure works. If expression is true then statement1 will execute else statement2 will execute.

If else (two way selection)


Final words:

 Control structures are important in decision making among different statements.They are above stated with their syntax and examples.They can be studied from this c tutorial for beginners of shapes in c.

Logical Operators

 Logical Operators:

C++ provides us the facility of combining logical expression and evaluate their behavior. So, in this C tutorial for beginner, we are going to discuss  logical operators in c. We are going to discuss how to form and evaluate logical expressions and see how they work.

Below are three logical operators in C++ that we normally use:

Operator        Description

  1. !                    not
  2. &&                and
  3. ||                    or

Logical operators in c take two logical values, combine them and finally gives one logical value.

Expression            !expression

True (nonzero)            false (0)
False (0)                     true (1)

When you put not “ ! ” operator with expression it changes
  1. True to false
  2. False to true
  3. Nonzero to zero
  4. Zero to one

Let’s see some examples of “not” operator:

  1. ! (‘B’ > ‘A’)          !(true)             false
  2. !( 1 <= 10 )        !(true)             false
  3. !(1 != 1)            !(false)             true

Let’s see some examples of “and” operator:

  1. ( 100 >= 101 && 100 <= 101)                          false
  2. ( “shapes” == “shapes” && “me” == “me”)        true
  3. (!false && true)                                                true
  4. (1>0 && 1<0)                                                   false

Let’s see some examples of “or” operator:

  1. ( 100 >= 101|| 100 == 101)                             false
  2. ( “shapes” > “shapes” || “me” == “me”)            true
  3. (!false || !true)                                                true
  4. (1==0 || 1<0)                                                  false


Final words:

Logical operators are important in C++ programming. They have been discussed in detail in this c tutorial for beginners.
We hope that this post will be help full for our viewers.

Relational Operators in C++

Relational Operators In C++:

To make decisions in a C++ program, you must be able to compare conditions. So, in this C tutorial for beginners we’re going to discuss relational c operators. For example, if we want to see who has the highest, average and lowest marks in some class then we need to develop such algorithm which would require comparing marks of students so, we are going to need relational c operators for that.

In C++, a condition is represented by a logical expression. It would be either true or false. And true and false are Boolean values.

Consider:

            i>j        // i and j have some int values stored in them
It is a logical expression so, it would either have a true value or a false. “ > ” is a relational c operator. And relational operators allow you to make comparisons in a C++ program.
C++ includes six relational operators.

Operator                Description

  1. ==                      equal to
  2. !=                       not equal to
  3. <                        less than
  4. >                        greater than
  5. <=                      less than or equal to
  6. >=                      greater than or equal to

Note:

 “ ==  “ and “ =  “ are different signs. “ ==  “ is a double equal sign known as equality operator ad used to check equality of operands whereas “ = “ is known as assignment operator.

Expression            Result

  1. 1 < 10                true
  2. 2 == 2                true
  3. 4 > 11                 false
  4. 6.1 <= 7.9           true
  5. 5.8 >= 7.3           false

Relational operators in c can also be used to compare char values.

For example:

‘R’ > ‘T’            False
‘+’ < ‘*’             False
‘A’ <= ‘a’           False

Relational operators in c can also be used to compare strings.
  • string str1 = “Hello”
  • string str2 = “Hi”
  • string str3 = “Hello”
  • string str4 = “Air”

  • str1 < str2         true
  • str1 == str3       true
  • str1 > str 2        false
  • str < “An”          true

Final words:

 Relational operators are very important in C++ programming. They are the fundamental tools for comparing different things. In this C tutorial for beginners they have been discussed in detail with examples.

Creating A C++ Program

How to Create a C++ program??

In this C tutorial for beginners, we are going to learn how to create C++ programs with output. After studying previous tutorials, we now have the basic and required concepts needed to create a C++ program. A C++ program is a collection of function, one of which is the function main. A function is a set of instructions designed to accomplish specific task. We’ll deal with functions in further tutorials in detail.

The syntax of the function main is:

int main()
{
    Statement 1
    Statement 2
    .
    .
    .
    Statement n

return 0;
}

This main function body contains two type of statements:

1. Declaration statement:

Declaration statements are used to declare things as    variable.

2. Executable statements:

Executable statements perform calculations, manipulate data, create output, accept input and so on. Some executable statements that we came across with are assignment, input and output statements.

 The return 0 function is necessary and is always the last statement. In C++, return is reserved keyword.
 
This main function should be saved in .cpp extension file. 

The file containing this main function or source code is called the source code file or source file.

Things stated step by step needed for creating C++ program examples:

  • Comments if needed to introduce some information about your program
  • Use preprocessor directives to include header filese.g: #include<iostream>
    using namespace std;
  • Then we introduce any global scope variables if necessary.
  • Then we introduce main body as explained above with syntax.


Now, we’ll show you  simple c program examples to explain everything that we mentioned above.

//******************************************************
// Made by shapesinc.blogspot.com
//******************************************************

#include<iostream>    //preprocessor directive
using namespace std;

int main()
{
    int a, b, c;    //declarative statement
    double x, y    //declarative statement

    a=4;        //assignment statement
    cin >> b;    //input statement
    cout << a << “ ” << b <<endl;    //output statement
    return 0;
}

Order Of Operator Precedence In C++

 Order Of Operator Precedence In C++

C operator precedence is the most important thing in calculating  arithmetic, relational and logical operations. So, now we need to discuss the order of operator precedence in C when all these operators come in a single expression. In this C tutorial for beginners, we are going to discuss their order of precedence.

For example:

The expression like the ones below:

  •  11> 1 || !9 && 5+5*2 && 6%8
  •   2 > ‘A’ && 7*4 !true + (2 % 5 * 3 – 1 + 5)

How we are going to decide that which operator should be calculated first ,this will be done according to the operator precedence in c.
For this we need to know the c operator precedence order  when they are together.

          Operators                          Precedence

  1.   ! , + , - (unary)                            first
  2.       * , / , %                                 second
  3.         + , -                                      third
  4.   < , <= , > , >=                            fourth
  5.       == , !=                                    fifth
  6.         &&                                       sixth
  7.          ||                                       seventh
  8.   = (assignment operator)              last

Note: 

In C++, | and & are also operators. The behavior of these operators is different from && and ||.

Examples:

1.           !true && (20 >= 18)            
     First, we’ll evaluate !true which false and then (20>=18)      which is true and then we’ll use && which will give us    false.

2.           (2*10>10 && 2*10 == 20)        true

      First we’ll calculate, 2*10 which is equal to 20 then 20>10 which is true and then 20 == 20 which is true and when we apply && on it we get true value.

Final words:

C operator precedence  is very important while we are dealing with arithmetic , relational and logical operations.Keeping this fact in mind shapes in c has designed this C tutorial for beginners for its users which will help them out to understand how to solve such expressions.

Saturday 5 October 2013

Cout in C++

Cout in C++:

In previous tutorial, we learnt how to store data. Now we will learn in this C++ tutorial that how to print that desired result on the console.
In C++, output on the standard output device is accomplished through the use of "cout" and the operator “ << ”.

Note: 

The standard output device is usually the screen.

Syntax:

cout << expression or identifier ;

This is called an output statement. In C++, "<<" is called the stream insertion operator.

Example:

 Here are some simple c programs with output to show the use of this command.
1.  char ch = A.
     cout << ch;

Output:

A                             //This A was stored in char variable ch

2.  cout << ‘A’;

Output:

A                             //This A was hard coded

For char ch variable, you didn’t needed double quotes but for hard coded ‘A’ you needed double quotes.

Statement                                                  Output
cout << 29 / 4 << endl;                                   7
cout <<“Hello World”<< endl;                    Hello World
cout <<20<< endl;                                         20
cout <<3.2<< endl;                                       3.2
cout << ”29 / 4“ << endl;                             29 / 4
cout <<20 + 100<< endl;                              120        
cout <<‘A’<< endl;                                          A
cout <<“4 + 16 =”<<4 + 20 <<endl;           4 + 16 = 20
cout <<2 + 3 * 4<< endl;                               14
cout <<“Hello \nWorld”<< endl;                Hello
                                                                                World
Look at the statement cout << “Hello \nWorld” << endl;
This statement contains \n. It is a newline character. It causes the insertion point to move to the beginning of the next line before printing there. That’s why it prints Hello one line and World on the next line.

Note:In C++, \ is called the escape character and \n is called newline escape sequence.
If we don’t assign any value to a variable and try to cout it on the screen then it will print a junk value.

Example:

int num;
cout << num <<endl;
The output will be some junk value.

Final Words:

In this c tutorial for beginners we have discussed how to print something on console with the help of cout in c ++.We have also showed some c programs with output which clarify the use of cout command in C++.

Indentation in C++

Indentation In C++:

In this c tutorial for beginners, we are going to discuss about indentation meaning.

Indentation has come from indent meaning the correct alignment of the code. The order of alignment does not affect the execution of program in any way. Indenting is only done to make the code neat and clean and to get the idea of how the code works and which step is connected to which. It is a good programming practice that you indent your code after writing it. If you do not indent it then we won’t get to know that how the code is working.

Example:

indent meaning

This is a bubble sort program. You can see that the code is unindented.
1.       The int temp=0; is typed one step forward which should have been just below int arr[size].  
2.       Arr[i] is just before the for loop so, in this way you cannot tell that if it is a part of the for loop or not.
3.        The if condition should have been below the for loop which has iterator ‘j’ and its parenthesis are also not at its place.
4.       The starting and ending parenthesis are also not at their place.


indent meaning

This is the indented code of bubble sort algorithm.

Steps for indenting:

  •  First see that the related loops, conditions and statements are correctly aligned and have a connection or not.
  • Then see if there are unnecessary new lines. If there are , then remove them.

Keyboard shortcut keys:

Auto indenting:

For auto indenting, select that part of code which you want to indent and then first click ctrl+K and then ctrl+F.

Key: Ctrl+K, Ctrl+F

Final Words:

In this post of shapes in c, you have learnt the meaning, use and advantages of indenting. In this c tutorial for beginners, we discussed the topic of C++ indentation in detail and each and every aspect of how it can be used and what steps should be kept in mind while indenting one’s code.