Category Archives: C & C++

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to get Device Orientation in Cocos2D, iPhone in Objective C?

Hello all……
We may need to know that what is your current device orientation.
Using the below code you can do this.

if([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortrait) {
            NSLog(@"Device is now in Portrait Mode");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeLeft) {
            NSLog(@"Device is now in LandscapeLeft Mode ");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeRight) {
            NSLog(@"Device is now in LandscapeRight Mode");
}
else if([[UIDevice currentDevice]orientation] ==
  kCCDeviceOrientationPortraitUpsideDown) {
            NSLog(@"Device is now in PortraitUpsideDown Mode");
ss="Apple-style-span" style="font-weight: normal;">
}

Note: If you have to explicitly set the orientation of your phone to any of the above you can set this in the appDelegate.m file. You can put an “||” (OR) symbol in between to set more than one.

Please leave your valuable comments if this post was useful…..

Binary Search in C Arrays – An Example

Hi,

Want to search for an item in C Arrays, using Binary Search ? Use the following sample of code to search in C Arrays using Binary Search.


#include <stdio.h>
#define SIZE 10

int binarySearch( const int b[], int searchKey, int low, int high );

int main() {
   int arr[ SIZE ];
   int i;
   int key = 5;
   int result = -1;

   for ( i = 0; i < SIZE; i++ ) {
      a[ i ] = 2 * i;
   }

   result = binarySearch( arr, key, 0, SIZE - 1 );

   if ( result != -1 ) {
      printf( "n%d is in the array %dn", key, result );
   } else {
      printf( "n%d Not in the array!n", key );
   }

   return 0;

}

int binarySearch( const int b[], int searchKey, int low, int high )
{
   int middle;

   while ( low <= high ) {
      middle = ( low + high ) / 2;

      if ( searchKey == b[ middle ] ) {
         return middle;
      } else if ( searchKey < b[ middle ] ) {
         high = middle - 1;
      } else {
         low = middle + 1;
      }
   }
   return -1;

}

Guess the output!
:)

How to search for a particular character in a C++ string ?

Hi,

In order to search for a particular character in a C++ string, use the following code.

#include <iostream>
#include <cstring>

using namespace std;

int main() {

  const char *testStr= "coderz@heaven";

  const char *temp;

  // Searching
  temp = strchr(testStr, '@');

  if(temp )

      cout << "Found";

  return 0;
}

C++ program to add two complex nos.

The program contains a class complex with two member variables x and y and a string class with one member variable. Two objects are created for complex class and string class and accepted values through read () function and their values are added using the operator overloaded function and assigned to the third object for each class. Values of the added object are displayed using the display () function. The + operator is overloaded here.

#include<iostream.h>
#include<string.h>
#include<conio.h>
class number
{
	private:
		int num1,num2;

	public:
		void input()
		{
			cout<<"nntEnter the real part:";
			cin>>num1;
			cout<<"ntEnter the imaginary part:";
			cin>>num2;
			cout<<"n";
		}
		number operator + (number x)      /*Operator overloading*/
		{
			number temp;
			temp.num1 = num1 + x.num1;
			temp.num2 = num2 + x.num2;
			return(temp);
		}

		void display()
		{
			cout<<"nntSum of two numbers is: "<<num1<<" + i "<<num2;

		}
};

Output

First Number
Enter the real part: 5
Enter the imaginary part: 4

Second Number
Enter the real part: 1
Enter the imaginary part: 2

Sum of 2 no is : 6 + i 6

C++ program append the two text files

Three file objects are created using the fstream class one for first, second for second file and third for the appended file. The first two files are opened in the input mode and third in the append mode. The first file is opened and checked for error condition if the file exist its contents are written to the third file else the program is aborted with a message on the screen. This process is repeated for the second file also .If the two files exist ,the first file contents are written first and second file contents are written to the third file by appending to its present contents.

#include<iostream.h>
            #include<conio.h>
