Archive

Posts Tagged ‘c++ program’

Calender Program in C

October 9th, 2011 No comments

Found this question on a C Programming Fan Page on Facebook. Decided to give it a shot.

Problem Statement : Write A Program that receives the month and year from the keyword as integers & prints the calendar in the following format.

Input : Month, Year

Output:
Mon Tue Wed Thu Fri Sat Sun
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31


Adding a link to the first executable. Will post the source code soon - needs some big time improvement.

Note - It doesn't work for certain leap years. Will fix it and update soon.

Download - calender.exe

ASCII Values & Table Generator in C

August 1st, 2011 2 comments

What are ASCII values? Why are they needed?
We are all aware of the fact that all computers understand is 0 & 1 - and everything else is stored as patterns containing 0's and 1's. Some of us also know that numbers like 25, 12, etc can be represented as patterns of 0's & 1's. The computer interprets 25 as 11001 and 12 as 1100.  But how does it interpret a  sentence like "My name is K" or a word like "name" or a letter like "K"? Also, how does it know the difference between 'k' & 'K'?

This is where ASCII values come in. Each character (including a space) has a certain corresponding number associated to it. And there are different numbers assigned to the lower and upper case of the same alphabet.  For instance, the letter 'a' corresponds to the number 97 while 'A' corresponds to the number 65.

An ASCII table maps the characters to the numbers. Apart from the equivalent decimal representation, it also gives the hexadecimal and octal representations of the character.

This is what the ASCII table looks like -

ascii value table

Here's a little tool that can help you experiment with ASCII values.

What's it got to do with programming?

Now, the more important question. What has your programming got to do with ASCII values?
To begin with, have a look at the following C code -

main()
{
char c;
printf("Enter any character\n");
scanf("%c", &c); /*scans a character */
printf("%d", c); /* prints a decimal */
getch();
}

It scans a character and returns an integer. Do you think the code is incorrect? Try compiling it. It does return a number for every character. And what is this number? Exactly, the decimal ASCII value of the character. Don't believe me? That's what the table is for.

Note that %d is responsible for giving us the corresponding decimal value from the ASCII table. We could similarly use %x to hexadecimal and %o for octal values corresponding to the character.

Now, we could try doing it the other way round. Input a number and get the corresponding character, that is.

main()
{
int d;
printf("Enter any number\n");
scanf("%d", &d); /* scans a decimal */
printf("%c", d); /* prints a character */
getch();
}

That's not it. We may even generate the complete column for a character from the ASCII table. All we need to do is print the dec, hex and oct equivalents for the input character.

main()
{
char c;
printf("Enter any character\n");
scanf("%c", &c); /*scans a character */
printf("%d\t", c); /* prints dec */
printf("%x\t", c); /* prints hex */
printf("%o", c); /* prints oct */
getch();
}

Now, we can easily use a loop to generate the complete ASCII table. The above table ends at the dec value 127. However, the extended ASCII table is defined to the decimal value 255(ie - it has 256 values). See this link for the extended ASCII table.

#include <stdio.h>
#include <conio.h>
/* program to generate the complete ASCII table */
main()
{
int x;
for(x=1;x<=255;x++)
{
printf("\n%c\t", x); /* prints char */
printf("%d\t", x); /* prints dec */
printf("%x\t", x); /* prints hex */
printf("%o", x); /* prints oct */
}
getch();
}

You can now try experimenting with ASCII values, decimal, hex, octal and characters. Good Luck!
{Btw, Just to let you know - ASCII stands for American Standard Code for Information Interchange}

 

Logic to Find Exponents with Integral Powers

July 22nd, 2011 No comments

If you've noticed, In C Programming, you cannot use a^b directly to find the value of an exponent. Although, there is a pow(a, b) function that gives you the result. But, it's always nice to work with the basic logic.

If you look at the definition of an exponential:

"Exponentiation is a mathematical operation, written as a^n. When n is a positive integer, exponentiation corresponds to repeated multiplication." - Wikipedia

We're gonna work out our logic using this very basic definition [especially the part where it says - exponentiation corresponds to repeated multiplication ;)]

Code:

main()
{
int base, index;
printf("Enter the base\n"); /* say, 2 */
scanf("%d", &base);
printf("Enter the index\n"); /* say, 3 */
scanf("%d", &index);

/* always remember that 2^3 is actually 2x2x2 ie-2 multiplied by itself 3 times */

int i;
int power=base; /* power is initiallized to 2 */
for(i=1;i<index;i++)
{
power=power*base; /* 1st loop : power = 2*2, 2nd loop : power =(2*2)*2 */
}

printf("\n%d", power);
getch();
}

It's pretty easy to understand using an example. Refer to the example in comments to see how the code works. Also, this is not the only way. Think of how you could achieve the same with a different (and perhaps, better) code.

