Increasing and decreasing orders

Hello! Today I am going to show you how to read n numbers from the keyboard and rearrange them in an increasing or decreasing order.I hope this  helps you! Enjoy!

So,in order to do that you will need to work with arrays of numbers. Example code:

#include <iostream>

using namespace std;
int n,V[101],ok,i,aux;
int main()
{

    cin>>n;
    for (i=1;i<=n;i++)
        cin>>V[i];
    do
    {
        ok=0;
        for(i=1;i<=n-1;i++)
       {
           if (V[i]>V[i+1])
        {
            aux= V[i];
            V[i]= V[i+1];
            V[i+1]= aux;
            ok = 1;
        }
       }
    }

    while (ok==1);
    for(i=1;i<=n;i++)
    cout<<V[i]<<" ";

    return 0;
}
/*this code rearranges the numbers in an increasing order, if you want to
rearrange them in a decreasing order you have to change the if condition from
V[i]>V[i+1] to V[i]<V[i+1] */

 

Feel free to try the code yourselves, soon I will talk about reading the values from a file in case you have some values that are already generated.

Keep on coding 😉 !

Advertisements

Arrays

Hello! Today I am going to explain how arrays work and why they are so important in procedural programming.

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, five values of type int can be declared as an array without having to declare 5 different variables (each with its own identifier). Instead, using an array, the five int values are stored in contiguous memory locations, and all five can be accessed using the same identifier, with the proper index. These elements are numbered from 0 to 4, being 0 the first and 4 the last; In C++, the first element in an array is always numbered with a zero (not a one), no matter its length.

Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:

type name [n]

where type is a valid type (such as int or float), name is a valid identifier and the n field (which is always enclosed in square brackets []), specifies the length of the array in terms of the number of elements.

Therefore, the v array, with five elements of type int, can be declared as such:

int v[5];

Initializing an array

By default, regular arrays of local scope (for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.

But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example:

int v[5] ={0, 85, 264, 2, 4};

The number of values between braces {} shall not be greater than the number of elements in the array. For example, in the example above, v was declared having 5 elements , and the braces {} contained exactly 5 values. If declared with less, the remaining elements are set to their default values (which for fundamental types, means they are filled with zeroes). For example:

int x[5] ={1,2,3};

will save the values 1,2 and 3 on the first three positions and the rest will be filled with zeros.

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty []. In this case, the compiler will assume automatically a size for the array that matches the number of values included between the braces {}:

int v [] ={0, 85, 264, 2, 4};

Accessing the values of an array

The values of any of the elements in an array can be accessed just like the value of a regular variable of the same type. The syntax is:

name[index]

For example:

v[3] =150;

will change the value of the third element inside the array to 150. As you can see the expression name[index] acts as a normal variable of type int or float or whatever it is declared.

Example code:

#include <iostream>
using namespace std;

int v [] = {16, 2, 77, 40, 12071};
int n, result=0;

int main ()
{
  for ( n=0 ; n<5 ; n++ )
  {
    result =result + foo[n];
  }
  cout << result;
  return 0;
}
//this code will output the value 12206 inside the console

I hope this helped you acquire a basic understanding of arrays and if you have any further questions feel free to ask me !

Keep on coding 😉 !

Check if a number is palindrome

Hello! Today I am going to show you how to determine whether a number is a palindrome or not using a basic algorithm.

First of all, what is a palindrome number?

A palindrome number is a number that reads the same backwards as forward.

Now the code :

#include <iostream>

using namespace std;

int main()
{
   int num, reverse_num=0, remainder,temp;
   cout<<"Enter an integer : ";
   cin>>num;

   /* Here we are generating a new number (reverse_num)
    * by reversing the digits of original input number
    */
   temp=num;
   while(temp!=0)
   {
      remainder=temp%10;
      reverse_num=reverse_num*10+remainder;
      temp/=10;
   }

   /* If the original input number (num) is equal to
    * to its reverse (reverse_num) then its palindrome
    * else it is not.
    */
   if(reverse_num==num)
      cout<<num<<" is a palindrome number"<<endl;
   else
      cout<<num<<" is not a palindrome number"<<endl;
   return 0;
}

And this is how you check whether a number is a palindrome or not, I hope this helped you!

Keep on coding ;)!

The greatest common divisor and the least common multiple

Hello! Today I am going to show you another basic algorithm. one that finds out the greatest common divisor and the least common multiple of two numbers using repetitive subtractions. Enjoy!

#include 

using namespace std;

int main()
{
    int a,b,auxa,auxb, m;
    cout<<"a=";cin>>a;
    cout<<"b=";cin>>b;
    auxa=a;
    auxb=b;
    
    while (a!=b)
    {
      if (a>b)
        a=a-b;
      else
        b=b-a;
      }
    m=auxa*auxb/a;
    cout<<"The greatest common divisor is "<<a<<endl;
    cout<<"The least common multiple "<<m<<endl;
    return 0;
}

I hope this helped you! If you have any questions feel free to ask me!

Keep on coding 😉

Operators

Hello! Since almost any code requires operators and operators are one of the most important things in programming I thought I would make a post in which I am talking about them! Hope this helps you!

Enjoy!

First, what is an “operator”?

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations and there are multiple types of operators, the most common of them being arithmetic operators and logical operators.

Arithmetic Operators

There are following arithmetic operators supported by C++ language:

Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example
+ Adds two operands A + B will give 30
Subtracts second operand from the first A – B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
Decrement operator, decreases integer value by one A– will give 9

Relational Operators

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators

There are following logical operators supported by C++ language

Assume variable A holds 1 and variable B holds 0, then:

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.

Keep on coding 😉 !

Compare two numbers

