Friday, October 21, 2011

Solution to Challenge # 2

So the time for challenge # 2 is over and here is the solution:

Problem Statement: A program that inputs an integer and displays the second last digit present in it.


Sample Input:
1) 341534
2) 95402367
3) 59

Sample Output:

1) 3
2) 6
3) 5





Solution:


#include <iostream>
using namespace::std;
int main(void)
{
        int num;
        int last_digit;
        cout << "Enter an integer: ";
        cin>>num;
        last_digit = num/10%10;
        cout << "Last digit of the entered integer is: "<<last_digit<<endl;
        return 0;
}



This solution is submitted by Tom and is absolutely correct. Congrats Tom! :) I hope you are having fun with C++ and I look forward to your future participation as well.



Wednesday, October 12, 2011

Solution to Challenge # 1

Problem Statement: A program that inputs an integer and displays the last digit present in it.


Sample Input:
1) 341534
2) 95402367
3) 59
Sample Output:
1) 4
2) 7
3) 9

 

Solution:

#include<iostream>

using namespace::std;

int main(void)

{

int num;

int last_digit;

cout<<”Enter an integer: ”;

cin>>num;

last_digit = num%10;

cout<<”Last digit of the entered integer is: ”<<last_digit<<endl;

return 0;

}

It was as simple as that. Best of luck for the next challenge. Smile

Tuesday, September 13, 2011

The Challenge

