Wednesday, November 13
Two Dimension Pointers C++
Pointers are very useful construct of C++ programming language and what is more useful is 2d pointers.
The pointers are special variables pointing to a memory location or a variable where as an array is a collection of those variables. A 2d pointer is a pointer which is pointing to array of pointers.
e.g.
The pointers are special variables pointing to a memory location or a variable where as an array is a collection of those variables. A 2d pointer is a pointer which is pointing to array of pointers.
e.g.
//Assign an array of 5 nameless pointers to a 2d pointer
int **pointer = new int*[5];
//then assign values to each array
for(int i=0;i<5; i++)
{
pointer[] = new int[10];
}
//now we have a 2d pointer which can be also accessed as array
pointer[2][9] ; //this is third row and 10th element
Tuesday, November 12
Arrays in C++
Hey Guys.
This blog is related to a datatype in c++ that you'll find enormously helpful in your future assignments and semester projects.
So, to answer the very first question : "What is an Array ?"
Formally, 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.
Confused ? I'd be surprised if you weren't.
Think of it like this, you have 5 numbers. Now as a beginner in C++, i'll make ten different variables and the store them in separately in these variables. Like this :
By using array, we can use a single datatype to store multiple related elements within a closed structure. This makes it easier for us to access the values and acquire less space in the memory (10 elements in an array use less space than 10 different variables).
A typical way to initialize an array in c++ is :
datatype name [no. of elements] ;
The concept of arrays is very helpful for data structures.
You get a very good idea of memory management in c++. This concept will help you guys a lot in your 1st semester projects. Be it small databases, games, or anything. You'll always find arrays quite helpful.
Until next time.
This blog is related to a datatype in c++ that you'll find enormously helpful in your future assignments and semester projects.
So, to answer the very first question : "What is an Array ?"
Formally, 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.
Confused ? I'd be surprised if you weren't.
Think of it like this, you have 5 numbers. Now as a beginner in C++, i'll make ten different variables and the store them in separately in these variables. Like this :
int a=1; int b=5; int c=11; int d=19; int e=30;Now in order to access these stored values, we'll have to call each element by its distinct name.
By using array, we can use a single datatype to store multiple related elements within a closed structure. This makes it easier for us to access the values and acquire less space in the memory (10 elements in an array use less space than 10 different variables).
A typical way to initialize an array in c++ is :
datatype name [no. of elements] ;
//we shall now declare some arrays
//Suppose we want to make an array of 10 integer numbers.
int array1[10];
// we can assign elements to the array like this:
int array1[10] = {2,4,6,8,10,12,14,16,18,20};
float array2[5] = {3.14, 2.27, 0.6990, 4.5, 123.4};
string array3[3] = {"Porsche", "Lamborghini" , "Maserati"};
//Note that in an array of 10 elements, values are indexed as 0-9
// now we can access the values in the array using their index number
print(array1[0]); // 0 is the index number of the element in the array
// we'll get 2 in the output
//similarly
print(array2[3]); //This will print us 4.5
print(array3[1]); //This will print us Lamborghini
//In order to print every element of the array, we use for loop
for (int i=0; i<10; i++)
{
print(array1[i])
print(endl);
}
//This will print every element in the array1
//value of i will determine the index number of the element to be printed
//P.s. use cout statement instead of print command :)
The concept of arrays is very helpful for data structures.
You get a very good idea of memory management in c++. This concept will help you guys a lot in your 1st semester projects. Be it small databases, games, or anything. You'll always find arrays quite helpful.
Until next time.
Monday, November 11
Diamond Printing Problem from Uxama Ahmad
The problem was diamond did not print odd rows with required spaces and stars.
#include <iostream>
using namespace std;
int main()
{
int num,i=1,j=1,k=1,space,star;
cout<<"Enter odd number of rows: ";
cin>>num;
if(num%2==0)
num=num-1;
space=num/2;
star=1;
cout<<endl;
do
{
if(space!=0)
do //prints spaces
{
cout<<" ";
k++;
}while(k<=space);
k=1;
do //prints stars
{
cout<<"*";
j++;
}while(j<=star);
j=1;
cout<<endl;
i++; //current row number for diamond
if(i==(num/2)+1)
{
space=0;
star=num;
}
if(i<=num/2)
{
star=star+2;
space--;
}
if(i>1+num/2)
{
star=star-2;
space++;
}
//star=2*i-1;
}while(i<=num);
return 0;
}
sample outputSunday, November 10
Function Pointers : the power of C
Function pointers are a very powerful yet misunderstood aspect off programming languages.
A function pointer is simply a points to the address of a function in memory instead of pointing to a data variable like a regular pointer.When dereferenced, a function pointer can be used to invoke the function it points to and pass it arguments just like a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked indirectly through a variable instead of directly through a fixed name or address.
So, now why is such a simple construct so powerful? Its because the i
t allows us as developers to do things which wouldn't be possible without function pointers, a simple example is that a function pointer allows us to replace very long switch statements.
t allows us as developers to do things which wouldn't be possible without function pointers, a simple example is that a function pointer allows us to replace very long switch statements.
let us take the following code
float Add(float a, float b) { return a+b; }
float Sub(float a, float b) { return a-b; }
float Mul(float a, float b) { return a*b; }
float Div(float a, float b) { return a/b; }
//now we write a function thattakes 3 parameters first two are floating point
// numbers and third is a function pointer
float MathOp(float a, float b, float (*FuncPtr)(float, float))
{
return FuncPtr(a,b);
}
int main()
{
//Now we can simply call MathOp with appropriate arguments
float x= MathOp(10,5,&Mul);
cout<<x<<endl;
return 0;
}
In the above code the important thing is the declaration of a function pointer.
float (*FuncPtr)(float, float)
Let us break it down.
first is the return type of the function pointed to by the function pointer. which is this case is float.
Second is part is (* FunctionPointerIdentifier) . The parentheses and the * are the syntax declaring it as a function pointer and must not be confused as anything else. The asterisk is followed by any identifier for the function pointer.
The third part is the parameter list of the function pointed to by the function pointer.
Thus a function pointer can point to any function that has the same return type and parameter list as those declared in that function pointers declaration So,all functions, you want to use with the same function pointer, must have the same parameters and return-type!
This was just a very basic introduction to Function Pointers. There are a lot of other things that make function pointers such a powerful tool.
Functions Continued (Functions Input)
Input in functions : type of input
We can use functions by 2 methods of input:
- input as passing arguments by values [Part 1;]
- input as passing arguments by reference [Part 2;]
Part 1; using function : passing arguments by value
Problem 1; scope of variable and functionality
- In this type, we give function the value of a variable not that variable...!!!
- Function creates a local scope variable (local to the functions body only)
- It does not change the value of original variable.
- Say we ran an square function which takes argument by value and argument is x
- When function is called it reserves memory of ram and makes a copy of value of x and runs operations on this copy
- In the end when it returns value then function is removed from memory so is that copy of variable
- Original variable remains intact
- This is how scope of variable is defined
Problem 2; returning complex values
Say we have to make a function which takes 5 variables and returns separate value
How to return this: compare those variables for largest one? Obviously we can't return this:
return if (num1>num2&&num1>num3){num1}; and if we have to put all five variables confirmation statements?
Here is a tip: make a local scope variable which will collect all those values which has to be returned in the end i.e.
_________________________________________________________________________________
int result; //this variable only exists while function is working when it is done this variable
will be removed so it is a local variable to this function only / must not match existing one
if (num1>num2&&num1>num3){result=num1;}
if (num2>num3){result=num2;}
else {result=num3;}
return result;
_______________________________________________________________________
Very easy!
Now every time you can just create your required variable and save returning values in it and return it easily....!!!!
==================================================================================================================================================
Till next time.. Please let me know your problem with syntax or logic or error so i can make better understanding in the article...!!!
Do comment in section below :)
Do comment in section below :)
Saturday, November 9
Factorial Using Recursive Function
#include <iostream>
#include <conio.h>
using namespace std;
int Factorial(int number)
{
if (number <2)
{
return 1;
}
else
{
return (number * Factorial(number - 1));
}
}
void main()
{
int num;
cout << "Enter Number: ";
cin >> num;
int fact = Factorial(num);
cout << "\nFactorial: " << fact;
_getch(); //use 'getch()' if you are using version older than Visual Studio 2013.
}
Friday, November 8
Macros In C++ By Umair Sajid
Macros In C++ By Umair Sajid
Macros : are pre-processor directives Just As#include<stdio.h>
#include<graphic
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
#include<dos.h>
#include<iostream>
but In Above Directive Directs The Compiler to include followings library functions . However We Are Concern with the Macros.
Syntax: #define ADD x+y
Actually They Can Be think As Same As Functions But Just Defined Before Main and with A little difference of Syntax and working. In a Nutshell You can Call Macros as Functions Using As A Variable
Use: Macros In C++ Is Usually Used Where We Required Fast Execution. However The Same Work Can be Done By Using Functions But The Function can pass arguments and require a return_type of the Integers or Result Return.
Lets Come To A Simple Program That prompt the user to enter a number and prints its cube and square using macros.
#include<iostream>
#define SQUARE num*num // MACROS
#define CUBE num*num*num // MACROS
using namespace std;
int main()
{
int num;
cout<<"\n\t\tEnter A Number : "; // prompt to enter a number
cin>>num; // store it in num
cout<<"\n\t\tThe Square of "<<num<<" is : "<<SQUARE<<"\n"; // Just as function call we have used
cout<<"\n\t\tThe Cube of "<<num<<" is :"<<CUBE; // macros
cout<<"\n\n";
cout<<"\n\t\t***THANKYOU PC Umair Sajid ****\n\n";
}
Increment Decrement Operators
C++ has a great feature of increment and decrement operators.
increment means to increase value and decrement means to decrease value.
e.g.
increment means to increase value and decrement means to decrease value.
e.g.
int apples = 10 ; apples = apples + 1 ; //increments by 1 apples = apples - 1 ; //decrements by 1 //now apples ==10 //in C++ we can do this more easily with increment and decrement operators. apples++; //increments apples--; //decrements Type of increment/decrement operators PostFix: it changes value of variable after rest of the statement is executed. Prefix: it changes value before any other calculation. e.g. int oranges = apples++; /* oranges will now be 10 and after execution apples value will increase by 1 so apples=1 */ //similarly this will result in 10 oranges and 10 apples oranges = --apples; //first apples will be set to 10(11-1) and then oranges = apples = 10; /* We can see in the above example that --apples/++apples or vice versa changes the value of apples. The compiler reads the following line : */ oranges = ++apples ; // change apples = apples+1. Then set the value of Oranges = apples (new value) /*So the statement has altered the original value of apples. // If we do not want to change the value of apples and still set the value of oranges, then we do the following : */ oranges = apples+1; //So the value of apples remains intact and +1 value is set for oranges :)
Simple void function use by Usman Sherry
Use of a Simple Void Function
#include<iostream>
using namespace std;
void function(); ////void type function
int main()
{
function(); //// not necesserely use inside cout statment
cout<<endl; //// as it is a display. Align it properly if needed
return 0;
}
void function() //// returns nothing
{
cout<<"This line would be simpaly displayed if this function is called";
} //// no return used
//////////// you can also use loop for a display i.e. triangle or diamond and function will just print on screen ///////////////////////////
Best Explanation of Functions by Usman Sherry
00:05
By
Usman Shery
c++
,
C++ Functions Explained
,
usman sherry
,
void functions c++ use
3
comments
Some basic understanding to use functions:
First of all we have to look for output of functions as we want
- void
- int
- double
- and so for other types. The major difference is between void and non-void (integral, character and float) outputs.
Void: (with no arguments)
------------------------------------------------------------------------------------------------------------
- #include<iostream>
- using namespace std;
- void function(); //with or without arguments dose not effect it's output type
- void main()
- {
- function();
- }
- void function()
- {
- cout<<"To display something "<<endl;
- } // void type returns no value with or without argument
------------------------------------------------------------------------------------------------------------
Output will be:
To display something Press any key to continue . . .
------------------------------------------------------------------------------------------------------------
Void: (with arguments)
------------------------------------------------------------------------------------------------------------
- #include<iostream>
- using namespace std;
- void function(int); //with or without arguments dose not effect it's output type
- void main()
- {
- int y;
- cin>>y;
- function(y);
- }
- void function(int y)
- {
- cout<<"Square is :"<<y*y<<endl;
- } // void type returns no value with or without argument
------------------------------------------------------------------------------------------------------------
Output will be: (let y=5)
Square is :25 Press any key to continue . . .
_________________________________________________________________
------------------------------------------------------------------------------------------------------------
Other types of outputs:
without argument
------------------------------------------------------------------------------------------------------------
- #include<iostream>
- using namespace std;
- int function(); //with or without arguments dose not matter it's output type
- void main()
- {
- cout<<function()<<endl;
- }
- int function()
- {
- return 5*99;
- } // must return a value
------------------------------------------------------------------------------------------------------------
Output will be:
495 Press any key to continue . . .
------------------------------------------------------------------------------------------------------------
with argument
------------------------------------------------------------------------------------------------------------
- #include<iostream>
- using namespace std;
- int function(int,int); //with or without arguments dose not matter it's output type
- void main()
- {
- int x,y;
- cin>>x>>y;
- cout<<function(x,y)<<endl;
- }
- int function(int x,int y)
- {
- return y*x;
- } // must return a value
------------------------------------------------------------------------------------------------------------
Output will be: (x=5 / y=3)
5
3
15 Press any key to continue . . .
------------------------------------------------------------------------------------------------------------
Thursday, November 7
Pointer to array Declaration and Definition
Many of you has question in your mind that how to declare and define Pointer to Array in C++.
I 'll show how?
I 'll show how?
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
//int pointer to array declaration.
int *pointer_array[10];
//defining pointer to array.
for(int i=0; i<100; i++)
{
pointer_array[i] = new int[5];
for (int j=0; j<5; j++)
pointer_array[i][j] = -1;
}
getch();
}
Array Sorting with Selection Sort
In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity.
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
For more detail use Wiki... Selection Sort
#include <iostream>
#incl
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
For more detail use Wiki... Selection Sort
#include <iostream>
#incl
ude <conio.h>
using namespace std;//Selection Sort Function
void Ssort(int *a,int length)
{
int temp;
for(int i=length-1;i>0;i--)
{
int first=0;
for(int j=1;j<=i;j++)
if(a[j]>a[first])first=j; temp=a[first];a[first]=a[i];a[i]=temp;}
}
void main()
{
int arr[10];
int temp[10];
arr[0]=100;
arr[1]=33;
arr[2]=43;
arr[3]=26;
arr[4]=46;
arr[5]=88;
arr[6]=52;
arr[7]=17;
arr[8]=53;
arr[9]=77;
for(int i=0;i<10;i++)
{
temp[i]=arr[i];
cout<<arr[i]<<",";
}
//calling selection sort function
Ssort(temp,10);
//Displaying the result.
cout<<endl<<endl;
for(int i=0;i<10;i++)
cout<<temp[i]<<",";
getch();
}
Smallest of integers alternate approach
//code by http://CppQA.blogspot.com
//we are community of developers focusing on help for new programmers
#include <iostream>
using namespace std;
#define CHAR_BIT 8
/*Function to find minimum of x and y*/
int min(int x, int y)
{
return x + ((y - x) & ((y - x) >>
(sizeof(int) * CHAR_BIT - 1)));
}
/* Function to find minimum of 3 numbers x, y and z*/
int smallest(int x, int y, int z)
{
return min(x, min(y, z));
}
int main()
{
int x = 1, y = 100, z = 90;
cout << "Minimum of 3 numbers is " << smallest(x, y, z) << endl<<"http://CppQA.blogspot.com"<<endl;
return 0;
}
you can fork this code on ideone.com
Wednesday, November 6
Swapping without use of third variable
23:14
By
Unknown
swapping in three steps
,
swapping using multiplication operator
,
swapping variables without another variable
8
comments
Swapping means to interchange values of usually two variables and is done using third temp variable e.g.
But take a look at code swapping without use of third variable, this trick will come handy in future assignments
For the person who can explain this code to me and post a solution using (^) operator, there is a GENUINE MICROSOFT VISUAL STUDIO KEY ;)
You can post a request for guest post in comments, anywhere
int var1 = 10, var2 = 20; int temp = var2; var2 = var1; var1 = temp; //now var1 = 20 and var2 = 10 //hence values have been swapped
But take a look at code swapping without use of third variable, this trick will come handy in future assignments
int var1 = 10, var2 = 20; var1 = var1 * var2; var2 = var1 / var2; var1 = var1 / var2; //now var1 = 20 and var2 = 10 //hence values have been swapped
For the person who can explain this code to me and post a solution using (^) operator, there is a GENUINE MICROSOFT VISUAL STUDIO KEY ;)
You can post a request for guest post in comments, anywhere
Smallest Integer Without Using Comparison Operator
#include <iostream>
using namespace std;
#define CHAR_BIT 8
/*Function to find minimum of x and y*/
int min(int x, int y)
{
return y + ((x - y) & ((x - y) >>
(sizeof(int) * CHAR_BIT - 1)));
}
/* Function to find minimum of 3 numbers x, y and z*/
int smallest(int x, int y, int z)
{
return min(x, min(y, z));
}
int main()
{
int x = 12, y = 15, z = 5;
cout << "Minimum of 3 numbers is " << smallest(x, y, z) << endl;
return 0;
}
Special Diamonds Continued -- Usman Sherry
(Continued From Special Diamonds Part 1)
Part 2;
Here will use 2 loops inside one loop so that it is easy to print shape in less loops and coding;
It is simple because the loop we used for triangle in first page is going to be repeated in this loop only we will change the size alignment of shapes upside down;
int i,j,k,rows,size1,size2;cin<<rows;size1 [as described before you have to choose sequence of shapes so ]size2 [there are two options size1=1 and size2=rows /// or size2=rows and size1=1]do{ j=size1;do{cout<<”required character”;j--;} while (j < size);size1 ?? ; //here you define corresponding proceeding sizek=size2;do{cout<<”required character”;k--;} while (j < size);size2 ?? ; //here you define corresponding proceeding size}while(i<rows);I hope you have got the ideado{ //the main loopdo{ //corresponding first shape}whiledo{ //corresponding second shape}while}whileAnd in case of diamond you have to detect central row and print same size pyramid upside and then same size pyramid downsideTo detect central row è total rows / 2 = central row -1 //do not use this in codei.e. central row=(total rows/2 +1); //use this in code to detect central rowin this way you can print first part then print single row of size of central row then print second part so that the both main loops will have same size and almost same coding;
first main loopcentral rowlast main loop
Special Diamonds Program Set
A post by Usman of BESE 19 at MCS.
The simple program logic for Diamond printing program:
1.
We could simply use four
nested loop sets for printing this shape as in part 1;
but it would take about 8 loops for
printing a sum of 4 shapes structure [ in diamond 4 triangles are summed up to
make its structure ]
so to make it a bit simple [ 4 + 2 loop in
which 4 loops are for triangles and 2 loops join them ] we divide it into 2
parts instead of 4 like in part 1, this is described in part
2;
2.
Part 2 has simple loop
nesting by dividing main shape into 2 parts as Upper half and Lower half;
Part 1;
This will help you understanding loops for
printing shape’s basic structure which is triangle in this topic;
a.
Make simple triangle of 2
loops as a set is very basic;
int i,j,rows,size;
cin>>rows; //take input
size = rows; //give the initial size of shape which is decreasing
size = 1; //if shape is increasing then size is 1
do //it will run row’s * time
{ j=size; //it will change size of rows constantly
do //this loop is always as this format whatever shape is decreasing or increasing as it has to print a line of given width anywhere required
{
cout<<”required character”; // do not put endl here as it is a continues line
j--;
} while (j < size);
size--; //if size of shape is decreasing downwards
size++; //if size of shape is increasing downwards
cout<<endl;
}while (i<given rows);
Please visit next part at Special Diamonds Part 2













