tag:blogger.com,1999:blog-86121088709283576102024-03-19T12:54:30.820+05:30Learn C Programming from Scratch: Easy-to-Follow Tutorial for BeginnersLearn C programming from scratch with our comprehensive tutorial series. Master the fundamentals, explore advanced concepts, and unleash your coding potential. Build a strong programming foundation with our easy-to-follow C programming tutorial. From data types to functions, arrays to pointers, we've got you covered. Unknownnoreply@blogger.comBlogger124125tag:blogger.com,1999:blog-8612108870928357610.post-2556743560999101232015-07-25T22:05:00.000+05:302015-07-26T02:43:26.064+05:30Program to Check Whether the Person is in Teen Age or Not in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to check whether the person is in teen age or not with output and proper explanation. Here we find out whether a person is a teenager or not by using an if-else condition and C logical operators.</div>
<br />
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int age ;
clrscr() ;
printf("Enter the age : ") ;
scanf("%d", &age) ;
if(age >= 13 && age <= 19)
printf("\nThe person is in teen age.") ;
else
printf("\nThe person is not in teen age.") ;
getch() ;
}
</pre>
<b>Output of above program is</b><br />
<br />
Enter the age : 18<br />
The person is in teen age.<br />
<br />
<div style="text-align: justify;">
<b><br /></b></div>
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here first user enters a number specifying an age. Then in the If part of If-else condition we check whether the previously entered age is between the range of 13-19 i.e. the teen age. If the age that user entered is indeed between 13 and 19 then the If block gets executed otherwise the else part will be executed.</div>
<div style="text-align: justify;">
<br /></div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<b>Note: </b>In the If condition here, if you notice you'll see that we are using logical AND (&&) operator for the conjunction of two conditions i.e. age >= 13 and age <= 19. That means the if part will only gets executed when both the conditions are true.</div>
</blockquote>
</div>
Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-8612108870928357610.post-37666516817709448762015-07-21T13:24:00.000+05:302015-07-26T02:48:25.066+05:30Biggest of 3 Numbers Using Ternary Operator in C<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here is a program to find biggest of 3 numbers using <a href="http://cprogramming.language-tutorial.com/2012/01/ternary-operator-in-c.html">ternary operator</a> with output and explanation in C programming language.</div>
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int a, b, c, big ;
clrscr() ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
getch() ;
}
</pre>
<br />
<br />
<span style="font-size: large;"><b>Output of above program</b></span><br />
<br />
Enter three numbers : 20 30 10 <br />
<br />
The biggest number is : 30 <br />
<b><span style="font-size: large;"><br /></span></b>
<div style="text-align: justify;">
<b><span style="font-size: large;">Explanation of above program</span></b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Note: </b>If you don't know about ternary operator first read it here. <a href="http://cprogramming.language-tutorial.com/2012/01/ternary-operator-in-c.html">Ternary Operator in C</a>.</blockquote>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
To understand this program lets convert this ternary operator into its equivalent if else.</div>
<div style="text-align: justify;">
</div>
<div style="text-align: center;">
<b> big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ; </b>
<br />
<div style="text-align: justify;">
<div style="text-align: left;">
<b> If else equivalent of above ternary expression </b><br />
<b> </b>
<br />
<pre class="cpp" name="code">if(a > b){
if(a > c){
big = a;
}else{
big = c;
}
}
else{
if(b > c){
big = b;
}else{
big = c;
}
}
</pre>
<br />
Now once ternary operator's expression is converted into simple if else it is easy to understand the program. So I let you to it.</div>
</div>
</div>
</div>
Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-8612108870928357610.post-10396374158338633942015-07-19T16:11:00.000+05:302015-07-26T02:44:07.586+05:30Find Sum of +VE & -VE Elements in an Array in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to find sum of positive and negative elements of an array in C using for loops and IF-Else condition.</div>
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int a[20], i, n, psum = 0, nsum = 0 ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nEnter the elements :\n\n") ;
for(i = 0 ; i < n ; i++)
scanf("%d", &a[i]) ;
for(i = 0 ; i < n ; i++)
{
if(a[i] > 0)
psum = psum + a[i] ;
if(a[i] < 0)
nsum = nsum + a[i] ;
}
printf("\nSum of positive elements is : %d", psum) ;
printf("\n\nSum of negative elements is : %d", nsum) ;
getch() ;
}
</pre>
<br />
<b>Output of above program is </b><br />
<br />
Enter the limit : 5 <br />
<br />
Enter the elements : <br />
<br />
-10 30 50 -20 40 <br />
<br />
Sum of positive elements is : 120 <br />
<br />
Sum of negative elements is : -30 <br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here we have some variables. So let's first take a look at each variable -</div>
<ul style="text-align: justify;">
<li>i - is the loop variable.</li>
<li>n - is the limit or number of elements that user wants to enter in the array.</li>
<li>a[20] - is an integer array of size 20. That means this array a[20] can have at most 20 integer values at any time.</li>
<li>psum - is used to store the sum of positive values of the array. It is initialized to zero at the start of the program.</li>
<li>nsum - is used to store the sum of negative values of the array. It is initialized to zero at the start of the program.</li>
</ul>
<div style="text-align: justify;">
First we ask the user to enter a limit or the number of elements he wants in the array. After that we use a for loop to enter the numbers in the array.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
To calculate the sum we have another for loop which loops for the value of i = 0 to n - 1. Inside this for loop we have two IF conditions which check that the value stored in array at a particular position is positive or negative. If the value in the array is positive or greater than zero then the first IF is executed and that value is added to the sum of positive numbers i.e. psum. And If the value in the array is negative or less than zero then the second IF is executed and that value is added to the sum of negative numbers i.e. nsum. </div>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8612108870928357610.post-58006917039661497982015-07-18T21:52:00.000+05:302015-07-26T02:44:57.891+05:30Program to Change an Integer to Words in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to change an integer to words with output and proper explanation. This program makes use of C concepts like <a href="http://cprogramming.language-tutorial.com/search/label/For%20Loops">For loop</a>, <a href="http://cprogramming.language-tutorial.com/search/label/While%20Loop">While loop</a>, <a href="http://cprogramming.language-tutorial.com/search/label/Arrays%20in%20C">Arrays</a>, <a href="http://cprogramming.language-tutorial.com/search/label/Switch%20Case">Switch Case</a>, <a href="http://cprogramming.language-tutorial.com/search/label/Break">Break </a>and <a href="http://cprogramming.language-tutorial.com/search/label/Modulus%20in%20C">Modulus</a>.</div>
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
long n, a[10], i, c = 0 ;
clrscr() ;
printf("Enter a number : ") ;
scanf("%ld", &n) ;
while(n > 0)
{
a[c] = n % 10 ;
n = n / 10 ;
c++ ;
}
printf("\n") ;
for(i = c - 1 ; i >= 0 ; i--)
{
switch(a[i])
{
case 0 :
printf("ZERO ") ;
break ;
case 1 :
printf("ONE ") ;
break ;
case 2 :
printf("TWO ") ;
break ;
case 3 :
printf("THREE ") ;
break ;
case 4 :
printf("FOUR ") ;
break ;
case 5 :
printf("FIVE ") ;
break ;
case 6 :
printf("SIX ") ;
break ;
case 7 :
printf("SEVEN ") ;
break ;
case 8 :
printf("EIGHT ") ;
break ;
case 9 :
printf("NINE ") ;
break ;
}
}
getch() ;
}
</pre>
<br />
<br />
<b>Output of above program is </b><br />
<br />
Enter a number : 123<br />
ONE TWO THREE<br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
First take a look at all the variables. All variables are of Long Data Type- </div>
<ul style="text-align: justify;">
<li>n - is the number that user enters.</li>
<li>a[10] - is an array of size 10 and is used to store each digit of the above number n at separate indexes.</li>
<li>i - is the loop variable.</li>
<li>c - is a counter variable which is initialized to zero at the start of the program.</li>
</ul>
<div style="text-align: justify;">
First we ask the user to enter a number (n can contain up to 10 digits for now) and stores it in variable n. Then using while loop, we're storing each digit of number n inside the array a[10]. Remember each digit is stored at a separate index. After the while loop the array a[10] will contain every digit of n but in reverse order e.g. if n = 123 then a[0] = 3, a[1] = 2 and a[2] = 1. (<a href="http://cprogramming.language-tutorial.com/2012/01/program-for-reversing-integer-in-c-c.html">How to Reverse an Integer. Read it here.</a>)</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
After this we're converting each digit to words with the help of for loop and switch case. Remember that the array contains the values in reverse order so we're also executing our for loop in reverse direction too.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Let's understand this program with an example. Suppose n = 123 then the steps involved are - </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Working of While Loop - </b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>n > 0 or 123 > 0. So while loop executes with c = 0 -</b></div>
<ul style="text-align: justify;">
<li>a[c] = n % 10 or a[0] = 123 % 10 = 3.</li>
<li>n = n / 10 = 123 / 10 = 12.</li>
<li>c++ or c = 1.</li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>n > 0 or 12 > 0. So while loop executes with c = 1 and a[0] = 3 -</b></div>
<div style="text-align: justify;">
</div>
<ul style="text-align: justify;">
<li>a[c] = n % 10 or a[1] = 12 % 10 = 2.</li>
<li>n = n / 10 = 12 / 10 = 1.</li>
<li>c++ or c = 2.</li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>n > 0 or 1 > 0. So while loop executes with c = 2, a[0] = 3 and a[1] = 2 -</b></div>
<div style="text-align: justify;">
</div>
<ul style="text-align: justify;">
<li>a[c] = n % 10 or a[2] = 1 % 10 = 1.</li>
<li>n = n / 10 = 1 / 10 = 0.</li>
<li>c++ or c = 3.</li>
</ul>
<div style="text-align: justify;">
Now n is not greater than zero so while loop terminates. Now c = 3, a[0] = 3, a[1] = 2 and a[2] = 1.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
After while loop, for loop is executed. Our for loops runs for i = c - 1 to 0, decrementing value of i each time. Inside for loop we have a switch case condition in which we're passing the value of array a[10]. Take a look at the working of for loop.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Working of For loop -</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>i = c - 1 = 3 - 1 = 2 -</b><b> </b></div>
<ul style="text-align: left;">
<li>We're passing a[i] in switch statement i.e. a[2] = 1 (first digit of our number).</li>
<li>When 1 is passed as a value in switch statement the case marked with value 1 i.e. CASE 1 is executed, printing the text "ONE ".</li>
<li>Next using break statement we're exiting the switch case and for loop is executed again with updated values.</li>
</ul>
<br />
<div style="text-align: justify;">
<b>i = 1 -</b><b> </b></div>
<ul style="text-align: left;">
<li>We're passing a[i] in switch statement i.e. a[1] = 2 (second digit of our number).</li>
<li>When 2 is passed as a value in switch statement the case marked with value 2 i.e. CASE 2 is executed, printing the text "TWO ".</li>
<li>Next using break statement we're exiting the switch case and for loop is executed again with updated values.</li>
</ul>
<br />
<div style="text-align: justify;">
<b>i = 0 -</b><b> </b></div>
<ul style="text-align: left;">
<li>We're passing a[i] in switch statement i.e. a[0] = 3 (third digit of our number).</li>
<li>When 3 is passed as a value in switch statement the case marked with value 3 i.e. CASE 3 is executed, printing the text "THREE ".</li>
<li>Next using break statement we're exiting the switch case and for loop is executed again with updated values.</li>
</ul>
<br />
<b>i = -1 so for loop is terminated.</b><br />
<br />
<blockquote class="tr_bq">
<div style="text-align: justify;">
<b>Tip: </b>To understand the program more perfectly you can also take different values
of n and try the above process yourself. It will help you to understand
the process much clearly and helps in improving your debugging
ability. <b> </b></div>
</blockquote>
<br />
<ul style="text-align: left;">
</ul>
<div style="text-align: justify;">
</div>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8612108870928357610.post-49770599153378657972015-07-09T13:44:00.000+05:302015-07-26T02:53:06.843+05:30Program to Find the Average of First n Natural Numbers<div dir="ltr" style="text-align: left;" trbidi="on">
Here is a program to find the average of first n natural numbers using for loop with output and explanation.<br />
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int n, i ;
float sum = 0, avg ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
for(i = 1 ; i <= n ; i++)
sum = sum + i ;
avg = sum / n ;
printf("\nAverage of first %d numbers is : %.2f", n, avg) ;
getch() ;
}
</pre>
<br />
<span style="font-size: large;"><b>Output of above program</b></span> <br />
<br />
Enter the limit : 5 <br />
<br />
Average of first 5 numbers is : 3.00<br />
<br />
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<span style="font-size: large;"><b>Explanation of above program</b></span></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
In this program to calculate average of first n natural numbers, we have two integers (n, i) and two floating point (sum, avg) variables. First we initialize the variable sum to zero and then ask user to enter a limit. Now inside the for loop which runs from 1 to n, we're calculating the sum first by simply adding the loop variable ( i )with our variable ( sum ) as we're working on first n numbers. Then outside the loop we are calculating the average by dividing the total sum by n and then we're displaying the average.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Remember:</b> If you notice carefully, we haven't placed any curly brackets ( {} ) in our for loop as our for loop contains only one statement. And in C you can omit curly brackets from any loop including for, while, do-while as well as from conditional statements (if else), if and only if there is only one statement inside that particular block just like we have here in our for loop.</blockquote>
</div>
</div>
Unknownnoreply@blogger.com4tag:blogger.com,1999:blog-8612108870928357610.post-4939311535157378782015-07-04T12:19:00.000+05:302015-07-26T02:52:10.893+05:30Program for Printing Addition Table of the Given Number in C<div dir="ltr" style="text-align: left;" trbidi="on">
Here's a program for printing addition table of the given number using for loop in C programming language.<br />
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int i, t, n ;
clrscr() ;
printf("Enter the table : ") ;
scanf("%d", &t) ;
printf("\nEnter the limit : ") ;
scanf("%d", &n) ;
printf("\nThe table is :\n\n") ;
for(i = 1 ; i <= n ; i++)
printf("%4d + %4d = %4d\n", i, t, i + t) ;
getch() ;
}
</pre>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8612108870928357610.post-10426240965957126752015-06-27T10:51:00.000+05:302015-07-26T02:49:28.407+05:30Program to count number of digits in an integer | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here’s a C program to count the number of digits in an integer with output and proper explanation. The program uses while loop.</div>
<br />
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int n, count = 0 ;
clrscr() ;
printf("Enter a number: ") ;
scanf("%d", &n) ;
while(n > 0)
{
count++ ;
n = n / 10 ;
}
printf("\nThe number of digits is: %d", count) ;
getch() ;
}
</pre>
<br />
<br />
<b>Output of above program</b><br />
<br />
Enter a number: 52<br />
<br />
The number of digits is: 2<br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program
</b> </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
In this program we are first inputting an integer, counting the total number of digits in that number and finally displaying the output to the user. Let’s see how the above program does this. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
There are two variables - n to hold the number and count to count the number of digits in that number (n).<br />
<br />
Next we are asking the user to enter a number and storing it in the variable n. After that our while loop calculates the number of digits in n. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
To understand what is happening inside while loop it’s better to take an example. Suppose, user entered 52. The process of while loop with n = 52 is as follows - </div>
<ul style="text-align: justify;">
<li>First n > 0 i.e. 52 > 0, so the program will enter in the while loop. </li>
<li>In the next step, value of count (initialized to 0 at the start of program) is incremented by 1 with the help of C’s auto incrementing operator (++). So after this step, value of count is 1. </li>
<li>Now the number (n) is divided by 10 and result is stored again in n i.e. n = n / 10 or n = 52 / 10. Now as you know when you divide two numbers and store the result in an integer variable, only integer part of that result is stored in that integer variable not the fractional part. So when you divide 52 by 10, even when the correct result is 5.2 the new value of n will be 5 i.e. after this step n = 5 and count = 1. </li>
<li>Now that all statements inside the while loop has been executed once, the looping condition is again checked. </li>
<li>Again n > 0 i.e. 5 > 0, so the program will again enter the while loop and above steps are followed in the same manner, each time incrementing the value of count by 1 and dividing the number by 10.</li>
<li> Once the value of n becomes 0 or less than 0, the while loop will exit and rest of the program will continue execution. </li>
</ul>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<b>Tip: </b>To understand the program you can also take different values of n and try the above process yourself. It will help you to understand the process much clearly and helps in improving your debugging ability.</div>
</blockquote>
<ul style="text-align: justify;">
</ul>
</div>
Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-8612108870928357610.post-74765259039951331122015-06-14T13:11:00.000+05:302015-07-26T02:42:36.019+05:30Ternary Operator in C<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Ternary operator is an operator which can be used in place of an if else condition when both if and else part has only one line inside them. Lets look at the syntax of ternary operator in C language and understand ternary operators with example.</div>
<a name='more'></a><br />
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b><span style="font-size: large;">Syntax of Ternary Operators in C</span></b><br />
<br />
<span style="font-size: large;"><span style="font-size: small;">Here is the syntax of ternary operator along with its if else equivalent code.</span></span><br />
<span style="font-size: large;"><span style="font-size: small;"> </span></span><b><span style="font-size: large;"> </span></b></div>
<div style="text-align: justify;">
<pre class="cpp" name="code">(some condition to check) ? (if condition is true) : (if condition is false);
/*
if(some condition to check){
//if condition is true
}else{
//if condition is fasle
}
*/
</pre>
</div>
<br />
<br />
Ternary operator has three operands (as the name ternary suggests).<br />
<ul style="text-align: left;">
<li>First is the condition which needs to be checked for true or false. </li>
<li>After the condition, there is a <b>question mark ( ? )</b> and after the question mark comes the statement which is executed if the condition is true i.e the if part of if else.</li>
<li>At last there is a<b> colon ( : )</b> and after colon comes the statement which is executed if the condition is false i.e the else part of if else.</li>
</ul>
<br />
<ul style="text-align: left;">
</ul>
<span style="font-size: large;"><a href="http://cprogramming.language-tutorial.com/2012/01/biggest-of-3-numbers-using-ternary.html">Example of Ternary Operator in C</a></span></div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-68316635937900371032015-06-10T10:48:00.000+05:302015-07-26T02:41:54.838+05:30C++ Interview Questions - Constructor and Destructor<div dir="ltr" style="text-align: left;" trbidi="on">
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
<b>Q: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?</b><br />
A: There is nothing like Virtual Constructor. The Constructor can’t be
virtual as the constructor is a code which is responsible for creating
an instance of a class and it can’t be delegated to any other object by
virtual keyword means.<b></b></div>
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
<br /></div>
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
<b>Q: What is constructor or ctor?</b><br />
A: Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is<br />
different from other methods in a class.<b></b></div>
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
<br /></div>
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
<b>Q: What about Virtual Destructor?</b><br />
A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime<br />
depending on the type of object caller is calling to, proper destructor will be called.</div>
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
</div>
<div data-mce-style="text-align: left;" dir="ltr" style="text-align: left;">
<b>Q: What is the difference between a copy constructor and an overloaded assignment operator?</b><br />
A: A copy constructor constructs a new object by using the content of the argument object. An<br />
overloaded assignment operator assigns the contents of an existing object to another existing<br />
object of the same class.<br />
<br />
<b>Q: Can a constructor throws an exception? How to handle the error when the constructor fails?</b><br />
A:The constructor never throws an error.<br />
<br />
<b>Q: What is default constructor?</b><br />
A: Constructor with no arguments or all the arguments has default values.<br />
<br />
<b>Q: What is copy constructor?</b><br />
A: Constructor which initializes the it's object member variables ( by
shallow copying) with another object of the same class. If you don't
implement one in your class then compiler implements one for you. for
example:<br />
(a) Boo Obj1(10); // calling Boo constructor<br />
(b) Boo Obj2(Obj1); // calling boo copy constructor<br />
(c) Boo Obj2 = Obj1;// calling boo copy constructor<br />
<br />
<b>Q: When are copy constructors called?</b><br />
A: Copy constructors are called in following cases:<br />
(a) when a function returns an object of that class by value<br />
(b) when the object of that class is passed by value as an argument to a function<br />
(c) when you construct an object based on another object of the same class<br />
(d) When compiler generates a temporary object<br />
<br />
<b>Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?</b><br />
A: No. It is specified in the definition of the copy constructor
itself. It should generate an error if a programmer specifies a copy
constructor with a first argument that is an object and not a reference.<br />
<br />
<b>Q: What is conversion constructor?</b><br />
A: constructor with a single argument makes that constructor as conversion ctor and it can beused for type conversion.<br />
for example:<br />
<pre class="cpp" name="code">class Boo{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object</pre>
<br />
<b>Q:What is conversion operator??</b><br />
A:class can have a public method for specific data type conversions.<br />
for example:<br />
<pre class="cpp" name="code">class Boo{
double value;
public:
Boo(int i )
operator double(){
return value;
}
};
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double.</pre>
now conversion operator gets called to assign the value.<br />
<br />
<b>Q: How can I handle a constructor that fails?</b><br />
A: throw an exception. Constructors don't have a return type, so it's
not possible to use return codes. The best way to signal constructor
failure is therefore to throw an exception.<br />
<br />
<b>Q: How can I handle a destructor that fails?</b><br />
A: Write a message to a log-_le. But do not throw an exception. The C++
rule is that you must never throw an exception from a destructor that
is being called during the "stack unwinding" process of another
exception. For example, if someone says throw Foo(), the stack will be
unwound so all the stack frames between the throw Foo() and the } catch
(Foo e) { will get popped. This is called stack unwinding. During stack
unwinding, all the local objects in all those stack frames are
destructed. If one of those destructors throws an exception (say it
throws a Bar object), the C++ runtime system is in a no-win situation:
should it ignore the Bar and end up in the } catch (Foo e) { where it
was originally headed? Should it ignore the Foo and look for a } catch
(Bare) { handler? There is no good answer:either choice loses
information. So the C++ language guarantees that it will call
terminate() at this point, and<br />
terminate() kills the process. Bang you're dead.<br />
<br />
<b>Q: What is Virtual Destructor?</b><br />
A: Using virtual destructors, you can destroy objects without knowing
their type - the correct destructor for the object is invoked using the
virtual function mechanism. Note that destructors can also be declared
as pure virtual functions for abstract classes. if someone will derive
from your class, and if someone will say "new Derived", where "Derived"
is derived from your class, and if someone will say delete p, where the
actual object's type is "Derived" but the pointer p's type is your
class.<br />
<br />
<b>Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?</b><br />
A: No. It is specified in the definition of the copy constructor
itself. It should generate an error if a programmer specifies a copy
constructor with a first argument that is an object and not a reference.<b> </b><br />
<br />
<b>Q: What's the order that local objects are destructed?</b><br />
A: In reverse order of construction: First constructed, last
destructed. In the following example, b's destructor will be executed
first, then a's destructor:<br />
<pre class="cpp" name="code">void userCode(){
Fred a;
Fred b;
...
}</pre>
<pre class="cpp" name="code"> </pre>
<b>Q: What's the order that objects in an array are destructed?</b><br />
A: In reverse order of construction: First constructed, last
destructed. In the following example, the order for destructors will be
a[9], a[8], ..., a[1], a[0]:<br />
<pre class="cpp" name="code">void userCode(){
Fred a[10];
...
}</pre>
<pre class="cpp" name="code"></pre>
<b>Q: Can I overload the destructor for my class?</b><br />
A: No.<br />
You can have only one destructor for a class Fred. It's always called
Fred::~Fred(). It never takes any parameters, and it never returns
anything.<br />
You can't pass parameters to the destructor anyway, since you never explicitly call a destructor (well, almost never).<br />
<br />
<b>Q: Should I explicitly call a destructor on a local variable?</b><br />
A: No!<br />
The destructor will get called again at the close } of the block in
which the local was created. This is a guarantee of the language; it
happens automagically; there's no way to stop it from happening. But you
can get really bad results from calling a destructor on the same object
a second time! Bang! You're dead!<br />
<br />
<b>Q: What if I want a local
to "die" before the close } of the scope in which it was created? Can I
call a destructor on a local if I really want to?</b><br />
A: No! [For context, please read the previous FAQ].<br />
Suppose the (desirable) side effect of destructing a local File object
is to close the File. Now suppose you have an object f of a class File
and you want File f to be closed before the end of the scope (i.e., the
}) of the scope of object f:<br />
<pre class="cpp" name="code">void someCode(){
File f;
...insert code that should execute when f is still open...
We want the side-effect of f's destructor here!
...insert code that should execute after f is closed...
}</pre>
There is a simple solution to this problem. But in the mean time, remember: Do not explicitly<br />
call the destructor!<br />
<br />
<b>Q: OK, OK already; I won't explicitly call the destructor of a local; but how do I handle the above situation?</b><br />
A: Simply wrap the extent of the lifetime of the local in an artificial block {...}:<br />
<pre class="cpp" name="code">void someCode(){
{
File f;
...insert code that should execute when f is still open...
} f's destructor will automagically be called here!
...insert code here that should execute after f is closed...
}</pre>
<br />
<br />
<b>Q: What if I can't wrap the local in an artificial block?</b><br />
A: Most of the time, you can limit the lifetime of a local by wrapping
the local in an artificial block ({...}). But if for some reason you
can't do that, add a member function that has a similar effect as the
destructor. But do not call the destructor itself!<br />
For example, in
the case of class File, you might add a close() method. Typically the
destructor will simply call this close() method. Note that the close()
method will need to mark the File object so a subsequent call won't
re-close an already-closed File. E.g., it might set thefileHandle_ data
member to some nonsensical value such as -1, and it might check at the
beginning to see if the fileHandle_ is already equal to -1:<br />
<pre class="cpp" name="code">class File {
public:
void close();
~File();
...
private:
int fileHandle_; // fileHandle_ >= 0 if/only-if it's open
};
File::~File(){
close();
}
void File::close(){
if (fileHandle_ >= 0) {
...insert code to call the OS to close the file...
fileHandle_ = -1;
}
}</pre>
Note that the other File methods may also need to check if the fileHandle_ is -1 (i.e., check if the File is closed).<br />
Note also that any constructors that don't actually open a file should set fileHandle_ to -1.<br />
<br />
<b> Q: But can I explicitly call a destructor if I've allocated my object with new?</b><br />
A: Probably not.<br />
Unless you used placement new, you should simply delete the object
rather than explicitlycalling the destructor. For example, suppose you
allocated the object via a typical new expression:<br />
Fred* p = new Fred();<br />
Then the destructor Fred::~Fred() will automagically get called when you delete it via:<br />
delete p; // Automagically calls p->~Fred()<br />
You should not explicitly call the destructor, since doing so won't
release the memory that was allocated for the Fred object itself.
Remember: delete p does two things: it calls the destructor and it
deallocates the memory.<br />
<br />
<b>Q: What is "placement new" and why would I use it?</b><br />
A: There are many uses of placement new. The simplest use is to place
an object at a particular location in memory. This is done by supplying
the place as a pointer parameter to the new part of a new expression:<br />
<pre class="cpp" name="code">#include // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred
void someCode()n{
char memory[sizeof(Fred)]; // Line #1
void* place = memory; // Line #2
Fred* f = new(place) Fred(); // Line #3 (see "DANGER" below)
// The pointers f and place will be equal
...
}</pre>
Line #1 creates an array of sizeof(Fred) bytes of memory, which is big
enough to hold a Fred object. Line #2 creates a pointer place that
points to the first byte of this memory (experienced C programmers will
note that this step was unnecessary; it's there only to make the code
more obvious). Line #3 essentially just calls the constructor
Fred::Fred(). The this pointer in the Fred constructor will be equal to
place. The returned pointer f will therefore be equal to place.<br />
<i><b>ADVICE:</b></i>
Don't use this "placement new" syntax unless you have to. Use it only
when you reallycare that an object is placed at a particular location in
memory. For example, when your hardware has a memory-mapped I/O timer
device, and you want to place a Clock object at that memory location.<br />
<i><b>DANGER:</b></i>
You are taking sole responsibility that the pointer you pass to the
"placement new" operator points to a region of memory that is big enough
and is properly aligned for the object type that you're creating.
Neither the compiler nor the run-time system make any attempt to check
whether you did this right. If your Fred class needs to be aligned on a 4
byte boundary but you supplied a location that isn't properly aligned,
you can have a serious disaster on your hands (if you don't know what
"alignment" means, please don't use the placement new syntax). You have
been warned.<br />
You are also solely responsible for destructing the placed object. This is done by explicitly calling the destructor:<br />
<pre class="cpp" name="code">void someCode(){
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
...
f->~Fred(); // Explicitly call the destructor for the placed object
}</pre>
This is about the only time you ever explicitly call a destructor.<br />
Note: there is a much cleaner but more sophisticated way of handling the destruction / deletionsituation.<br />
<br />
<b> Q: When I write a destructor, do I need to explicitly call the destructors for my member objects?</b><br />
A: No. You never need to explicitly call a destructor (except with
placement new). A class's destructor (whether or not you explicitly
define one) automagically invokes the destructors for member objects.
They are destroyed in the reverse order they appear within the
declaration for the class.<br />
<pre class="cpp" name="code">class Member {
public:
~Member();
...
};
class Fred {
public:
~Fred();
...
private:
Member x_;
Member y_;
Member z_;
};
Fred::~Fred(){
// Compiler automagically calls z_.~Member()
// Compiler automagically calls y_.~Member()
// Compiler automagically calls x_.~Member()
}</pre>
<br />
<br />
<b> Q: When I write a derived class's destructor, do I need to explicitly call the destructor for my base class?</b><br />
A: No. You never need to explicitly call a destructor (except with
placement new).A derived class's destructor (whether or not you
explicitly define one) automagically invokes the destructors for base
class subobjects. Base classes are destructed after member objects. In
the event of multiple inheritance, direct base classes are destructed in
the reverse order of theirappearance in the inheritance list.<br />
<pre class="cpp" name="code">class Member {
public:
~Member();
...
};
class Base {
public:
virtual ~Base(); // A virtual destructor
...
};<
class Derived : public Base {
public:
~Derived();
...
private:
Member x_;
};
Derived::~Derived(){
// Compiler automagically calls x_.~Member()
// Compiler automagically calls Base::~Base()
}</pre>
Note: Order dependencies with virtual inheritance are trickier. If you
are relying on order dependencies in a virtual inheritance hierarchy,
you'll need a lot more information than is in this FAQ.<br />
<br />
<b> Q: Is there any difference between List x; and List x();?</b><br />
A: A big difference!<br />
Suppose that List is the name of some class. Then function f() declares a local List object called x:<br />
<pre class="cpp" name="code">void f(){
List x; // Local object named x (of class List)
...
}</pre>
But function g() declares a function called x() that returns a List:<br />
<pre class="cpp" name="code">void g()
List x(); // Function named x (that returns a List)
...
}</pre>
<br />
<br />
<b> Q: Can one constructor of a class call another constructor of the same class to initialize the this object?</b><br />
A: Nope.<br />
Let's work an example. Suppose you want your constructor Foo::Foo(char)
to call another constructor of the same class, say Foo::Foo(char,int),
in order that Foo::Foo(char,int) would help initialize the this object.
Unfortunately there's no way to do this in C++. Some people do it
anyway. Unfortunately it doesn't do what they want. For example, the
line Foo(x, 0); does not call Foo::Foo(char,int) on the this object.
Instead it calls Foo::Foo(char,int) to initialize a temporary, local
object (not this), then it immediately destructs that temporary when
control flows over the ;.<br />
<pre class="cpp" name="code">class Foo {
Foo(char x);
Foo(char x, int y);
...
};
Foo::Foo(char x) {
...
Foo(x, 0); // this line does NOT help initialize the this object!!
...
}</pre>
You can sometimes combine two constructors via a default parameter:<br />
<pre class="cpp" name="code">class Foo {
public:
Foo(char x, int y=0); // this line combines the two constructors
...
};</pre>
If that doesn't work, e.g., if there isn't an appropriate default
parameter that combines the two constructors, sometimes you can share
their common code in a private init() member function:<br />
<pre class="cpp" name="code">class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
private:>
void init(char x, int y);
};
Foo::Foo(char x){
init(x, int(x) + 7);
...
}
Foo::Foo(char x, int y){
init(x, y);
}
void Foo::init(char x, int y){
...
}</pre>
BTW do NOT try to achieve this via placement new. Some people think
they can say new(this) Foo(x, int(x)+7) within the body of
Foo::Foo(char). However that is bad, bad, bad. Please don't write me and
tell me that it seems to work on your particular version of your
particular compiler; it's bad. Constructors do a bunch of little magical
things behind the scenes, but that bad technique steps on those
partially constructed bits. Just say no.<br />
<br />
<b> Q: Is the default constructor for Fred always Fred::Fred()?</b><br />
A: No. A "default constructor" is a constructor that can be called with
no arguments. One example of this is a constructor that takes no
parameters:<br />
<pre class="cpp" name="code">class Fred {
public:
Fred(); // Default constructor: can be called with no args
...
};</pre>
Another example of a "default constructor" is one that can take arguments, provided they are given default values:<br />
<pre class="cpp" name="code">class Fred {
public:
Fred(int i=3, int j=5); // Default constructor: can be called with no args
...
};</pre>
<br />
<br />
<b> Q: Which constructor gets called when I create an array of Fred objects?</b><br />
A: Fred's default constructor (except as discussed below).<br />
<pre class="cpp" name="code">class Fred {
public:
Fred();
...
};
int main(){
Fred a[10]; //calls the default constructor 10 times
Fred* p = new Fred[10]; //calls the default constructor 10 times
...
}</pre>
<br />
If your class doesn't have a default constructor, you'll get a
compile-time error when you attempt to create an array using the above
simple syntax:<br />
<pre class="cpp" name="code">class Fred {
public:
Fred(int i, int j); //assume there is no default constructor
...
};
int main() {
Fred a[10]; //ERROR: Fred doesn't have a default constructor
Fred* p = new Fred[10]; //ERROR: Fred doesn't have a default constructor
...
}</pre>
<br />
However, even if your class already has a default constructor, you
should try to use std::vector rather than an array (arrays are evil).
std::vector lets you decide to use any constructor, not just the default
constructor:<br />
<pre class="cpp" name="code">#include
int main(){
std::vector a(10, Fred(5,7)); //the 10 Fred objects in std::vector a will be initialized with Fred(5,7)
...
}</pre>
<br />
Even though you ought to use a std::vector rather than an array, there
are times when an arraymight be the right thing to do, and for those,
you might need the "explicit initialization of arrays" syntax. Here's
how:<br />
<pre class="cpp" name="code">class Fred {
public:
Fred(int i, int j); //assume there is no default constructor
...
};
int main() {
Fred a[10] = {
Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), // The 10 Fred objects are
Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7) // initialized using Fred(5,7)
};
...
}</pre>
<br />
Of course you don't have to do Fred(5,7) for every entry you can put in
any numbers you want, even parameters or other variables.<br />
Finally,
you can use placement-new to manually initialize the elements of the
array. Warning: it's ugly: the raw array can't be of type Fred, so
you'll need a bunch of pointer-casts to do things like compute array
index operations. Warning: it's compiler- and hardware-dependent: you'll
need to make sure the storage is aligned with an alignment that is at
least as strict as is required for objects of class Fred. Warning: it's
tedious to make it exception-safe: you'll need to manually destruct the
elements, including in the case when an exception is thrown part-way
through the loop that calls the constructors. But if you really want to
do it anyway, read up on placementnew. (BTW placement-new is the magic
that is used inside of std::vector. The complexity of getting everything
right is yet another reason to use std::vector.) By the way, did I ever
mention that arrays are evil? Or did I mention that you ought to use a<br />
std::vector unless there is a compelling reason to use an array?<br />
<br />
<b> Q: Should my constructors use "initialization lists" or "assignment"?</b><br />
A: Initialization lists. In fact, constructors should initialize as a
rule all member objects in the initialization list. One exception is
discussed further down. Consider the following constructor that
initializes member object x_ using an initialization list:<br />
Fred::Fred() : x_(whatever) { }. The most common benefit of doing this
is improved performance. For example, if the expression whatever is the
same type as member variable x_, the result of the whatever expression
is constructed directly inside x_ the compiler does not make a separate
copy of the object. Even if the types are not the same, the compiler is
usually able to do a better job with initialization lists than with
assignments. The other (inefficient) way to build constructors is via
assignment, such as: Fred::Fred() { x_ = whatever; }. In this case the
expression whatever causes a separate, temporary object to be created,
and this temporary object is passed into the x_ object's assignment
operator. Then that temporary object is destructed at the ;. That's
inefficient. As if that wasn't bad enough, there's another source of
inefficiency when using assignment in a constructor: the member object
will get fully constructed by its default constructor, and this might,
for example, allocate some default amount of memory or open some default
file. All thiswork could be for naught if the whatever expression
and/or assignment operator causes the object to close that file and/or
release that memory (e.g., if the default constructor didn't allocate a
large enough pool of memory or if it opened the wrong file). Conclusion:
All other things being equal, your code will run faster if you use
initialization lists rather than assignment.<br />
Note: There is no
performance difference if the type of x_ is some built-in/intrinsic
type, such as int or char* or float. But even in these cases, my
personal preference is to set those data members in the initialization
list rather than via assignment for consistency. Another symmetry
argument in favor of using initialization lists even for
built-in/intrinsic types: non-static const and nonstatic<br />
reference
data members can't be assigned a value in the constructor, so for
symmetry it makes sense to initialize everything in the initialization
list. Now for the exceptions. Every rule has exceptions (hmmm; does
"every rule has exceptions" have exceptions? reminds me of Gdel's
Incompleteness Theorems), and there are a couple of exceptions to the
"use initialization lists" rule. Bottom line is to use common sense: if
it's cheaper, better, faster, etc. to not use them, then by all means,
don't use them. This might happen<br />
when your class has two
constructors that need to initialize the this object's data members in
different orders. Or it might happen when two data members are
self-referential. Or when a data member needs a reference to the this
object, and you want to avoid a compiler warning about using the this
keyword prior to the { that begins the constructor's body (when your
particular compiler happens to issue that particular warning). Or when
you need to do an if/throw test on a variable (parameter, global, etc.)
prior to using that variable to initialize one of your this members.
This list is not exhaustive; please don't write me asking me to add
another "Or<br />
when...". The point is simply this: use common sense.<br />
<b> Q: Should you use the this pointer in the constructor?</b><br />
A: Some people feel you should not use the this pointer in a
constructor because the object is not fully formed yet. However you can
use this in the constructor (in the {body} and even in the
initialization list) if you are careful.<br />
Here is something that
always works: the {body} of a constructor (or a function called from the
constructor) can reliably access the data members declared in a base
class and/or the data members declared in the constructor's own
class.This is because all those data members are guaranteed to have been
fully constructed by the time the constructor's {body} starts
executing.<br />
Here is something that never works: the {body} of a
constructor (or a function called from the constructor) cannot get down
to a derived class by calling a virtual member function that is
overridden in the derived class. If your goal was to get to the
overridden function in the derived class, you won't get what you want.
Note that you won't get to the override in the derived class independent
of how you call the virtual member function: explicitly using the this
pointer (e.g., this->method()), implicitly using the this pointer
(e.g., method()), or even calling some other function that calls the
virtual member function on your this object. The bottom line is this:
even if the caller is constructing an object of a derived class, during
the constructor of the base class, your object is not yet of that
derived class. You have been warned. Here is something that sometimes
works: if you pass any of the data members in this object to another
data member's initializer, you must make sure that the other data member
has already been initialized. The good news is that you can determine
whether the other data member has (or has not) been initialized using
some straightforward language rules that are independent of the
particular compiler you're using. The bad news it that you have to know
those language rules (e.g., base class sub-objects are initialized first
(look up the order if you have multiple and/or virtual inheritance!),
then data members defined in the class are initialized in the order in
which they appear in the class declaration). If you don't know these
rules, then don't pass any data member from the this object (regardless
of whether or not you explicitly use the this keyword) to any other data
member's initializer! And if you do know the rules, please be careful.<br />
<b>Q: What is the "Named Constructor Idiom"?</b><br />
A: A technique that provides more intuitive and/or safer construction operations for users of your class.<br />
The problem is that constructors always have the same name as the
class. Therefore the only way to differentiate between the various
constructors of a class is by the parameter list. But if there are lots
of constructors, the differences between them become somewhat subtle and
error prone. With the Named Constructor Idiom, you declare all the
class's constructors in the private or protected sections, and you
provide public static methods that return an object. These static<br />
methods are the so-called "Named Constructors." In general there is one
such static method for each different way to construct an object.<br />
For example, suppose we are building a Point class that represents a
position on the X-Y plane. Turns out there are two common ways to
specify a 2-space coordinate: rectangular coordinates (X+Y), polar
coordinates (Radius+Angle). (Don't worry if you can't remember these;
the point isn't the particulars of coordinate systems; the point is
that there are several ways to create a Point object.) Unfortunately the
parameters for these two coordinate systems are the same: two floats.
This would create an ambiguity error in the overloaded constructors:<br />
<pre class="cpp" name="code">class Point {
public:
Point(float x, float y); // Rectangular coordinates
Point(float r, float a); // Polar coordinates (radius and angle)
// ERROR: Overload is Ambiguous: Point::Point(float,float)
};
int main() {
Point p = Point(5.7, 1.2); // Ambiguous: Which coordinate system?
...
}</pre>
<br />
One way to solve this ambiguity is to use the Named Constructor Idiom:
<br />
<pre class="cpp" name="code">#include // To get sin() and cos()
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point::Point(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }
inline Point Point::polar(float radius, float angle)
{ return Point(radius*cos(angle), radius*sin(angle)); }
Now the users of Point have a clear and unambiguous syntax for creating Points in either coordinate system:
int main() {
Point p1 = Point::rectangular(5.7, 1.2); // Obviously rectangular
Point p2 = Point::polar(5.7, 1.2); // Obviously polar
...
}</pre>
<br />
Make sure your constructors are in the protected section if you expect
Point to have derivedclasses.The Named Constructor Idiom can also be
used to make sure your objects are always created via new. Note that the
Named Constructor Idiom, at least as implemented above, is just as fast
as directly calling a constructor modern compilers will not make any
extra copies of your object.</div>
</div>
Unknownnoreply@blogger.com9tag:blogger.com,1999:blog-8612108870928357610.post-89041103246564729552015-06-04T20:26:00.000+05:302015-07-26T02:40:13.000+05:30C++ Interview Questions with Answers Part 1<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Q.1) What is C++?</b><br />
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.<br />
<br />
<b>Q.2) C++ used for:</b><br />
C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can be used to make CGI scripts or console-only DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.<br />
<br />
<b>Q.3) How do you find out if a linked-list has an end? (i.e. the list is not a cycle) </b><br />
You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle. <br />
<br />
<b>Q.4) What is the difference between realloc() and free()?</b><br />
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer. <br />
<br />
<b>Q.5) What is function overloading and operator overloading?</b><br />
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. <br />
Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs). <br />
<br />
<b>Q.6) What is the difference between declaration and definition?</b><br />
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.<br />
E.g.: <br />
<pre class="cpp" name="code">void stars () //function declaration </pre>
<br />
The definition contains the actual implementation.<br />
E.g.: <br />
<pre class="cpp" name="code">void stars (){// declarator
for(int j=10; j > =0; j--) //function body
cout << *;
cout << endl;
}</pre>
<br />
<br />
<b>Q.7) What are the advantages of inheritance?</b> <br />
<br />
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional. <br />
<br />
<b>Q.8) How do you write a function that can reverse a linked-list? </b><br />
<br />
<pre class="cpp" name="code">void reverselist(void){
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail){
head->next = 0;
tail->next = head;
} else {
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur-> next = head;
for(; curnext!=0; ){
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}
</pre>
<br />
<br />
<b>Q.9) What do you mean by inline function?</b><br />
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables. <br />
<br />
<b>Q. 10) Write a program that ask for user input from 5 to 9 then calculate the average </b><br />
<pre class="cpp" name="code">#include "iostream.h"
int main() {
int MAX = 4;
int total = 0;
int average;
int numb;
for (int i=0; i<MAX; i++) {
cout << "Please enter your input between 5 and 9: ";
cin >>
while ( numb<5 || numb>9) {
cout << "Invalid input, please re-enter: ";
cin >> numb;
}
total = total + numb;
}
average = total/MAX;
cout << "The average number is: " << average << "\n";
return 0;
}
</pre>
<br />
<br />
<b>Q. 11) Write a short code using C++ to print out all odd number from 1 to 100 using a for loop </b><br />
<pre class="cpp" name="code">for( unsigned int i = 1; i < = 100; i++ )
if( i & 0x00000001 ) cout << i << \",\";
</pre>
<br />
<b>Q.12) What is public, protected, private?</b> <br />
Public, protected and private are three access specifier in C++. <br />
<ul style="text-align: left;">
<li>Public data members and member functions are accessible outside the class. </li>
<li>Protected data members and member functions are only available to derived classes. </li>
<li>Private data members and member functions can’t be accessed outside the class. However there is an exception can be using friend classes.</li>
</ul>
<b>Q.13) Write a function that swaps the values of two integers, using int* as the argument type. </b><br />
<pre class="cpp" name="code">void swap(int* a, int*b) {
int t;
t = *a;
*a = *b;
*b = t;
}</pre>
<br />
<br />
<b>Q.14) Tell how to check whether a linked list is circular.</b> <br />
Create two pointers, each set to the start of the list. Update each as follows:<br />
<pre class="cpp" name="code">while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next;
if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print (\"circular\n\");
}
}</pre>
<br />
<br />
<b>Q.15) OK, why does this work?</b><br />
If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet. <br />
<br />
<b>Q.16) What is virtual constructors/destructors? </b><br />
<b><i>Answer1</i></b><br />
Virtual destructors:<br />
If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.<br />
There is a simple solution to this problem declare a virtual base-class destructor.<br />
This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. <br />
<br />
<b><i>Answer2</i></b><br />
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.<br />
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.<br />
<br />
<b>Q.17) Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. Does c++ support multilevel and multiple inheritance?</b><br />
Yes.<br />
<br />
Q.<b>18) What are the advantages of inheritance?</b><br />
<ul style="text-align: left;">
<li>It permits code reusability.</li>
<li>Reusability saves time in program development.</li>
<li>It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.</li>
</ul>
<br />
<b>Q.19) What is the difference between declaration and definition?</b><br />
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.<br />
E.g.: <br />
<pre class="cpp" name="code">void stars () //function declaration</pre>
<br />
The definition contains the actual implementation.<br />
E.g.: <br />
<pre class="cpp" name="code">void stars () {// declarator
for(int j=10; j>=0; j--) //function body
cout<<”*”;
cout<<endl;
}</pre>
<br />
<br />
<b>Q.20) What is the difference between an ARRAY and a LIST?</b><br />
<b><i>Answer1</i></b><br />
Array is collection of homogeneous elements.<br />
List is collection of heterogeneous elements. <br />
<br />
For Array memory allocated is static and continuous.<br />
For List memory allocated is dynamic and Random. <br />
<br />
Array: User need not have to keep in track of next memory allocation.<br />
List: User has to keep in Track of next location where memory is allocated. <br />
<br />
<b><i>Answer2</i></b><br />
Array uses direct access of stored members, list uses sequencial access for members.<br />
<br />
<pre class="cpp" name="code">//With Array you have direct access to memory position 5
Object x = a[5]; // x takes directly a reference to 5th element of array
//With the list you have to cross all previous nodes in order to get the 5th node:
list mylist;
list::iterator it;
for( it = list.begin() ; it != list.end() ; it++ ){
if( i==5){
x = *it;
break;
}
i++;
}</pre>
<br />
<br />
<b>Q.21) Does c++ support multilevel and multiple inheritance?</b> <br />
Yes. <br />
<br />
<b>Q.22) What is a template? </b><br />
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:<br />
template <class indetifier> function_declaration; template <typename indetifier> function_declaration;<br />
The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way. <br />
<br />
<b>Q.23) Define a constructor - What it is and how it might be called (2 methods).</b> <br />
<b>Answer1</b><br />
constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized.<br />
<br />
Ways of calling constructor:<br />
<ol style="text-align: left;">
<li>Implicitly: automatically by complier when an object is created.</li>
<li>Calling the constructors explicitly is possible, but it makes the code unverifiable.</li>
</ol>
<br />
<b>Answer2</b><br />
<pre class="cpp" name="code">class Point2D{
int x; int y;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
main(){
Point2D MyPoint; // Implicit Constructor call. In order to allocate memory on stack, the default constructor is implicitly called.
Point2D * pPoint = new Point2D(); // Explicit Constructor call. In order to allocate memory on HEAP we call the default constructor.
}</pre>
<br />
<br />
<b>Q.24) You have two pairs: new() and delete() and another pair : alloc() and free(). </b><br />
<b>Explain differences between eg. new() and malloc()</b> <br />
<i><b>Answer1</b></i><br />
1.) “new and delete” are preprocessors while “malloc() and free()” are functions. [we dont use brackets will calling new or delete]. <br />
2.) no need of allocate the memory while using “new” but in “malloc()” we have to use “sizeof()”. <br />
3.) “new” will initlize the new memory to 0 but “malloc()” gives random value in the new alloted memory location [better to use calloc()] <br />
<br />
<b><i>Answer2</i></b><br />
new() allocates continous space for the object instace<br />
malloc() allocates distributed space.<br />
new() is castless, meaning that allocates memory for this specific type,<br />
malloc(), calloc() allocate space for void * that is cated to the specific class type pointer.<br />
<br />
<b>Q.25) What is the difference between class and structure?</b> <br />
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. <br />
Class: Class is a successor of Structure. By default all the members inside the class are private.<br />
<br />
<b>Q.26) What is RTTI?</b><br />
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many Interview Questions - Homegrown versions with a solid, consistent approach. <br />
<br />
<b>Q.27) What is encapsulation?</b> <br />
Packaging an object’s variables within its methods is called encapsulation. <br />
<br />
<b>Q.28) Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE</b> <br />
<b><i>Answer1</i></b><br />
POLYMORPHISM : A phenomenon which enables an object to react differently to the same function call.<br />
in C++ it is attained by using a keyword virtual<br />
<br />
<i>Example</i><br />
<pre class="cpp" name="code">public class SHAPE{
public virtual void SHAPE::DRAW()=0;
}
</pre>
<blockquote class="tr_bq">
Note here the function DRAW() is pure virtual which means the sub classes must implement the DRAW() method and SHAPE cannot be instatiated </blockquote>
<br />
<pre class="cpp" name="code">public class CIRCLE::public SHAPE{
public void CIRCLE::DRAW(){
// TODO drawing circle
}
}
public class SQUARE::public SHAPE{
public void SQUARE::DRAW(){
// TODO drawing square
}
}</pre>
<br />
<br />
now from the user class the calls would be like<br />
<pre class="cpp" name="code">globally
SHAPE *newShape;
</pre>
When user action is to draw<br />
<br />
<pre class="cpp" name="code">public void MENU::OnClickDrawCircle(){
newShape = new CIRCLE();
}
public void MENU::OnClickDrawCircle(){
newShape = new SQUARE();
}
</pre>
the when user actually draws<br />
<br />
<pre class="cpp" name="code">public void CANVAS::OnMouseOperations(){
newShape->DRAW();
}</pre>
<br />
<br />
<br />
<b>Answer2</b><br />
<pre class="cpp" name="code">class SHAPE{
public virtual Draw() = 0; //abstract class with a pure virtual method
};
class CIRCLE{
public int r;
public virtual Draw() { this->drawCircle(0,0,r); }
};
class SQURE
public int a;
public virtual Draw() { this->drawRectangular(0,0,a,a); }
};
</pre>
<br />
Each object is driven down from SHAPE implementing Draw() function in its own way. <br />
<br />
<b>Q.29) What is an object?</b> <br />
Object is a software bundle of variables and related methods. Objects have state and behavior. <br />
<br />
<b>Q.30) How can you tell what shell you are running on UNIX system?</b> <br />
You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.<br />
<br />
<b>Q.31)What do you mean by inheritance? </b><br />
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.<br />
<br />
Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples.<br />
<br />
<pre class="cpp" name="code">class Point2D{
int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};
Point2D MyPoint;</pre>
<br />
You cannot directly access private data members when they are declared (implicitly) private: <br />
<br />
<pre class="cpp" name="code">MyPoint.x = 5; // Compiler will issue a compile ERROR
//Nor yoy can see them:
int x_dim = MyPoint.x; // Compiler will issue a compile ERROR
</pre>
<br />
On the other hand, you can assign and read the public data members: <br />
<br />
<pre class="cpp" name="code">MyPoint.color = 255; // no problem
int col = MyPoint.color; // no problem
</pre>
<br />
With protected data members you can read them but not write them:
<br />
<br />
<pre class="cpp" name="code">MyPoint.pinned = true; // Compiler will issue a compile ERROR
bool isPinned = MyPoint.pinned; // no problem</pre>
<div class="MsoNormal">
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8612108870928357610.post-49861945723407531712015-05-31T12:10:00.000+05:302015-07-26T02:38:55.130+05:30Finding the Number of 500, 100, 50, 20, 10, 5, 2, 1 Rupee Notes in a Given Amount<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a fun program in C programming language to find the number of 500, 100, 50, 20, 10, 5, 2, 1 rupee notes in a given amount. It'll surely help cashiers to mange things properly.</div>
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int rs, a, b, c, d, e, f, g, h ;
clrscr() ;
printf("Enter the amount in Rupees : ") ;
scanf("%d", &rs) ;
while(rs >= 500)
{
a = rs / 500 ;
rs = rs % 500;
printf("\nThe no. of five hundreds are : %d", a) ;
break ;
}
while(rs >= 100)
{
b = rs / 100 ;
rs = rs % 100;
printf("\n\nThe no. of hundreds are : %d", b) ;
break ;
}
while(rs >= 50)
{
c = rs / 50 ;
rs = rs % 50;
printf("\n\nThe no. of fifties are : %d", c) ;
break ;
}
while(rs >= 20)
{
d = rs / 20 ;
rs = rs % 20;
printf("\n\nThe no. of twenties are : %d", d) ;
break ;
}
while(rs >= 10)
{
e = rs / 10 ;
rs = rs % 10;
printf("\n\nThe no. of tens are : %d", e) ;
break ;
}
while(rs >= 5)
{
f = rs / 5 ;
rs = rs % 5;
printf("\n\nThe no. of fives are : %d", f) ;
break ;
}
while(rs >= 2)
{
g = rs / 2 ;
rs = rs % 2;
printf("\n\nThe no. of Twos are : %d", g) ;
break ;
}
while(rs >= 1)
{
h = rs / 1 ;
rs = rs % 1;
printf("\n\nThe no. of ones are : %d", h) ;
break ;
}
getch() ;
}
</pre>
<br />
<div style="text-align: justify;">
<span style="font-size: large;"><b>Output of above program is</b></span></div>
<br />
Enter the amount in Rupees : 698<br />
<br />
The no. of five hundreds are : 1<br />
<br />
The no. of hundreds are : 1 <br />
<br />
The no. of fifties are : 1 <br />
<br />
The no. of twenties are : 2 <br />
<br />
The no. of fives are : 1 <br />
<br />
The no. of Twos are : 1 <br />
<br />
The no. of ones are : 1<br />
<br />
<br />
<div style="text-align: justify;">
<span style="font-size: large;"><b>Explanation of above program</b></span></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Above program is pretty straightforward. All it does is that it takes an amount as input and shows how many 500, 100, 50, 10, 5, 2, 1 notes are needed. As this program contains all basics of C programming, lets understand this program by an example. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Remember: </b>When you divide two integer and stores the value in an integer only integer part of the result is stored e.g. 10 / 3 = 3.333 but when you store this result in another integer, it will only hold 3 as its value (to store the exact result use float as data type).</blockquote>
<blockquote class="tr_bq">
Also in C, <b>%</b> is modulus and is used to calculate remainder so e.g. 5 % 3 will be 2.</blockquote>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Suppose, rs = 698. Now we go step by step .</div>
<ul style="text-align: justify;">
<li>First while loop executes as 698 >= 500, so a = 698 / 500 = 1 and rs = rs % 500 = 698 % 500 = 198. The printf() is executed.</li>
<li>Next while loop executes as 198 >= 100, so a = 198 / 100 = 1 and rs = rs % 100 = 198 % 100 = 98. The printf() is executed.</li>
<li>Next while loop executes as 98 >= 50, so a = 98 / 50= 1 and rs = rs % 50 = 98 % 50 = 48. The printf() is executed. </li>
<li>Next while loop executes as 48 >= 20, so a = 48 / 20= 2 and rs = rs % 20 = 48 % 20 = 8. The printf() is executed. </li>
<li>The next while loop is not executed because 8 < 10.</li>
<li> Next while loop executes as 8 >= 5, so a = 8 / 5= 1 and rs = rs % 5 = 8 % 5 = 3. The printf() is executed. </li>
<li>Next while loop executes as 3 >= 2, so a = 3 / 2= 1 and rs = rs % 2 = 3 % 2 = 1. The printf() is executed. </li>
<li>Next while loop executes as 1 >= 1, so a = 1 / 1= 1 and rs = rs % 1 = 1 % 1 = 0. The printf() is executed. </li>
</ul>
<br /></div>
Unknownnoreply@blogger.com12tag:blogger.com,1999:blog-8612108870928357610.post-59469331953411218912015-01-26T21:56:00.000+05:302015-01-26T15:05:16.715+05:30Convert Numbers to Characters in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to convert the given number (1 to 10) to characters with output and proper explanation. This program makes use of C's <a href="http://cprogramming.language-tutorial.com/search/label/Switch%20Case">Switch Case</a> and <a href="http://cprogramming.language-tutorial.com/search/label/Break">Break </a>statements.</div>
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter a number <1 to 10> : ") ;
scanf("%d", &n) ;
switch(n)
{
case 1 :
printf("\nONE") ;
break ;
case 2 :
printf("\nTWO") ;
break ;
case 3 :
printf("\nTHREE") ;
break ;
case 4 :
printf("\nFOUR") ;
break ;
case 5 :
printf("\nFIVE") ;
break ;
case 6 :
printf("\nSIX") ;
break ;
case 7 :
printf("\nSEVEN") ;
break ;
case 8 :
printf("\nEIGHT") ;
break ;
case 9 :
printf("\nNINE") ;
break ;
case 10 :
printf("\nTEN") ;
break ;
default :
printf("\nInvalid Input.") ;
}
getch() ;
}
</pre>
<br />
<b>Output of above program is</b><br />
<br />
Enter a number <1 to 10> : 1 <br />
<br />
ONE<br />
<br />
<br />
<b>Explanation of above program </b><br />
<br />
<div style="text-align: justify;">
The program first asks user to enter a number between 1 to 10. When user enters a number the program take that
value and passes it to the switch-case statement. Here the program picks
a case based on the value that user entered before and executes that
particular case. If no case matches the users request, default case will
be executed.</div>
<div style="text-align: justify;">
<br /></div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<b>Suggestion</b>: If you notice you'll see that inside each case there is a break
statement. Now what is the need to use break statement inside each
case? <a href="http://cprogramming.language-tutorial.com/2012/01/why-use-break-statement-inside-switch.html">Read it here - Why use break statement inside switch case</a>. </div>
</blockquote>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Suppose user entered 1this value is passed to the switch case statement and the case that matches the value that's passed is executed. In this case, CASE 1 will be executed printing the text "ONE" and then execution of switch case is stopped using a break statement. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
When user enters a value that doesn't match any case then the default case is executed.</div>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8612108870928357610.post-57169310938945520162015-01-12T13:45:00.000+05:302015-01-26T15:06:22.128+05:30C Program to Check the Given Character is Vowel or not<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to check whether the given character is vowel or not with example and explanation. This program uses an <a href="http://cprogramming.language-tutorial.com/search/label/If%20Else%20in%20C">IF-ELSE Condition</a> to determine whether the given character is a vowel or not.</div>
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
char c ;
clrscr() ;
printf("Enter the character : ") ;
scanf("%c", &c) ;
if( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
printf("\n%c is a vowel", c) ;
else
printf("\n%c is not a vowel", c) ;
getch() ;
}
</pre>
<br />
<br />
<b>Output of above program</b> <br />
<br />
Enter the character : a<br />
a is a vowel<br />
<br />
<br />
Enter the character : z<br />
z is not a vowel<br />
<br />
<br />
<b>Explanation of above program</b> <br />
<br />
<div style="text-align: justify;">
This program first asks the user to enter a character and stores its value in character variable <b>c</b>. Then using an IF-Else condition, program checks whether the entered character is among {a, e, i, o, u, A, E, I, O, U}. If entered character is among this set, program prints that entered character is vowel otherwise, program prints that entered character is not a vowel.</div>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-67763485538190211922014-09-21T01:18:00.000+05:302015-01-26T15:01:52.935+05:30Program to Find Length of String in C<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to find the length of the given string with output and explanation. This program makes use of C concepts like <a href="http://cprogramming.language-tutorial.com/search/label/For%20Loop">For loop</a> and <a href="http://cprogramming.language-tutorial.com/search/label/gets%20Function%20in%20C">gets Function in C</a>.</div>
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
char str[80] ;
int i ;
clrscr() ;
printf("Enter the string : ") ;
gets(str) ;
for(i = 0 ; str[i] != '\0' ; i++) ;
printf("\nThe length of the string is : %d", i) ;
getch() ;
}
</pre>
<br />
<b>Output of above program</b> <br />
<br />
Enter the string : C Program<br />
The length of the string is : 9<br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
In this program, we have first declared a character array <i>str </i>of size 80. Then, the program prompts the user to enter a string whose length is to be found. String is taken as input using <i>gets</i> function (<a href="http://cprogramming.language-tutorial.com/2012/11/what-is-gets-function-in-c-with-syntax.html">What is gets function?</a>) and stored in character array <i>str </i>itself<i>. </i>After that using FOR loop, length of string is determined.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here if you look at the FOR loop, you might find its syntax a bit weird as there is no body of this FOR loop and the FOR statement is terminated by a semicolon (;). But working of FOR loop in this program is very simple. The loop runs from loop variable <i>i = 0 to str[i] != '\0'</i>, incrementing <i>i</i> each time until null character is encountered. This means that this FOR loop will until str[i] is null.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Lets understand the working of FOR loop using an example.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Suppose, user enters the string as "Hello" and this is stored in <i>str</i>. So now str = "Hello". Now, working of FOR loop is as follows -</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>When i = 0, str[i] = H</b>: Value of i is incremented to 1.</div>
<div style="text-align: justify;">
<b>When i = 1, str[i] = e</b>: Value of i is incremented to 2.</div>
<div style="text-align: justify;">
<b>When i = 2, str[i] = l</b>: Value of i is incremented to 3. </div>
<div style="text-align: justify;">
<b>When i = 3, str[i] = l</b>: Value of i is incremented to 4. </div>
<div style="text-align: justify;">
<b>When i = 4, str[i] = o</b>: Value of i is incremented to 5.</div>
<div style="text-align: justify;">
<b>When i = 5, str[i] = \0</b>: Loop is terminated.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
So, after FOR loop is executed, value of <i>i</i> shows the length of the string.</div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8612108870928357610.post-84540359111507649772014-09-16T15:21:00.000+05:302015-01-26T14:46:31.073+05:30Checking the Given Number is Armstrong or Not using C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to find the given number is Armstrong or not with output and proper explanation. This program also uses C while loop and modulus.</div>
<a name='more'></a><br />
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>What is an Armstrong Number?</b> A number is an Armstrong number if the sum of cubes of each digit of that number is equal to the number itself e.g. 153 is an Armstrong number i.e. 1<sup>3</sup> + 5<sup>3</sup> + 3<sup>3</sup> = 153.</blockquote>
</div>
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int n, r, s = 0, t ;
clrscr() ;
printf("Enter a number : ") ;
scanf("%d", &n) ;
t = n ;
while(n > 0)
{
r = n % 10 ;
s = s + (r * r * r) ;
n = n / 10 ;
}
if(s == t)
printf("\n%d is an armstrong number", t) ;
else
printf("\n%d is not an armstrong number", t) ;
getch() ;
}
</pre>
<br />
<b>Output of above program is </b><br />
<br />
Enter a number : 153<br />
153 is an armstrong number.<br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Following is the list and use of each variable that we're using in this program -</div>
<ul style="text-align: justify;">
<li>n - is the number that we're checking.</li>
<li>t - is the temporary variable whose value is equal to n i.e. t = n.</li>
<li>r - is used to store the remainder (we'll see that in a minute).</li>
<li>s - is the sum of cubes of all digits of n.</li>
</ul>
<div style="text-align: justify;">
We first ask the user to enter a number n and then we also store this value of n in temporary variable t. Then using the While loop we calculate sum of cubes of all digits of n. Outside the loop we check if the sum of cubes of all digits of n is equal to the number itself then we print that the number is Armstrong number otherwise the number is not an Armstrong number.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Suppose n = 153. So t is also 153. Let's see how while loop works in this example -</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>n = 153 i.e. n > 0. While loop's first iteration -</b></div>
<ul style="text-align: justify;">
<li>First we calculate value of r - <b>r = n % 10</b> = 153 % 10 = 3.</li>
<li>Next we update the value of sum i.e. s (currently equal to 0) as - <b>s = s + (r * r * r) = </b>0 + (3 * 3 * 3) = 27.</li>
<li>Next we update the value of n by - n = n / 10 = 153 / 10 = 15. (Since n is of data type int only integer value of division is stored in n).</li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>n = 15 i.e. n > 0. While loop's first iteration -</b></div>
<ul style="text-align: justify;">
<li>First we calculate value of r - <b>r = n % 10</b> = 15 % 10 = 5.</li>
<li>Next we update the value of sum i.e. s (now equal to 1) as - <b>s = s + (r * r * r) </b>= 27 + (5 * 5 * 5 ) = 27 + 125 = 152.</li>
<li>Next we update the value of n by - n = n / 10 = 15 / 10 = 1. </li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>n = 1 i.e. n > 0. While loop's first iteration -</b></div>
<ul style="text-align: justify;">
<li>First we calculate value of r - <b>r = n % 10</b> = 1 % 10 = 1.</li>
<li>Next we update the value of sum i.e. s (now equal to 126) as - <b>s = s + (r * r * r) = </b>152 + (1 * 1 * 1)= 152 + 1 = 153.</li>
<li>Next we update the value of n by - n = n / 10 = 1 / 10 = 0.</li>
</ul>
<div style="text-align: justify;">
n = 0 i.e n < 0. While loop is terminated now. Outside the loop, we compare the value of sum s and variable t and if these two are equal that means the number is Armstrong number. </div>
<div style="text-align: justify;">
<br /></div>
<br />
<ul style="text-align: left;">
</ul>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8612108870928357610.post-79244877310044060382014-09-10T23:20:00.000+05:302015-01-26T14:45:27.306+05:30Program to Find the Given Number is Perfect Number or not in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a c program to find the given no. is perfect no. or not with output and proper explanation.</div>
<a name='more'></a><br />
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>What are Perfect Numbers?</b> A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself e.g. 6 is a perfect number - Divisors of 6 are 1, 2, 3, 6 and 1 + 2 + 3 = 6. Another perfect number is 28.</blockquote>
</div>
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int i, n, s = 0 ;
clrscr() ;
printf("Enter a number : ") ;
scanf("%d", &n) ;
for(i = 1 ; i < n ; i++)
{
if(n % i == 0)
s = s + i ;
}
if (s == n)
printf("\n%d is a perfect number", n) ;
else
printf("\n%d is not a perfect number", n) ;
getch() ;
}
</pre>
<br />
<b>Output of above program is </b><br />
<br />
Enter a number : 5<br />
5 is not a perfect number<br />
<br />
Enter a number : 6 <br />
6 is a perfect number <br />
<br />
Enter a number : 28 <br />
28 is a perfect number <br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here we have some integer variables let's understand the purpose of each first -</div>
<ul style="text-align: justify;">
<li>n - This is the number that user enters.</li>
<li>s - It is used to calculate the sum of all divisors of number n (excluding n itself). This sum is later compared with the original number to check for the perfect number.</li>
<li>i - This is the loop variable.</li>
</ul>
<div style="text-align: justify;">
First the user enters a number to check whether that number is perfect or not. Then the for loop will run for i = 1 to i < n or up to i = n - 1. Inside the loop we check whether the number n is completely divisible by every number from 1 to n - 1 by using this expression - <b>n % i == 0.</b> If this expression is true then the if condition inside the loop gets executed and inside If we add that value of <b>i</b> to the sum variable<b> s</b>. Once the loop is finished we compare the sum variable and original number i.e. <b>n == s.</b> If this is true that means the number n is perfect otherwise it's not a perfect number.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Lets take an example - Suppose n = 6. The for loop will execute for i = 1 to i = 5. The process is as follows -</div>
<ul style="text-align: justify;">
<li><b>i = 1; </b>Value of n % i = 6 % 1 == 0, so the if condition is executed and sum is updated as - s = s + i = 0 + 1 = 1.</li>
<li><b>i = 2;</b> Value of n % i = 6 % 2 == 0, so the if condition is executed and sum is updated as - s = s + i = 1 + 2 = 3.</li>
<li><b>i = 3;</b> Value of n % i = 6 % 3 == 0, so the if condition is executed and sum is updated as - s = s + i = 3 + 3 = 6.</li>
<li><b>i = 4;</b> Value of n % i = 6 % 4 == 2, The for loop will continue with the next value of i.</li>
<li><b>i = 5;</b> Value of n % i = 6 % 5 == 1, The for loop will terminate now.</li>
</ul>
<div style="text-align: justify;">
Outside the loop n == s i.e. 6 == 6 is also true so the number 6 is perfect number. </div>
<div style="text-align: justify;">
<br /></div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<b>Tip: </b>To understand the program you can also take different values
of n and try the above process yourself. It will help you to understand
the process much clearly and helps in improving your debugging
ability. </div>
</blockquote>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-2860607449611741382014-09-01T21:18:00.000+05:302015-01-26T14:44:19.751+05:30Program for Reversing an Integer in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here's a C program to reverse an integer with output and proper explanation. This program uses while loop.</div>
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
long n, r, s = 0 ;
clrscr() ;
printf("Enter a number : ") ;
scanf("%ld", &n) ;
while(n > 0)
{
r = n % 10 ;
s = r + s * 10 ;
n = n / 10 ;
}
printf("\nThe reversed number is : %ld", s) ;
getch() ;
}
</pre>
<br />
<b>Output of above program</b><br />
<br />
Enter a number : 123<br />
The reversed number is : 321<br />
<br />
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Explanation of above program</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
This program takes a number and displays its reverse. Also this program uses variables of type <b>long</b>. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Note: </b>The long data type has a size of 4 bytes which is more than int data type's size of 2 bytes. So, the use of long data type enables the user to enter much bigger numbers.</blockquote>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here we have 3 variables all of the data type <b>long</b> - </div>
<ul style="text-align: justify;">
<li>n - is the number that user enters and whose reverse we're finding.</li>
<li>r - is used as a temporary variable to store the remainder (we'll see it's use in a minute).</li>
<li>s - is the reverse of n. It is initialized to 0 at the beginning of program.</li>
</ul>
<div style="text-align: justify;">
The reverse of the number is calculated inside the while loop. The while loop here has three statements inside it. Let's understand how while loop works here to determine the reverse of a number with the help of an example.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Suppose n = 123. The process of while loop for n = 123 is as follows -</div>
<ul style="text-align: justify;">
<li>First n > 0 i.e. 123 > 0 so the program enters the while loop.</li>
<li>Then we calculate modulo 10 of our number and store its value in r i.e. r = n % 10 = 123 % 10 = 3 (since we're calculating modulo 10, the result is simply the last digit of n).</li>
<li>Next we're calculating the value of s using the following expression -<b> s = r + s * 10</b>. Therefore using old values of r and s the new value of s is - s = 3 + 0 * 10 = 3.</li>
<li>And finally we divide n by 10 and storing its value again in n itself i.e. n = n / 10 = 123 / 10 = 12 (since the type of n is long int so the fractional part is dropped from the result).</li>
<li> Now that all statements inside the loop have been executed once the looping condition is again checked.</li>
<li>Again n > 0 i.e. 12 > 0 so the loop will execute again following all the steps mentioned above.</li>
<li>Then we calculate the value of r i.e. r = n % 10 = 12 % 10 = 2 (again the last digit of n).</li>
<li>The new value of s is s = r + s * 10 = 2 + 3*10 = 32.</li>
<li>Now we divide n by 10. Therefore, n = 12 / 10 = 1. </li>
<li>Again the looping condition is checked and the loop is executed one more time with n = 1 and s = 32. </li>
<li>Then we calculate the value of r i.e. r = n % 10 = 1 % 10 = 1 (again the last digit of n).</li>
<li>The new value of s is s = r + s * 10 = 1 + 32*10 = 321 (reverse of n).</li>
<li>Now we divide n by 10. Therefore, n = 1 / 10 = 0.</li>
<li>Now the looping condition becomes false and the loop terminates printing the final result.</li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Note</b>: If you’d notice the printf()
and scanf() in this example you’d see that I wrote %ld not %d. The
reason behind this is that we’re working with variables of data type
long (long int) not just int. So, while we use %d for int type, we’re
using %ld to print value of long (and in case of scanf to take long as
input) here.
</blockquote>
</div>
<br /></div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-45165745227127094192014-08-20T15:40:00.000+05:302015-01-26T14:42:43.419+05:30Program to Find the Sum of Fibonacci Series in C | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
Here’s a C program to find the sum of Fibonacci series with output and proper explanation. The program uses for loop.<br />
<br />
<a name='more'></a><br />
<blockquote class="tr_bq">
<b>What is Fibonacci Series?</b> By definition, the first two numbers in the Fibonacci sequence are 0 and
1, and each subsequent number is the sum of the previous two. e.g. <br />
<div style="text-align: center;">
<b>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
</b></div>
</blockquote>
<br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int a = -1, b = 1, c = 0, i, n, sum = 0 ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nThe fibonacci series is : \n\n") ;
for(i = 1 ; i <= n ; i++)
{
c = a + b ;
printf("%d \t", c) ;
sum = sum + c ;
a = b ;
b = c ;
}
printf("\n\nThe sum of the fibonacci series is : %d", sum) ;
getch() ;
}
</pre>
<br />
<br />
<b>Output of above program </b><br />
<br />
Enter the limit : 5<br />
<br />
The fibonacci series is :
0 1 1 2 3<br />
<br />
The sum of the fibonacci series is : 7<br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b> </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
This program first calculates the Fibonacci series up to a limit and then calculates the sum of numbers in that Fibonacci series. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The program has several variables -</div>
<ul style="text-align: justify;">
<li>a, b, c - These integer variables are used for the calculation of Fibonacci series. The values of a, b and c are initialized to -1, 1 and 0 respectively.</li>
<li> n - This integer is the limit determining the number of elements of Fibonacci series that should be calculated.</li>
<li>sum - It is the sum of elements of Fibonacci series.</li>
<li>i - This is the loop variable.</li>
</ul>
<div style="text-align: justify;">
First the user enters a limit. After that for loop takes the control and
calculates the sum of Fibonacci series up to the previously entered
limit. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
To understand the working of for loop in this program, let’s take an
example. Suppose the limit is 5 i.e. n = 5. So the for loop will
executes for i = 1 to 5. Let’s go through each step one by one. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Note</b>: The process mentioned below is the standard way to calculate
Fibonacci series so just remember the steps as is.</blockquote>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>
Process for i = 1</b></div>
<ul style="text-align: justify;">
<li><b></b>First we update the value of c (initially 0) with the following
expression -<b> c = a + b</b>. So after this c = -1 + 1 = 0 (first value of
Fibonacci series).</li>
<li>Then we print the value of c. Notice \t is used to provide 8 spaces (1
tab) between two values see in the output.</li>
<li>Then we update the value of variable sum as - sum = sum + c = 0 + 0 =
0.</li>
<li>At last we update the value of a as - <b>“a = b”</b> and then the value of b
as -<b> “b = c”</b>. So after this step a = 1 and b = 0. </li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Process for i = 2</b></div>
<ul style="text-align: justify;">
<li>We again update the value of c like before. So after this c = a + b = 1
+ 0 = 1 (second value of Fibonacci series).</li>
<li>Then we print the value of c.</li>
<li>Then we update the value of variable sum as - sum = sum + c = 0 + 1 =
1.</li>
<li>At last we update the value of a as - “a = b” and then the value of b
as - “b = c”. So after this step a = 0 and b = 1. </li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Process for i = 3</b></div>
<ul style="text-align: justify;">
<li>We again update the value of c like before. So after this c = a + b = 0
+ 1 = 1 (third value of Fibonacci series).</li>
<li>Then we print the value of c.</li>
<li>Then we update the value of variable sum as - sum = sum + c = 1 + 1 =
2.</li>
<li>At last we update the value of a as - “a = b” and then the value of b
as - “b = c”. So after this step a = 1 and b = 1. </li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Process for i = 4</b></div>
<ul style="text-align: justify;">
<li><b></b>We again update the value of c like before. So after this c = a + b = 1
+ 1 = 2 (fourth value of Fibonacci series).</li>
<li>Then we print the value of c.</li>
<li>Then we update the value of variable sum as - sum = sum + c = 2 + 2 =
4.</li>
<li> At last we update the value of a as - “a = b” and then the value of b
as - “b = c”. So after this step a = 1 and b = 2. </li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>Process for i = 5</b></div>
<ul style="text-align: justify;">
<li>We again update the value of c like before. So after this c = a + b = 1
+ 2 = 3 (third value of Fibonacci series).</li>
<li>Then we print the value of c.</li>
<li>Then we update the value of variable sum as - sum = sum + c = 4 + 3 =
7.</li>
<li>At last we update the value of a as - “a = b” and then the value of b
as - “b = c”. So after this step a = 2 and b = 3. </li>
</ul>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
This is how we calculate the Fibonacci series and sum of Fibonacci
series.
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Also look at: </b><a href="http://cprogramming.language-tutorial.com/2012/01/program-to-find-fibonacci-series-in-c-c.html">Program to Calculate Fibonacci Series only</a>.</blockquote>
</div>
<div style="text-align: justify;">
<blockquote class="tr_bq">
<b>Tip: </b>To understand the program you can also take different values
of n and try the above process yourself. It will help you to understand
the process much clearly and helps in improving your debugging
ability. </blockquote>
</div>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-53432252828970731532014-08-16T20:08:00.000+05:302015-01-26T14:41:55.585+05:30Program to Print all the Divisors of a Given Number | C Program<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here’s a C program to print all the divisors of a given number with output and proper explanation. This program uses for loop. </div>
<br />
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
int i, n ;
clrscr() ;
printf("Enter the number : ") ;
scanf("%d", &n) ;
printf("\nThe divisors are :\n\n") ;
for(i = 1 ; i <= n ; i++)
if(n % i == 0)
printf("%d\t", i) ;
getch() ;
}</pre>
<br />
<br />
<b>Output of above program</b><br />
<br />
Enter the number : 21<br />
<br />
The divisors are :
1 3 7 21<br />
<br />
<br />
<div style="text-align: justify;">
<b>Explanation of above program</b> </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The integer variable n is the number whose divisors are being calculated and i is the loop variable. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
First, we ask the user to enter a number. Inside the loop, we are checking if the number n is divisible by the current loop variable (i) i.e. if n % i == 0 then we print the value of i but if the number n is not divisible by the current loop variable then the loop will continue with other values until the loop is terminated. In this way all the divisors are calculated. </div>
<div style="text-align: justify;">
<br /></div>
<blockquote class="tr_bq">
<div style="text-align: justify;">
<b>Tip: </b>To understand the program you can also take different values
of n and try the above process yourself. It will help you to understand
the process much clearly and helps in improving your debugging
ability. </div>
</blockquote>
<blockquote class="tr_bq">
<b>Also look at: </b><a href="http://cprogramming.language-tutorial.com/2012/01/program-to-print-numbers-that-are.html">Program to Find out Multiples of a Given Number.</a></blockquote>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-25825264116527805002014-07-31T21:33:00.000+05:302015-01-26T14:24:38.661+05:30How to swap two numbers using three variables in C<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Here's a program to swap two numbers using three variables with explanation using C Programming language.<br />
<a name='more'></a><br />
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
<pre class="cpp" name="code">#include<stdio.h> //header file
#include<conio.h> //header file
void main() {
int firstnum, secnum, temp;
clrscr();
printf("Enter the first number");
scanf("%d",&firstnum);
printf("Enter the second number");
scanf("%d",&secnum);
printf("First Num is %d\nSecond num is %d, firstnum, secnum);
temp = firstnum;
firstnum = secnum;
secnum = temp;
printf("After Swapping...\nFirst Num is %d\nSecond num is %d, firstnum, secnum);
getch();
} </pre>
</div>
</div>
<br />
<b>Explanation of above program</b><br />
In the above code, first we included the header file then inside main we declared three variables - firstnum and secnum for storing the values of first and second number respectively and temp is for temporary storage (we'll get to that in a minute). Next we prompt the user to enter two numbers after which we are printing those numbers out for the user. After that we are doing the swap.<br />
<b><br /></b>
<b>How swapping is done?</b><br />
To swap here we use another variable named temp. First we are storing the value of firstnum in temp. Now in the next step we are overwriting firstnum with the value of secnum so that firstnum now holds the value of secnum (half swapping is done). Finally, we store the value of temp (currently holding value of firstnum) into secnum. This is how swapping is done using three variables.<br />
<br />
<b>To learn how to swap two numbers using just two variables</b><br />
<a href="http://cprogramming.language-tutorial.com/2011/12/how-to-swap-two-numbers-using-only-two.html">How to swap two numbers using only two variables</a></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8612108870928357610.post-54862823423725964982014-07-20T21:30:00.000+05:302015-01-26T14:24:13.439+05:30How to swap two numbers using only two variables in C<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;">
Here's a program to swap two numbers using only two variables with explanation using C Programming language.<br />
<a name='more'></a><br />
<br />
<div dir="ltr" style="text-align: left;">
<pre class="cpp" name="code">#include<stdio.h> //header file
#include<conio.h> //header file
void main() {
int firstnum, secnum;
clrscr();
printf("Enter the first number");
scanf("%d",&firstnum);
printf("Enter the second number");
scanf("%d",&secnum);
printf("First Num is %d\nSecond num is %d, firstnum, secnum);
firstnum= firstnum + secnum;
secnum= firstnum - secnum;
firstnum= firstnum - secnum;
printf("After Swapping...\nFirst Num is %d\nSecond num is %d, firstnum, secnum);
getch();
} </pre>
</div>
</div>
<br />
<b>Explanation of above program</b><br />
In
the above code, first we included the header file then inside main we
declared two variables - firstnum and secnum for storing the values of
first and second number respectively. Next we prompt the user to enter two
numbers after which we are printing those numbers out for the user.
After that we are doing the swap.<br />
<b><br />
</b><br />
<b>How swapping is done using just two variables?</b><br />
First we are storing the sum of both numbers in firstnum. Then we are subtracting the value of secnum from the new value of firstnum and by this now secnum holds the value of firstnum that user has entered (half swapping is done). Now we are again subtracting firstnum and new value of secnum and storing it in firstnum resulting in complete swapping. In this way the swapping is done using just two variables.<br />
<br />
<br />
<b>Lets understand with an example</b><br />
If you ain't able to understand the above program don't worry lets look at an example:<br />
<br />
<br />
Suppose, currently firstnum = 10 and secnum = 15. After performing the first step i.e.<br />
<br />
<pre class="cpp" name="code">firstnum= firstnum + secnum;</pre>
firstnum = 10 + 15 = 25. i.e. firstnum now has a value of 25. After second step i.e.<br />
<br />
<br />
<pre class="cpp" name="code">secnum= firstnum - secnum;</pre>
secnum = 25 - 15 = 10 i.e. secnum now has a value of 10 i.e. original value of firstnum. After performing the last step i.e.<br />
<br />
<pre class="cpp" name="code">firstnum= firstnum - secnum;</pre>
firstnum = 25 - 10 = 15 i.e. firstnum now has a value of 15 i.e. original value of secnum. Hence the numbers are finally swapped using just two numbers.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8612108870928357610.post-88383579195872460162014-07-04T19:26:00.000+05:302014-07-04T22:30:57.470+05:30Program to Perform Various String Operations on a Given String in C<div dir="ltr" style="text-align: left;" trbidi="on">
Here is a C program to perform different manipulations on a given string. This program encapsulates different operations provided by C language on a <a href="http://cprogramming.language-tutorial.com/search/label/Strings%20in%20C">String </a>e.g.<br />
<ul style="text-align: left;">
<li>finding length of a string</li>
<li>converting a string to uppercase or lowercase</li>
<li>reversing a string </li>
<li>concatenating of two strings</li>
<li>copy one string to another string</li>
</ul>
This program uses C concepts like <a href="http://cprogramming.language-tutorial.com/search/label/Arrays%20in%20C">Array</a>, <a href="http://cprogramming.language-tutorial.com/2012/11/what-is-gets-function-in-c-with-syntax.html">Gets Function</a> and <a href="http://cprogramming.language-tutorial.com/search/label/String%20Functions">String Functions</a> like <a href="http://cprogramming.language-tutorial.com/search/label/String%20Length%20strlen%28%29">string length (strlen())</a>, <a href="http://cprogramming.language-tutorial.com/search/label/String%20Copy%20strcpy%28%29">string copy (strcpy())</a>,strcat(), strrev(), strlwr() and strupr().<br />
<a name='more'></a><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
char str1[40], str2[40] ;
clrscr() ;
printf("Enter the first string : \n\n") ;
gets(str1) ;
printf("\nEnter the second string : \n\n") ;
gets(str2) ;
printf("\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Length is : %d and %d", strlen(str1), strlen(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Uppercase is : %s and %s", strupr(str1), strupr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Lowercase is : %s and %s", strlwr(str1), strlwr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Reverse is : %s and %s", strrev(str1), strrev(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- String copy is : %s ", strcpy(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Concatenation is : %s ", strcat(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
getch() ;
}
</pre>
<br />
<br />
<b>Output of above program</b><br />
<br />
Enter the first string :<br />
Football<br />
<br />
Enter the second string :<br />
Rocks!<br />
<br />
String 1 = Football & String 2 = Rocks! - Length is : 8 and 6<br />
String 1 = Football & String 2 = Rocks! - Uppercase is : FOOTBALL and ROCKS!<br />
String 1 = FOOTBALL & String 2 = ROCKS! - Lowercase is : football and rocks!<br />
String 1 = football & String 2 = rocks! - Reverse is : llabtoof and !skcor<br />
String 1 = llabtoof & String 2 = !skcor - String copy is : !skcor<br />
String 1= !skcor & String 2= !skcor - Concatenation is : !skcor!skcor<br />
String 1 = !skcor!skcor & String 2 = !skcor</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8612108870928357610.post-47131388513772939212014-05-23T13:03:00.000+05:302014-05-23T13:03:07.309+05:30Program to Concatenate the Given Two Strings in C<div dir="ltr" style="text-align: left;" trbidi="on">
Here is a C program to concatenate two strings using C function <i>strcon(function)</i>. This program uses C concepts like <a href="http://cprogramming.language-tutorial.com/search/label/For%20Loops">For Loop in C</a>, <a dir="ltr" href="http://cprogramming.language-tutorial.com/search/label/Auto%20Incrementing%20Operator%20%2B%2B">Auto Incrementing Operator ++</a> and <a href="http://cprogramming.language-tutorial.com/search/label/Auto%20Decrementing%20Operator%20--">Auto Decrementing Operator --</a>.<br />
<a name='more'></a><br /><br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
void main()
{
char str1[20], str2[20], strcon[40] ;
int i, j ;
clrscr() ;
printf("Enter the first string : ") ;
scanf("%s", str1) ;
printf("\nEnter the second string : ") ;
scanf("%s", str2) ;
for(i = 0 ; str1[i] != '\0' ; i++)
strcon[i] = str1[i] ;
i-- ;
for(j = 0 ; str2[j] != '\0' ; j++)
strcon[i+j+1] = str2[j] ;
strcon[i+j+1] = '\0' ;
printf("\nThe concatenation string is : %s", strcon) ;
getch() ;
}
</pre>
<br />
<br />
<b>Output of above program</b><br />
<br />
Enter the first string : Awesome<br />Enter the second string : Weather<br />The concatenation string is : AwesomeWeather<br />
<br />
<blockquote class="tr_bq">
<i><b>Take a Look at</b>: <a href="http://cprogramming.language-tutorial.com/search/label/Strings%20in%20C">Examples of different operations on Strings</a></i></blockquote>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-39019086294159136362014-05-23T12:48:00.000+05:302014-05-23T12:48:58.699+05:30Program to Count Vowels, Consonants, Digits, Specials and Words in a String in C<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Here is a C program for Counting vowels, consonants, digits, special characters & words in a given string. This program uses C concepts like <a href="http://cprogramming.language-tutorial.com/search/label/While%20Loop">While Loop</a>, <a href="http://cprogramming.language-tutorial.com/search/label/Strings%20in%20C">Strings in C</a>, <a href="http://cprogramming.language-tutorial.com/2012/11/what-is-gets-function-in-c-with-syntax.html">Gets Function</a>. This program also uses <span class="post-labels"><a href="http://cprogramming.language-tutorial.com/search/label/CTYPE.H%20Header%20File%20in%20C" rel="tag">CTYPE.H Header File in C</a>.</span></div>
<a name='more'></a><br />
<br />
<pre class="cpp" name="code"># include <stdio.h>
# include <conio.h>
# include <ctype.h>
void main()
{
char text[80], ch ;
int vowel = 0, cons = 0, digit = 0, word = 0, special = 0, i = 0;
clrscr() ;
printf("Enter the text : ") ;
gets(text) ;
while((ch = tolower(text[i++])) != '\0')
{
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
++vowel ;
else if(ch >= 'a' && ch <= 'z')
++cons ;
else if(ch >= '0' && ch <= '9')
++digit ;
else if(ch == ' ')
++word ;
else
++special ;
}
++ word ;
printf("\nThe text contains : ") ;
printf("\n\nNumber of vowels = %d", vowel) ;
printf("\n\nNumber of consonants = %d", cons) ;
printf("\n\nNumber of digits = %d", digit) ;
printf("\n\nNumber of special characters = %d", special) ;
printf("\n\nNumber of words = %d", word) ;
getch() ;
}
</pre>
<b> </b> <b> </b><br />
<br />
<b>Output of above program</b><br />
<br />
Enter the text : Tanmay was born on 22nd Oct 1989 !!!<br />
The text contains :<br />
Number of vowels = 6<br />
Number of consonants = 14<br />
Number of digits = 6<br />
Number of special characters = 3<br />
Number of words = 8 </div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8612108870928357610.post-66291632612808556182014-05-23T12:41:00.000+05:302014-05-23T12:44:41.254+05:30What is CTYPE.H Header in C Programming Language?<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
Overview of CTYPE.H header in C Language</h3>
<div style="text-align: left;">
This header declares a set of functions which deals with individual characters of a <a href="http://cprogramming.language-tutorial.com/search/label/Strings%20in%20C">String</a>. The functions could be used to either classify characters e.g. whether a character is alphanumeric, blank, space or a control character or it could be used to perform some transformation on individual characters e.g. change a character to upper/lower case.<br />
<a name='more'></a></div>
<div style="text-align: left;">
</div>
<h3 style="text-align: left;">
Functions available in CTYPE.H header in C Language</h3>
<div style="text-align: left;">
All functions in CTYPE.H take the <tt>int</tt> equivalent of one character as parameter and return an <tt>int</tt> that can either be another character or a value representing a Boolean value: an <tt>int</tt> value of <tt>0</tt> means false, and an <tt>int</tt> value different from <tt>0</tt> represents true.</div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Now let's take a look at some functions available in CTYPE.H. </div>
<h4 style="text-align: left;">
Classification Functions in CTYPE.H Header in C Language</h4>
<ul style="text-align: left;">
<li>isalnum - Check if character is alphanumeric (function )</li>
<li>isalpha - Check if character is alphabetic (function )</li>
<li>isblank - Check if character is blank (function )</li>
<li>iscntrl - Check if character is a control character (function )</li>
<li>isdigit - Check if character is decimal digit (function )</li>
<li>isgraph - Check if character has graphical representation (function )</li>
<li>islower - Check if character is lowercase letter (function )</li>
<li>isprint - Check if character is printable (function )</li>
<li>ispunct - Check if character is a punctuation character (function )</li>
<li>isspace - Check if character is a white-space (function )</li>
<li>isupper - Check if character is uppercase letter (function )</li>
<li>isxdigit - Check if character is hexadecimal digit (function )</li>
</ul>
<h4 style="text-align: left;">
Character Transformation/Conversion Functions in CTYPE.H Header in C Language</h4>
<ul style="text-align: left;">
<li>tolower - Convert uppercase letter to lowercase (function )</li>
<li>toupper - Convert lowercase letter to uppercase (function ) </li>
</ul>
<br />
<blockquote class="tr_bq">
<i><b>Take a look at</b>: <a href="http://cprogramming.language-tutorial.com/search/label/CTYPE.H%20Header%20File%20in%20C">Programs using CTYPE.H Header in C.</a></i></blockquote>
</div>
Unknownnoreply@blogger.com0