Basic Quiz Program in C

July 21st, 2011 No comments

This is a program for a simple quiz on the C Programming Language. It can be modified to be made into a quiz on any topic. It includes negative marking for wrong answers, keeps track of the score & displays it at the end of the quiz.

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

main()
{
int score=0;
int answer;

printf("Welcome to the C quiz\nThe quiz has 5 very basic questions on the C Programming Language. You get +3 for each correct answer & -1 for each wrong/invalid answer.\n");

printf("\nQ1) Why is it called 'C' & not 'D'?\n");
printf("[1]C stands for code\t[2]The inventor's name started with a C\n[3]It developed after a language called 'B'\t[4]Why should I care?\n");
scanf("%d", &answer);

if(answer==3)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("\nQ) It was developed at?\n");
printf("[1]IBMt[2]Bell Labsn[3]MITt[4]Microsoft(?)\n");
scanf("%d", &answer);

if(answer==2)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("nQ) Which of these is not a C keyword as per ANSI C ?\n");
printf("[1]externt[2]volatilen[3]entert[4]break\n");
scanf("%d", &answer);

if(answer==3)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("nQ) What is ANSI, btw? ?\n");
printf("[1]Area of Natural and Scientific Interest\t[2]American National Standards Institute\n[3]American National Standardization Institute\t[4]American National Society Of Intellectuals\n");
scanf("%d", &answer);

if(answer==2)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("\nQ)Which of these concepts is NOT supported by C ?\n");
printf("[1]Pointers\t[2]Functions\n[3]Strings\t[4]Namespaces\n");
scanf("%d", &answer);

if(answer==4)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("\nThank You for taking the Quiz.\n Your Total Score is %d out of 15", score);

getch();

}

Download the Application (.exe)

Personal Fitness & Weight Analyzer in C

July 20th, 2011 No comments

This C Program Analyzes if you're underweight, overweight or obese and accordingly suggests you to gain or lose the right amount of weight in the right period of time.

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

main()
{
int weight;

printf("Welcome to your Weight Analyser\n");
printf("To begin, Enter your current weight in pounds(lbs)\n\n");
scanf("%d", &weight);

printf("You currently have %d calories inside you.. In other words, If you lose %d calories, you'll dissapear altogether ;) Just Sayin!\n\n", weight*(3500), weight*(3500));

int height_ft, height_in;

printf("Now, to calculate your ideal weight, Enter your height.. How many feet?)n");
scanf("%d", &height_ft);
printf("And inches?nn");
scanf("%d", &height_in);

int bmi=(703*weight)/pow(((height_ft)*12+(height_in)),(2));

if(bmi<18.5)
{
printf("You're underweight, You need to gain weight.. How does that feel?\n");
}

else if(18.5<bmi && bmi<25)
{
printf("You don really need to lose any weight, Your height and weight are in proportion! :)\n");
}

else
{
if(25<bmi && bmi<30)
{
printf("You're overweight! :) Let's see what I can do you make you live longer and happier :).. \n\n");
}
else
{
printf("How do you even breathe? You're obese and sick! But I can help.\n\n");
}

int ideal_weight=(24.9/703)*(pow(((height_ft)*12+(height_in)),(2)));

printf("Considering your height will not increase anymore, For your ideal weight, You should reduce to %d \n\n", ideal_weight);
printf("Which means you'll need to shed %d pounds\n\n", weight-ideal_weight);
printf("For healthy weight loss, you should take %d days to do this by losing 500 calories each day\n\n", 7*(weight-ideal_weight));
printf("To do this, make sure that the calories you burn everyday are 500 more than the total calories you take in everyday.\n Good Luck \n");

}
getch();

}

Download the Application (.exe)

Arithmetic Progression Generator in C

July 20th, 2011 No comments

This application generates an AP series using a while loop by specifying the first term, common difference and the number of terms.

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

int main(void)
{
int repeat=1;

while(repeat==1)
{

int a, d, n;
printf("Enter first term\n");
scanf("%d", &a);
printf("Enter the common difference\n");
scanf("%d", &d);
printf("Enter number of terms\n");
scanf("%d", &n);

while(n>0)
{
printf("%dt", a);
a=a+d;
n=n-1;
}

printf("\n\nRepeat[1]\nExit[0\]n");
scanf("%d", &repeat);
}
getch();
}

Download the Application (.exe)

Basic Menu-Based Calculator in C

July 20th, 2011 No comments

Here's the code for a Basic Calculator Using Switch Statements:

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