Hello! Today I am going to show you the algorithm for comparing two numbers and printing the result inside the console, it is fairly easy so there shouldn’t be any problems.

#include <iostream>

using namespace std;
int a,b; // declaring the variables
int main()
{
    cout << "a= ";
     cin >>a; //reading the input from the console
    cout << "b= ";
     cin >>b;  //reading the input from the console 
     //comparing the two numbers
     if(a>b)
        cout<<a<<" is greater than "<<b;
     else if(a<b)
        cout<<b<<" is greater than "<<a;
     else if (a==b)
        cout<<"The introduced numbers are equal"<<'\n';
    
    return 0;
}

I hope this helped you ,you can try it yourselves inside code::blocks !If you haven’t seen the post in which I am explaining how to create a console application feel free check it out here.

Keep on coding 😉 !

 

“While” and “do…while” statements

Hello ! Today I thought I would talk about 2 other kinds of loops, the “while” and the “do…while” statements.Enjoy!

The while statement continually executes the same block of code as long as a condition is true.

Syntax:

while (condition){

//code here

}

You can implement an infinite loop by using the while statement as follows:

while(true){

//code here

}

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

do-while syntax:

do{

//your code here

}while(condition);

Notice how there is a semicolon at the end of the do-while statement. This is the only statement that ends in a semicolon so be careful not to forget using it ,thou I am pretty sure that the compiler will keep that in mind for you.

I hope this helped your understanding of the “while” and “do-while” statements.

Keep on coding 😉 !

For statement

Hello!

Now that we’ve talked about loops it is time to bring up the for statement. The for statement let’s you repeat a block of code over and over again and it is usually used to create loops that must be executed a specified number of times.

Syntax:

for ( init-expression ; cond-expression ; loop-expression){

//your code

}

Syntax Name When Executed Description
init-expression

 

Before any other element of the for statement, init-expression is executed only once. Control then passes to cond-expression. Often used to initialize loop indices. It can contain expressions or declarations.
cond-expression

 

Before execution of each iteration of statement, including the first iteration. statement is executed only if cond-expression evaluates to true (nonzero). An expression that evaluates to an integral type or a class type that has an unambiguous conversion to an integral type. Normally used to test for loop-termination criteria.
loop-expression

 

At the end of each iteration of statement. After loop-expression is executed, cond-expression is evaluated. Normally used to increment or decrement loop indices.

For example:

for (int i = 1; i<=5 ; i++)

cout << i;

This will output : 12345

Loop expression can be incremented ,decremented or modified in other ways too

Examples:

  • for (int i = 1; i<=20 ;i = i+2)
  • for (int i = 1; i<=20 ;i*i)
  • for (int i = 1; i<=20 ;i = i*3)

and so on!

I hope that now you have a basic understanding of the for statement in C++ 🙂

Keep on coding! 😉

Loops

Hello!

Today I wanted to talk about the “for” statement but I realized that I can’t talk about that without first talking about loops, so here we go.

There may be situations where you have to execute the same block of code multiple times,that’s where loops come in. A loop statement allows us to execute a statement or a group of statement multiple times without needing to write them over and over again in your code.

The C++ programming language provides us with the following types of loops to handle looping requirements:

Loop Type Description
while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do…while loop Like a while statement, except that it tests the condition at the end of the loop body
nested loops You can use one or more loop inside any another while, for or do..while loop.

But we also have a few loop statements, that I will talk about in another post, to help us control those loops so we can save time, for example :

Control Statement Description
break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
goto statement Transfers control to the labeled statement. Though it is not advised to use goto statement in your program because it can cause bugs ,make the program hard to understand and hard to modify.

If you need to execute a loop for an infinite number you can use an infinite loop. A loop becomes infinite if the condition set never becomes false,for example :

while(true){

your code here

}

or

for( ; ; ){

your code here

}

I hope this helped you understand how loops work and when you should use them.

Keep on coding! 😉

If statement

Hello guys! I decided to start posting about the basic statements in c++. Those statement are:

  • The “if” statement
  • The “for” statement
  • The “while” statement
  • The “do while” statement

Today I am going to talk about the if statement, I hope this helps you figure out how it works and how to use it. Enjoy!

The if statement is one of the most basic syntax and it allows you to control whether a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user’s input. For example, by using an if statement to check a user entered password, your program can decide whether a user is allowed access to the program. 


When programming, the aim of the program will often require the checking of one value stored by a variable against another value to determine whether one is larger, smaller, or equal to the other.

There are a number of operators that allow these checks.

Here are the relational operators, as they are known, along with examples:

  1.  “>”  means greater than ,for example 5>4 is TRUE
  2.  “<” means less than, for example 4
  3. “>=”means greater than or equal, for example 4>=4 is TRUE, while 4>=3 is also TRUE
  4. “<=” means less than or equal, for example 4<=4 is TRUE, while 3<=4 is also TRUE
  5. “==” means equal to, for example 4==4 is TRUE 
  6. “!=” means not equal to, for example 4!=5 is TRUE

Basic If Statement Syntax

The structure of an if statement is as follows: 

     if (TRUE)

         Execute condition



Here is a simple example that shows the syntax: 

   if(5<10)

         cout<<“What a surprise, 5 is lower than 10”;

If you want to add multiple commands in an IF STATEMENT you can use braces:

  if(5<10)

{

         cout<<“Hello!”<<endl;

         cout<<“What a surprise, 5 is lower than 10”;

}

 This will make the program execute both commands.

*”endl” will make sure that the next statement is printed on the next line and stands for end line.

 This is what your program will show without the “endl”:

And this is what your program will show with “endl”.

Be careful when using “endl”! Linux won’t read this command and your program won’t work, a replacement for endl that most programmers use is “\n” which does the exact same thing but is also accepted by linux.

Keep on coding! 😉