Hi! Here are all the details about challenge going on.

  • You should be a beginner of C++ (this blog is not for professionals)
  • Cutoff time for the submission of code will be displayed with the problem statement.
  • All the submitted solutions will be revealed after the challenge is over.
  • It is highly recommended you do not ask for help on other forums and try to solve the problem yourself (believe me that's for your own benefit).
  • You would be able to see a voting widget to vote for the code you think is best (properly commented, compact, not unnecessarily lengthy or difficult to understand), after submissions are ended.
  • Votes do help in increasing your winning chances but all the codes will be checked by a professional to ensure no one is trying to cheat.
  • Results will be displayed after two days of submissions.
  • The winner will get a chance to display his profile/blog/website on the sidebar till the winner for next challenge is announced.
  • After one challenge is over there will be a post having the problem statement , the best solution and the link to the winner's profile/website/blog.
  • No one is eligible to win consecutively. However if your code is good enough your name will be displayed in the post published afterwards.
  • The administrator's decisions will be final.


Monday, September 12, 2011

How to write to a .txt file

In the last post I told you how to read input from a .txt file. Lets see how can we save output in a .txt without displaying it on the screen.

Step 1: Include the header file ‘fstream’ which is used for declaring the input/output stream variables.

Step 2: Declare the output variable say ‘out’ using ofstream as ‘ofstream out;’. (We use ofstream for output variables and ifstream for input variables.)

Step 3: Open the file you want to read the input from using the command ‘out.open(“yourfilename.txt”);’.

Step 4: Now where you want to output something to the file just use 'out' in place of 'cout'.

Step 5: Close the file at the end of your program with ‘out.close();’.


Example Source Code:
#include<iostream>
#include<fstream>
using namespace:std;
int main (void)
{
int x;
x=1;
ofstream out;
out.open(“MyFile.txt”);
out<<x;
cout<<”Value of x has been written in your file. "<<endl;
out.close();
return 0;
}


REMEMBER:
         Always keep your .txt file in the same directory as your .cpp file or otherwise you would have to give complete address of the file while opening it.


Saturday, September 10, 2011

How to read input from a .txt File

Reading input from the standard input device i.e keyboard is what we have done so far. We use input stream variable ‘cin’ for this purpose and user can enter his desired character or integer as an input to our program. What if we want to read the input from a text file? Lets see what we can do for this:

Step 1: Include the header file ‘fstream’ which is used fo declaring the input/output stream variables.

Step 2: Declare the input variable say ‘in’ using ifstream. It would be like ‘ifstream in;’. (We use ifstream for input variables and ofstream for output variables.)

Step 3: Open the file you want to read the input from using the command ‘in.open(“yourfilename.txt”);’.

Step 4: Now where ever in your program you want to read input from the file, you would use ‘in’ in place of ‘cin’.

Step 5: Close the file at the end of your program with statement ‘in.close();’.


Example Source Code:
#include<iostream>
#include<fstream>
using namespace:std;
int main (void)
{
int x;
ifstream in;
in.open(“MyFile.txt”);
in>>x;
cout<<”The first integer in your file is ”<<x<<endl;
in.close();
return 0;
}


REMEMBER:
1. Always keep your .txt file in the same directory as your .cpp file or otherwise you would have to give complete address of the file while opening it.
2. Always have something written in your file otherwise it will give you garbage as input.


Monday, September 5, 2011

How to Set Precision

There are quite some problems in which the output is required to be in decimal format. Making 1.00 from 1 could be done by a lot of other ways but none is as good and short as using setprecision(); Just include “iomanip” in your code and you are ready to use this manipulator.

Example Source Code:
#include<iostream>
#include<iomanip>
using namespace::std;
int main(void)
{
double number;
cout<<”Enter the integer: ”;
cin>>number;
cout<<showpoint<<fixed;
cout<<setprecision(2);
cout<<”You entered: ”<<number;
return 0;
}

Here:


Setprecision(int n) is used to set the required precision which you pass as an argument to the manipulator; See that it is 2 in the above program, you can change it. However this manipulator will only work for the upcoming cout statement. For setting the precision of next value, you again need to use this manipulator or you can use ‘fixed’ for convenience.

fixed(Optional) is used to fix the precision i.e throughout your program the precision will remain the same once you set it with setprecision.

Showpoint(Optional) forces the program to show the decimal point and the decimal part of the number whose decimal part is 0. e.g 1 may not show up as 1.00 if you do not instruct the computer to show the point by using this manipulator.

Friday, September 2, 2011

Sum of Natural Numbers up to 'n'

Adding consecutive natural numbers up to a number specified by user at run time is as easy as adding numbers to a known number. Here is the code to show you how its done:

Problem: Find sum of numbers up to 'n'. Where 'n' is entered by the user.


Algorithm:
1. Prompt for the number (say n).
2. Write a for loop in which set first condition to 0 and second to n.
3. Add n to another variable (say j) which was initially set to 0.
4. Print the sum(which is j) when out of for loop.

Source Code:
#include<iostream>
#include<conio.h>
using namespace::std;
int main (void)
{
int n;
int j;
j=0;
cout<<"Enter the number: ";
cin>>n;
for(int i=1; i<=n; i++)
j=j+i;
cout<<"Sum of natural numbers from 0 to "<<n<<" is: "<<j<<endl;
getch();
return 0;
}

You can modify the program according to your need; product of natural numbers, sum of squares of natural numbers etc.


Right Align Your Output

Wondering how to change the alignment of the output?  Here is a little tip:
cout<<right is used for right alignment of your output. Similarly you can align it back to left with cout<<left. Don't forget to add the directive 'iomanip' in your code. See the sample below:

#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace::std;
int main ()
{
          cout<<"How to right align your output \n"<<endl;
          cout<<right<<setfill(' ')<<setw(30);
          cout<<"123"<<endl;
          getch();
          return 0;
}

Here:
  • right is used to right align the output.
  • setw(30) is used to tell the computer how far you want to go from left. Here I have set it to 30 so 123 will be displayed 30 spaces away from left side.
  • setfill(' ') is used to to fill in the blank(between the left side of screen and the output) with any character you like. I have used a space here you can experiment with anything to see what it looks like.
Have a look at the screenshot of output you will get from above program. 




Tuesday, August 30, 2011

Separate Integer from a Decimal Number

Problem: Separate the integer part from a decimal number.


Algorithm:
1. Prompt for a number.
2. Assign the number to a variable with ‘int’ data type.
3. There you go ;)

Source Code:
#include<iostream>
#include<conio.h>
using namespace::std;
int main (void)
{
    double num;
    int integer;
    cout<<"Enter a decimal number: ";
    cin>>num;
    integer=num;        //an int can only save the integer part
    cout<<"Integer part of "<<num<<" is "<<integer;
    getch();
    return 0;
}


This is a little trick I use to separate integers. Do tell me if you have any other ideas.

Monday, August 29, 2011

Greater Number

Problem: Find which number is greater.


Algorithm:
1. Prompt for two numbers.
2. Make a decision of which number is greater.
3. Print the appropriate message.