int main(void)
{
int a, b;
int repeat=1;
printf("Welcome to the C calculator\nEnter any two numbers\n");
scanf("%d%d", &a, &b);

while(repeat==1)
{
int choice;
printf("Choose the operation to be performed\nDivision[1]\nMultiplication[2]\nAddition[3]\nSubtraction[4]\n");
scanf("%d", &choice);

int result;
switch(choice)
{
case 1:
result = a/b;
printf("The quotient is %d", result);
break;
case 2:
result = a*b;
printf("The product is %d", result);
break;
case 3:
result = a+b;
printf("The sum is %d", result);
break;
case 4:
result = a-b;
printf("The difference is %d", result);
break;
default:
printf("Please enter a valid choice");
break;
}
printf("\nRepeat[1]\nExit[0]n");
scanf("%d", &repeat);
}
getch();
}

Download the Application (.exe)

[C Tutorial 6] Performing Operations on the Input

July 4th, 2011 No comments

Once we get the input(s) from the user [Tutorial 5], it is time to modify the input by performing operations on it. The basic idea of coding is to design systems which perform various functions. And a function is nothing but a machine that gives output values for various input values.

Since our basic aim is to implement functions, we need to perform operations on the inputs to get outputs. Now, suppose you had to code a basic machine that adds 5 to the input.

function

You will need to:

Step 1 : Get an input value from the user

Step 2 : Add 5 to the input

Step 3 : Display output to the user

Method 1 -

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

int main()
{
int x;
printf("Enter any number\n"); /* Step 1 */
scanf("%d", &x);

int y;
y=x+5; /* Step 2 */
printf("The output is %d", y); /* Step 3 */
getch();
return 0;
}

In the above method, we have used two variables. x for the input and y for the output. However, we can add 5 to change the input itself and display it as the output (this is the power of programming, the otherwise constant inputs are variables in a program)

Method 2 -

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

int main()
{
int x;
printf("Enter any number\n"); /* Step 1 */
scanf("%d", &x);

x=x+5; /* Step 2 */
printf("The output is %d", x); /* Step 3 */
getch();
return 0;
}

Now, don't get confused when you see x=x+5; Just remember the following thumb rule :

In programming, the value on the right hand side(called the rvalue replaces the value on the left hand side(called the lvalue). In this case, (x+5) replaces x. hence, the new value of x is (x+5).

For a more elegant code, we could perform the addition in the printf function itself.

Method 3 -

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

int main()
{
int x;
printf("Enter any number\n"); /* Step 1 */
scanf("%d", &x);

printf("The output is %d", x+5); /* Steps 2 & 3 */
getch();
return 0;
}

In this case, the steps 2 and 3 can be implemented in a single line. As you will realize later, this is what programming is all about. A lot of people can program, but only a few can come up with the most elegant solution. And the most elegant one wins.

Note - in the above program, we did not have to define the "+" operator. It is one of the pre-defined C operators. C has a number of mathematical, logical and other operators. (discussed later)

[C Tutorial 5] Taking Input From User

July 2nd, 2011 No comments

/* how to take input data from the user - so we can later perform operations on it */

Just like printf is used to display output, scanf is its counterpart used to take input from the user. Assume that we need a number as input from the user(you're gonna need them in almost every program you make). We first need to define a variable that will hold the value of this number. A C variable is used to hold a value - it will store the value we take from the user.

So, there are essentially three steps we need to program this :

Step 1 - declare a variable to store value that the user will enter
Syntax - int a; declares a variable called a(you can call it anything) of the integer type.

Step 2 - ask the user to enter a value
Syntax - using printf

Step 3 - take the value and store it in the variable
Syntax - scanf("%d", &a);
%d stands for "take the value" and &a stands for "store it the variable called a".

The Program :

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

int main()
{
int a; /* Step 1 */
printf("Enter any number\n"); /* Step 2 */
scanf("%d", &a); /* Step 3 */
getch();
return 0;
}

Now, just to check it the program does what it's supposed to do. Let's display the value of a as the output. We just need to add another printf function to the above code :

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

int main()
{
int a; /* Step 1 */
printf("Enter any number\n"); /* Step 2 */
scanf("%d", &a); /* Step 3 */

printf("The value you entered was %d", a); /* displays the value of a */

getch();
return 0;
}

[C Tutorial 4] More on Displaying Output Text

July 2nd, 2011 No comments

/* this tutorial teaches how to move to a new line while printing text to output */

As we've seen in the previous tutorial, the printf function is used to display something as the output. Now, suppose we need to display the following :

Hello Sweety!
How are you?

We now need our program to go to the next line after printing Hello Sweety! Writing two different printf's won't work. A special keyword "n" (without the inverts) is used to do this. Printf takes n as an instruction to move to the next line.

The Program:

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

int main()
{
printf("Hello Sweety!\nHow are you?");
getch();
return 0;
}

Also, to leave a line between the two statements, i would add nn. Now look at the following images to see how the n works.
The first image is the same program written above. In the second image, we move to the next line after printing How are you?

same_line