#include<fstream.h>
#include<process.h>
void main()
{
		fstream file1, file2,file3;
		char ch;
		file1.open("file1.txt",ios :: out);
		file2.open("file2.txt",ios :: out);
		cout << "n Enter data in file 1 n";
		cin.get(ch);
		while(ch != 'n')
		{
			  file1.put(ch);
	 		 cin.get(ch);
		}
		cout << "n Enter data in file 2 n";
		cin.get(ch);
		while(ch != 'n')
		{
			  file2.put(ch);
			  cin.get(ch);
		}
		file1.close();	file2.close();

		file1.open("file1.txt",ios :: in);
		file2.open("file2.txt",ios :: in);
		file3.open("file3.txt",ios :: out | ios :: trunc | ios :: app);
		if(!file1)
		{
			 cout << "n First file not found ";
			 getch();
			 exit(0);
		}
		while(file1)
		{
			 file1.get(ch);
			 file3.put(ch);
		}
		if(!file2)
		{
			 cout << "n Second file not found ";
	 		getch();
			 exit(0);
		}
		while(file2)
		{
			 file2.get(ch);
			 file3.put(ch);
		}
		file1.close();
		file2.close();
		file3.close();
		cout << "nt Appended file contents n";
		file3.open("file3.txt",ios :: in);
		while(file3)
		{
			 file3.get(ch);
			 cout.put(ch);
		}
		getch();
}

Output :

Enter data in file 1
I am coder
Enter data in file 2
I am an student.
Appended file contents
I am coder. I am an student.

C++ program to copy the contents of a text file to another

Two file objects are created using the fstream class for the two files, one for source file and another destination file. The first file is opened and its contents are copied to the second file using get ( ) and put ( ) function. Each time the source file is opened error checking is done to ensure that the file is existing else the program is aborted with a message.

If the contents are successfully copied, the destination file contents are displayed on the screen.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<process.h>

void main()
{
		fstream file1, file2;
		char ch;
		clrscr();
		file1.open("file1.txt",ios :: out);
		cout << "nt Press 'enter key' to quit nn";
		cout << "n Enter the data n";
		cin.get(ch);
		while(ch != 'n')
		{
	   		 file1.put(ch);
	    		cin.get(ch);
		}
		file1.close();
		file1.open("file1.txt",ios :: in);
		if(!file1)
		{
			 cout<< "n File1 not found !! n";
			 getch();
			 exit(0);		// aborting…
		}
		cout << "n First file contents n";
		while(file1)
		{
			 file1.get(ch);
			 cout.put(ch);
		}
		file1.seekg(0);		      	    /* copying process..... */
		file2.open("file2.txt",ios :: out );
		cout << "nn First file contents copied to second file... n";
		while(file1)
		{
			 file1.get(ch);
			 file2.put(ch);
		}
		file1.seekg(0);
		file2.close();
		file2.open("file1.txt",ios :: in);
		if(!file1)
		{
			 cout<< "n File1 not found !! n";
			 getch();
			 exit(0); 		// aborting…
		}
		cout << "n Second file contents n";
		while(file2)
		{
			 file2.get(ch);
			 cout.put(ch);
		}
		file2.close();
		getch();
}

The output is like this

Press ‘enter key’ to quit
Enter the data
I am an Indian
First file contents
I am an Indian
First file contents copied to second file…
Second file contents
I am an Indian

Playing sound on the Mac Desktop in Objective C.

There are different ways for playing sound on the Mac in Objective C.

Let’s look at some of the methods..
1. Play by filename.

           NSSound *mySound = [NSSound soundNamed:@"sound"];

if you have no file named “sound” in your application’s main bundle, then it will return nil.

2. Play by pathName

           sound = [[NSSound alloc] initWithContentsOfFile:@"/Volumes/Audio/sound.aiff"
           byReference:YES];

