Pages

Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Wednesday, February 18, 2015

C program to find sum of series 1 x x 2 x n

C++ program to find sum of series 1+x+x^2+......+x^n


#include<iostream.h>
#include<conio.h>
#include<math.h>


void main()
{
clrscr(); //to clear the screen
long i,n,x,sum=1;

cout<<"1+x+x^2+......+x^n";
cout<<"

Enter the value of x and n:";

cin>>x>>n;


for(i=1;i<=n;++i)
sum+=pow(x,i);
cout<<"
Sum="<<sum;

getch(); //to stop the screen
}

Read more »

Tuesday, February 17, 2015

C program to find sum of series 1 x x 2 x n

C program to find sum of series 1+x+x^2+......+x^n

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
 int i,n;
float x,sum=0;
clrscr(); //to clear the screen
printf("1+x+x^2+......+x^n");
printf("

Enter the value of x and n:");

scanf("%f%d",&x,&n);

for(i=1;i<=n;++i)
sum+=pow(x,i);
 sum++;
printf("
Sum=%f",sum);

getch(); //to stop the screen
}
Read more »

What is Exception Handling in C


What is Exception Handling in C++? (try and catch block)

While doing programming we come many across errors. Most commonly there are two types of errors, logical errors and syntactical errors. The logical errors occur due to the poor understanding of problem and on the other hand syntactical errors arise due to poor understanding of language.



Many times we face some strange or odd problems other than these two types of errors, these are known as exceptions. Exceptions are the run time unusual conditions that a program may encounter while execution. It might include conditions such as division by zero, out-of-range index, running out of memory, etc.

Also Read: What is Virtual Base Class in C++?
Also Read: C++ Templates: Program to Swap Two Numbers Using Function Template



So we can say that the process of handling these types of exceptional conditions is known as exception handling. This is a new feature added to ANSI C++. Today, almost all compilers support this feature.



The exception handling process includes the following four steps:

1. Find the problem (Hit the exception)

2. Inform that an error has occurred (Throw the exception)

3. Receive the error information (Catch the exception)

4. Take corrective actions (Handle the exception)


Exception Handling Mechanism


C++ exception handling mechanism consists of three keywords, try, throw and catch.


try: The keyword try is used to define a block of statements which may produce exceptions and this block is known as try block.

throw: When an exception is detected, it is thrown using a throw statement in the try block.

catch: This block catches the exception thrown by throw statement in the try block and handles it appropriately. The catch block that catches an exception must immediately come after the try block that throws the exception.



The structure of these two blocks is shown below:



. . . . . .

. . . . . .

try

{

                . . . . . .

                throw exception                  //Block of statements which detects and throws an exception

                . . . . . .

                . . . . . .

}

catch(type arg)

{

                . . . . . .                             //Block of statements that handles the exception

                . . . . . .

}

. . . . . .

. . . . . .


When the try block throws an exception, the program control leaves the try block and enters the catch statement of the catch block. Here exception is nothing but an object used to transmit the information about a problem. If the type of object thrown matches the arg type of the catch statement then catch block is executed for handling the exception. If they do not match, the program is aborted with the help of abort() function which is invoked by default. When no exception is detected and thrown, the control goes to the statement immediately after the catch block or we can say catch block is skipped.


Also Read: Java Program to Make a Simple Calculator Using AWT
Also Read: Menu Driven C Program to Perform Insert, Display and Delete Operations on a Singly Linked List (SLL)


A program is given below that will explain you that how actually exception handling is done in C++.


#include<iostream>



using namespace std;



int main()

{

    int x,y,z;

    cout<<"Enter the values of x and y:";

    cin>>x>>y;

    z=x-y;



    try

    {

        if(z!=0)

        {

            cout<<"Result(x/z)="<<x/z;

        }

        else                                             //division by zero exception

        {

            throw(z);                                 //throws int object

        }

    }

    catch(int)                                        //catches the exception

    {

        cout<<"Exception caught: z="<<z;

    }



    return 0;

}


Outputs of the above program is shown below:

For First Run 
 

What is Exception Handling in C++?

For Second Run

What is Exception Handling in C++?

If you have any doubts then feel free to ask by commenting below. Please do share if you liked the article.



Source: E Balagurusamy
Read more »

Monday, February 16, 2015

C Program to print three numbers in descending order

#include<iostream.h>
#include<conio.h>


void main()
{
clrscr();
int a,b,c,big1,big2,big3;
cout<<"Enter three numbers:";
cin>>a>>b>>c;


 big1=a;
if(b>big1)
big1=b;
else
if(c>big1)
big1=c;


if(big1==a)
{
if(b>c)
{
big2=b;
big3=c;
}
else
{
big2=c;
big3=b;
}
}


else
{
if(big1==b)
if(a>c)
{
big2=a;
big3=c;
}
else
{
big2=c;
big3=a;
}


else
{
if(a>b)
{
big2=a;
big3=b;
}
else
{
big2=b;
big3=a;
}
}
}
cout<<"

Numbers in descending order......
";

cout<<big1<<" "<<big2<<" "<<big3;
getch();
}
Read more »

Sunday, February 15, 2015

C else if Clause

Till now we have learnt about the if statement, if-else statement, if-else nested statements and logical operators. Logical operators are good alternatives of nested if-else statements. But there are still some cases when we have to use nested if-else clause. So to make those situations a bit easy, Dennis Ritchie introduced else if clause.


What are else if clause?

Well they are no major difference between nested if-else and else if clause. As I told you earlier, the main problem with nesting is that it makes the program difficult to read. So to avoid that issue, else if clause is introduced.

General Syntax of else if clause is given below.

if (condition)
{
Statement 1
Statement 2 and so on
}

else if (condition)
{
Statement 1
Statement 2 and so on
}

else if (condition)
{
Statement 1
Statement 2 and so on
}

else
{
Statement 1
Statememt 2 and so on
}


Things to remember while using else if clause

  • You can use any number of else if clause in this ladder.
  • Usage of else in the last is completely optional. It means its up to you that you either want to include it or not in your program.
  • This does not destroy the readability of the program.
  • By using else-if clause, our program does not creep to the right due to indentation.

Remember by using else if clause, no change will occur in the execution of program. It is just the re-write of nested if-else clause. You can understand this point by watching below example.


C else if Clause

Lets try to understand this clause with one program.

Question: Make one program to check the eligibility of student to take admission in a college. The student must fulfil at least one condition to take admission in the college.
  • Student should be male. His marks should be more than 80% in 12th and his age should be at least 18 years.
  • Student should be female. Her marks should be more than 75% in 12th and her age should be at least 17 years.
  • Student should be played at any national level game. Age and qualification doesn’t matter in this case.


#include <stdio.h>

void main ()
{
int per, age;
char gen, game;

printf("Press M for male
F for female
Y for Yes in game
N for No in game
");
printf("Enter gender, age and percentage in class 12th
");
scanf("%c %d %d",&gen, &age, &per);
printf("Did you play in any game at national level
");
scanf("%c",&game);

if ((age>=18 && per>=80 && gen==M) || (age>=17 && per>=75 && gen==F))
prinf("You can take admission in our college.");
else if (game==Y)
printf("You can take admission based on sports Kota");
else
printf("You cannot take admission in our college.");
}

Output

Output

Explanation

  • In the beginning we gave some instructions to user that how he/she should enter the data in our program.
  • After that we printed the message and take some details from the student.
  • Now basically we have 2 conditions. At first we have to check the student if he/she eligible for general kota and in the last we have to check if he/she is eligible for sports kota.
  • To make things a bit clear I checked the results for general kota by using if keyword. I combined the conditions by using logical operators to make the program a bit compact.
  • After that by using else if clause I have checked if the student is eligible for sports kota.
  • If nothing works then I have also given the default else block to print the message “You cannot take admission in our college.”
Read more »

Friday, February 13, 2015

C program to check whether a given number is even or odd


C program to check whether a given number is even or odd

#include<stdio.h>
#include<conio.h>

void main()
{
int n;
clrscr();
printf("Enter any number:");
scanf("%d",&n);

if(n%2==0)
printf("The number is even");
else
printf("The number is odd");

getch();
}
Read more »

Preprocessor Directives in C Part 1

A program goes from several stages before getting executed. The program we write is converted into source code by using text editor which is stored with extension .C. After that it is converted to expanded source code by using preprocessor which is stored with extension .I. Now this expanded source code is converted to object code by using compiler which is stored with extension .OBJ. After that it is converted into executable code by using Linker and stored with extension .EXE.

Preprocessor Directives in C - Part 1

Preprocessor Directives in C

Preprocessor directive is a text substitution tool that instruct the compiler to pre-processor our program before its actual compilation. Each C preprocessor starts with # symbol. Generally they are defined at the beginning of the program just after the header files. But you can define them anywhere in the program.


Types of Preprocessor Directives in C

There are four types of preprocessor directives which are given below.

1. Macros
2. File inclusion
3. Conditional compilation
4. Miscellaneous directives


Macros

Macros are generally used to give a common name to the values which are used many times in a program. Or we can say that, macros are used to define symbolic constants. Consider below program to understand it.


//C program to calculate area of circle

#include <stdio.h>

#define PI 3.14 //macro

int main()
{
float r, a;
printf("Enter radius of the circle
");
scanf("%f",&r);
a=PI*r*r;
printf("Area of the circle is %f",a);

return 0;
}

Output

Macros

Points to remember
  • A macros always start with #define. In our program #define PI 3.14 is the macros definition. Wherever PI is encountered in the program it is replaced with 3.14. 
  • In the compilation of the program all the macros definition replaced with the values which are used with #define. It is done in the process when source code is converted into expanded source code.
  • Do not add semicolon at the end.
  • Generally macros are written in single line. If you want to write it in multiple lines then you have to use macro continuation operator i.e. . An example for this is given below.

Examples

#define OR ||
#define CHECK (a>10 && a<20)
#define MSG
printf("It is working fine")


Macros with arguments

Macros with arguments are similar to functions with arguments. Consider the below program to understand its working.

//C program to calculate perimeter of circle

#include<stdio.h>

#define PERI(x) (2*3.14*x) //macro with argument

int main()
{
float r,per;
printf("Enter radius of the circle
");
scanf("%f",&r);
per=PERI(r);
printf("Perimeter of the circle is %f",per);

return 0;
}

Output

Macros with arguments

Points to remember
  • In the above program I have used macros with argument with the statement #define PERI(x) (2*3.14*x)
  • Be careful while defining macros with arguments. In above example there must be no space between PERI and (x). The body of the macro should be placed in parentheses.
  • Whenever the macro calling is done in our program, its calling statement in replaced by its body.
  • They are fast as compared to functions because control do not goes to macro definition, the whole body comes at the place where calling is done.

File Inclusion

As its name suggests this preprocessor directive is used to include all the content of file to be included in the source code. Till now we have used preprocessor directives like #include<stdio.h> which includes all the contents from the header file stdio.h. These are predefined header files, you can also make your own and then include it in your program.

Examples

#include<math.h>
#include<stdlib.h>


Why it is used?
Its certainly a good question. It is not a good programming practice to write full program into a single file. While writing a very complex program it is recommend to break the program into files and include them in the beginning. Sometimes the macros of the program is also quite large which can only be stored in some files. So it is basically used for better management of the C program.
Read more »