Source Code:
#include<iostream>
#include<conio.h>
using namespace::std;
int main (void)
{
    int x,y;
    cout<<"Enter two numbers: ";
    cin>>x>>y;
    if
    (x>y)            //if x is greater
    cout<<x<<" is greater than "<<y<<endl;
    else if
    (x<y)            //if y is greater
    cout<<y<<" is greater than "<<x<<endl;
    else if (x==y)    //if both are equal
    cout<<"The numbers you entered are equal "<<endl;
    getch();
    return 0;
}

Thursday, August 18, 2011

Positive or Negative

Problem: Check whether the entered integer is negative, positive or zero.


Algorithm:
1. Prompt for the number.
2. Decide whether it is zero, greater than zero or less than zero.
3. Display the result.

Source Code:
#include<iostream>
#include<conio.h>
using namespace::std;
int main(void)
{
int num;
cout<<"Enter the number: ";
cin>>num;
//Deciding whether number is positive, negative or zero
if(num<0)
cout<<"Given number is negative"<<endl;
else if(num==0)
cout<<"Given number is zero"<<endl;
else if(num>0)
cout<<"Given number is positive"<<endl;
getch();
return 0;
}

Simple enough! There is only a decision to make in this program...


Tuesday, August 16, 2011

Average of three numbers

Problem: Find average of three numbers.


Algorithm:
1. Prompt for three numbers.
2. Calculate average by the formula.
3. Display the result.

Source Code:
#include<iostream>
#include<conio.h>
using namespace::std;
int main (void)
{
int num1;           //first number
int num2;          //second number
int num3;          //third number
int average;      //average
cout<<"Enter the first number ";
cin>>num1;
cout<<"Enter the second number ";
cin>>num2;
cout<<"Enter the third number ";
cin>>num3;
average=(num1+num2+num3)/3;         //formula for finding average
cout<<endl<<"Average of given three numbers is ";
cout<<average<<endl;
getch();
return 0;
}

Monday, August 15, 2011

Fahrenheit to Celsius

Problem: Convert given temperature from Fahrenheit to Celsius.


Algorithm:
1. Prompt for temperature in Fahrenheit.
2. Use appropriate formula to calculate its equivalent in Celsius.
3. Display the result.

Source Code:
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace::std;
int main(void)
{
double F;                    //for Fahrenheit
        double C;                   //for Celsius
cout<<"Enter temperature: ";
cin>>F;
C= 0.56 * ( F-32 );                 //formula for conversion
cout<<showpoint<<fixed;
cout<<setprecision(1);        //setting precision up to 1 decimal place
cout<<F<<"°F is equal to "<<C<<"°C"<<endl;
getch();                             //precaution for blinking screen
return 0;
}

Sunday, August 14, 2011

Round Off

Problem:   Round off a given decimal number to two decimal places.


Algorithm:
1. Input the decimal number.
2. Separate its integer part.
3. Subtract the integer part from the given number to get the fraction.
4. Multiply the fraction by 1000 (we need first 3 digits after the decimal point)
5. Find the third digit of this number by taking mode with 10.
6. If this digit is greater than or equal to 5, add 0.01 to the original decimal number else leave it as it is.
7. Set the precision to show two digits after the decimal point and display the result.

Source Code:
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace::std;
int main(void)
{
int integer;
int num;
double decimal;
double fraction;
cout<<"Enter the decimal number: ";
cin>>decimal; //Input the decimal number
integer=decimal; //Separating the integer part
fraction=decimal-integer;  //Separating the fraction part
num=(fraction*1000); // % operator in next step works only with integers
num=num%10; //Finding the 3rd digit after decimal point
cout<<fixed<<showpoint;
if(fraction>=5)
{
cout<<"Given decimal number rounded to two decimal places is: ";
cout<<setprecision(2)<<decimal+0.01<<endl;
}
else
{
cout<<"Given decimal number rounded to two decimal places is: ";
cout<<setprecision(2)<<decimal<<endl;
}
getch();
return 0;
}


This program is working fine with any kind of input. Let me know if you think something is wrong...



Saturday, August 13, 2011

Getting Started

Welcome Everyone!
I am planning to post C++ code snippets on this blog. I hope these snippets will be helpful for beginners (I'm not a pro myself). So, if you are stuck with a particular problem, you can always contact me and we will solve it together. I will love to help you out...
Enjoy programming, Its fun!

P.S: The snippets I post here are not copyright protected, you can use them anywhere you like!