3. Play by URL

        NSURL *soundURL = [NSURL
        fileURLWithString:@"file://~/soundfiles/sound.aiff"];
        NSSound *sound = [[NSSound alloc] initWithContentsOfURL:soundURL

byReference:NO];
Then to play the sound add

         if (![sound isPlaying])
                [sound play];

To pause the sound

               [sound pause];

To stop the sound.

              [sound stop];

To resume the sound

             [sound resume];

Please leave your valuable comments if this post was useful…..

Remove unwanted memory from iPhone….

Hi all ……
You know iPhone doesnot have garbage collection like ANDROID. So it becomes the responsibility of the developer or programmer to release the resources and remove the unwanted textures from your memory.
If you don’t remove the unused textures and other variables from your memory your application will exit after a while.

You often have the problem that your iPhone application exits unexpectedly, Most probably this may be the reason.

One method to check is…….
1. Release variables declared inside a function from there itself.
2. Release other variables inside the dealloc() function.
3. Remove the textures that remain in memory when you use images.
4. If you are using particle effects then don’t use the particle release function.
5. Unload the sounds on dealloc.

For removing the variables you can use..

[my_var release];

For removing the textures from the memory use this code inside the dellaoc function.
Check out the console if it is working. It will show console outputs such as “removing unused texture bla bla bla..”

/** this will remove all the unused frames if you are using sprite sheets **/
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
/** this will remove unused textures of images if you are using only images **/
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
/** this will remove all textures from memory **/
[[CCTextureCache sharedTextureCache] removeAllTextures];

But still your program may exit. This is due to the second line and put only the this line..

[[CCTextureCache sharedTextureCache] removeUnusedTextures];

This may solve your problem…….
This above code will release most of your unused memory.

Please leave your valuable comments if this post was useful…..

Difference between & and * operator in C

A beginner to Pointers in C often perplexed by different operators & and *
Let’s see what it really is and how simple it is.

& – This operator gives ‘the address of’ a variable
* – This operator gives ‘the value at address’ of a variable

(Note! Note! Note! Not the other way round! By heart it any way!)

Let’s codes speak…

#include
main()
{

	int myVariable = 25;

	printf("n Address of myVariable = %u", &myVariable);
	printf("n Value of myVariable = %u", myVariable);
	printf("n Value of myVariable = %u", *(&myVariable));
}

 

So… the output…

Guess?

Address of myVariable = 7589
//7589 is the address in memory of the variable myVariable

Value of myVariable = 25
//It simply printed the ‘myVariable’ which contains 25

Value of myVariable = 25
// Please do note that it printed ‘the value at address’ of ‘myVariable’
// Address is passed via &myVariable

:)

String Functions in C

Let’s now briefly discuss about four essential String function used in C.

We are going to discuss about
a) strlen()
b) strcpy()
c) strcat()
d) strcmp()

Codes speak louder than words! Let’s see what these functions do in a simple C Program.


#include
main()
{

	char stringOne[15] = "CoderzHeaven";
	char stringTwo[] ="Codes";
	char stringThree[15];

	int varOne, varTwo;

	//Counting the string length
	varOne = strlen(stringOne);
	printf("n Length of stringOne = %d", varOne);

	//Copying stringOne to stringThree
	strcpy(stringThree, stringOne);
	printf("n After Copying process, stringThree=%s", stringThree);

	//Comparing two strings
	varTwo=strcmp(stringThree, stringOne);
	printf("n On Comparing stringThree & stringOne, varTwo=%d", varTwo);

	//Comparing two strings
	varTwo = strcmp (stringOne, stringTwo);
	printf("n On Comparing stringOne & stringTwo, varTwo=%d", varTwo);

	//Concatenating two strings
	strcat(stringOne, stringTwo);
	printf("n After Concatenation, stringOne = %s", stringOne);

}

Output???
Here y
Length of stringOne = 12
After Copying process, stringThree = CoderzHeaven;
On Comparing stringThree & stringOne, varTwo = 0
On Comparing stringOne & stringTwo, varTwo= -1
After Concatenation, stringOne = CoderzHeavenCodes