Showing posts with label Assignments. Show all posts
Showing posts with label Assignments. Show all posts

Wednesday, May 19, 2010

How to use <conio.h> with GCC

This article will teach you how to use <conio.h> header file while programming in C under linux environment with GCC, and getting unbuffered input from the user.

Most of the students are taught C/C++ with Turbo C/C++ IDE in schools. Turbo C has a header file(unspecified in ANSI standard) <conio.h> with which programmer can program for unbuffered input using functions like getch(). Also there are other functions like gotoxy() etc. which work perfect in DOS environment with Turbo C.
After they learn about linux, and then GCC they start practicing in linux. If you are such an student, read on. This will be handy for you.
At some point of time you will write a program in which you want interactive user input from the user. Interactive in the sense that you want an action to be performed as soon as a key is pressed. But since standard library function getchar() buffers the input until ENTER key is pressed, it will be quite irritating for you. So, you'll miss your <conio.h> header file that you used in Turbo. Don't worry. I faced the same problem and I ran around like everything to find a soluion. And finally, I found a solution!!!

Solution
Just download the libconioh from this link
Install it. Here are the steps(I'm considering Ubuntu as the example):
1. Copy the downloaded archive to your home folder
2. Open the terminal, by pressing Alt+F2 and typing xterm and pressing enter.
3. Become root by typing
sudo -s
and supplying your password.
4. Type

tar -zxvf libconio-1.0.0.tar.gz
and press enter to extract the archive. To make the typing easy you may press the <tab> key on your keyboard after typing l of libconio-1.0.0.tar.gz for autocompletion of filename.
5. Now enter into the extracted directory by typing
cd libconio-1.0.0
and pressing enter.
6. Install the library by typing these commands one after another's execution.
./configure

make

make install 
 Now the library has been installed. How to use it for programming?
Just #include <conio.h> in your program. And when compiling your program(eg. myprogram.c in current working directory) using gcc give the library's detail to the linker like this:
gcc myprogram.c -lconio
You will get the a.out file if your program doesn't have any errors.
Execute it and enjoy!
./a.out
But what did that -lconio did? See, in gcc the source files and object library files can be linked by specifying them back to back. Like:
gcc file1.c file2.c lib1.a lib2.a
In linux the library files are with .a extension and they are stored in /usr/lib/ directory with the name format lib<library_name>.a . So when you installed libconioh it copied a file, named libconio.la to the /usr/lib directory. Now you can compile and link your program that uses conio.h by this command
gcc myprogram.c /usr/lib/libconio.a
The -l switch has been provided as a shortcut for your convenience. This -l makes conio to be read as /usr/lib/libconio.a hence when yo typed gcc myprogram.c -lconio it was interpreted as gcc myprogram.c /usr/lib/libconio.a . Now thats sweet! Isn't it?
   
Here is a sample program that reads characters from the keyboard, displays the character just next to it(for example, if u enter b it will display c)  and exits only when you press the small a key.

#include <conio.h>
int main(){
char c;
while((c=getch())!='a'){
putchar(c+1);
}
putchar('\n');
return 0;

Sunday, May 16, 2010

Implementing a list data structure using an array, in C


Long time since I interacted with C. I thought IIIT-A interviews are coming closer and they also have a coding test in which they ask to write programs, so I went off to revise data structures with C. I planned to study lists, linked lists, stacks, queues, trees and graphs and implement them all using C.
The first one on the target was lists. So I started off and wrote a lists demo program. I'm posting the program below. It may come handy to you if you are a student searching something for your assignment.
Compile it in GCC. You may also compile on Windoze but I haven't tested on Windoze.
The program allows to:
  1. Print all the values stored
  2. Insert a new value at specified position
  3. Insert a value at the end of the list(append)
  4. Delete a value at specified position
  5. Delete all occurences of a value from the list
  6. Find all occurences of an item
  7. Empty the list
I've also made the text colourful using the escape sequences for colours. Those \33[31m things are for colouring the text displayed while executing the program.

Here's the program.


#include <stdio.h>
#define SIZE 65536
#define ENDMARKER -65535

int data[SIZE];

int print_all();
int add(int pos, int datum);
int delete(int pos);
int append(int datum);
int delall(int datum);
int find(int datum);
int print(int pos);
int empty();

int main(){
int pos, datum;
int option;
data[0]=ENDMARKER;
printf("\n\33[36mWelcome to the list data structure demonstration program! The program starts with a list of integers(initially empty). Through this program's interface, you can insert items into the list at desired positions, or at the end; delete an item from the list from an specific position, or all occurences of an item from the list; find the position(s) of an item in the list; view all the items of the list; view an item stored at a particular position; or you may also empty the list.\n");
while(option!='9'){
printf("\n\33[32mMenu\n----\n");
printf("1. View all the items");
printf("\n2. Add an item at a given position");
printf("\n3. Add an item at the end of the list");
printf("\n4. Delete an item at a given position");
printf("\n5. Delete all occurences of an item value");
printf("\n6. Print an item at the given position");
printf("\n7. Find all the occurances of an item");
printf("\n8. Empty the list.");
printf("\n9. Exit\nEnter your choice and hit the enter key:");
scanf("%d",&option);
switch(option){
case 1:
print_all();
break;
case 2:
printf("\n\33[33mPlease enter the position where item should be inserted: ");
scanf("%d",&pos);
printf("Please enter the item value to be inserted: ");
scanf("%d",&datum);
add(pos, datum);
break;
case 3:
printf("\n\33[33mPlease enter the item value to be inserted at the end of the list: ");
scanf("%d",&datum);
append(datum);
break;

case 4:
printf("\n\33[33mPlease enter the position of the item to be deleted: ");
scanf("%d",&pos);
delete(pos);
break;
case 5:
printf("\n\33[33mPlease enter the item to be deleted from the list: ");
scanf("%d",&datum);
delall(datum);
break;
case 6:
printf("\n\33[33mPlease enter the position of the item whose value is to be printed: ");
scanf("%d",&pos);
print(pos);
break;
case 7:
printf("\n\33[33mPlease enter the item value whose position is to be found: ");
scanf("%d",&datum);
find(datum);
break;
case 8:
empty();
break;
case 9:
printf("\n\33[34mThank you for using this program. Have a nice time!\n\33[37m");
return(1);
break;
default:
printf("\n\33[31mInvalid use. Please retry.\n");
break;
}
}
printf("\33[37m");
return (0);
}

int num_items(){
int num=0;
int i;
for(i=0;data[i]!=ENDMARKER;i++);
return i;
}

int print_all(){
if(data[0]==ENDMARKER){
printf("\n\33[31mNo items could be found in the list.\nYou may insert some data first, before experimenting.\n");
return 0;
}
printf("\nFollowing items were found in the list:\n\n");
printf("\33[35mPosition\tItem\n");
printf("--------\t----\n");
int i;
for(i=0;data[i]!=ENDMARKER;i++){
printf("%8d\t%4d\n",i,data[i]);
}
printf("\n");
return 1;
}

int add(int pos, int datum){
if((pos>num_items()) || pos<0){
printf("\n\33[31mYou can't enter an item at this location because the list is full upto %d position. You can enter items from 0th position upto %dth position.\n",num_items(),num_items());
return (0);
}
data[num_items()+1]=ENDMARKER;
int i;
for(i=num_items();i>=pos;i--){
data[i]=data[i-1];
}
data[pos]=datum;
printf("\nThe item %d has been successfully inserted at the position %d.\nThe modified list is as follows.\n\n",datum,pos);
printf("\33[35mPosition\tItem\n");
printf("--------\t----\n");
for(i=0;data[i]!=ENDMARKER;i++){
printf("%8d\t%4d\n",i,data[i]);
}
printf("\n");
return 1;
}

int append(int datum){
data[num_items()+1]=ENDMARKER;
data[num_items()]=datum;
printf("\nThe item %d has been successfully appended to the list.\n The modified list is as follows.\n\n",datum);
printf("\33[35mPosition\tItem\n");
printf("--------\t----\n");
int i;
for(i=0;data[i]!=ENDMARKER;i++){
printf("%8d\t%4d\n",i,data[i]);
}
printf("\n");
return 1;
}

int delete(int pos){
if((pos>num_items()) || pos<0){
printf("\n\33[31mThat location doesn't hold any data value. Please enter a location that contains a value. Locations from 0 up to %d hold data values.\n",num_items());
return (0);
}
if(num_items()==0){
printf("\n\33[31mThe list is empty. No deletion possible.\n");
return 0;
}
int i;
for(i=pos;i<=num_items();i++){
data[i]=data[i+1];
}
data[num_items()]=ENDMARKER;
printf("\nThe item stored at the position %d has been successfully deleted.\n The modified list is as follows.\n\n",pos);
printf("\33[35mPosition\tItem\n");
printf("--------\t----\n");
for(i=0;data[i]!=ENDMARKER;i++){
printf("%8d\t%4d\n",i,data[i]);
}
printf("\n");
return 1;
}

int delall(int datum){
int i;
if(num_items()==0){
printf("\n\33[31mThe list is empty. No deletion possible.\n");
return 0;
}
int found=0;
for(i=0;i<=num_items();i++){
if(data[i]==datum){
found=1;
break;
}
}
if(found==0){
printf("\n\33[31mThe requested item wasn't found in the list. Deletion not possible.\n");
return (0);
}
for(i=0;data[i]!=ENDMARKER;i++){
if(data[i]==datum){
int j;
for(j=i;data[j+1]!=ENDMARKER;j++){
data[j]=data[j+1];
}
data[j]=ENDMARKER;
i--;
}
}
printf("\nAll the occurences of %d have been deleted from the list. The modified list is as follows:\n\n",datum); 
printf("\33[35mPosition\tItem\n");
printf("--------\t----\n");
for(i=0;data[i]!=ENDMARKER;i++){
printf("%8d\t%4d\n",i,data[i]);
}
printf("\n");
return 1;
}

int find(int datum){
int i;
if(num_items()==0){
printf("\n\33[31mThe list is empty.\n");
return 0;
}
int found=0;
for(i=0;i<=num_items();i++){
if(data[i]==datum){
found=1;
break;
}
}
if(found==0){
printf("\n\33[31mThe requested item wasn't found in the list.\n");
return (0);
}
printf("\n\33[35mPosition\tItem\n");
printf("--------\t----\n");
for(i=0;i<=num_items();i++){
if(data[i]==datum)printf("%8d\t%4d\n",i,data[i]);
}
return 1;
}

int print(int pos){
if(num_items()==0){
printf("\n\33[31mThe list is empty.\n");
return 0;
}
if(pos<0 || pos>=num_items()){
printf("\n\33[31mThats an invalid location.\n");
return 0;
}
printf("\n\33[35mPosition\tItem\n");
printf("--------\t----\n");
printf("%8d\t%4d\n",pos,data[pos]);
return 1;
}

int empty(){
if(num_items()==0){
printf("\n\33[31mThe list is already empty.\n");
return 0;
}
data[0]=ENDMARKER;
printf("\nThe list has been successfully emptied.\n");
return 1;
}

Sunday, April 18, 2010

My own chat application in C!!!!

After an standing-out(not outstanding :P) performance in GATE 2010 and missing the prestigious 99th percentile with just one question, I have to console myself for my shattered dream of being an IITian. I am looking for Tier-2 colleges now(I call IITs as tier-1 and NITs and IIITs as tier-2). I got an interview call from IIIT-B to be held on May 5th. In their interview a candidate has to present a technical talk of 5-10 minutes on any technical topic of his/her choice. He/She is then fired questions from the same topic by the selection committee. I have decided to speak on the topic "SOCKET COMMUNICATION". While the preparation I thought I should have an inside view of how it works by developing an application using it. After lots of research on the internet and many trial and errors I finally coded this crude chat application in C. You may also use it in your assignment if you're a student in search for stuff to do your assignments.

Note:
When one user is typing the message, the second one should not write anything :P i.e. it works similar to a walkie talkie.


Usage:
1. Compile the code into an object file and link the object file with wsock32.lib to generate the executable. I designed it and compiled it with Digital Mars Compiler & Linker You may use any compiler but you may need to modify the code a bit, based on your compiler.

To compile and link on dmc(that stands for Digital Mars Compiler) use these commands:
dmc -c chat.c
dmc chat.o wsock32.lib

2. You can test this app on two PCs/Laptops on LAN/WLAN. Launch it through command line on one computer. On the second launch it with the ip address of first computer as the command line argument.
For example(assuming it is placed in D:\'s root with the name chat.exe)
On first computer:
1. Window Key+R
2. Type cmd and press enter
3. Type d:\chat and press enter

On second computer:
1. Window Key+R
2. Type cmd and press enter
3. Type d:\chat <ip_of_first_comp.> like d:\chat 192.168.0.1



Download the executable here

Here is the source code:


#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>

#define MAXPENDING 1 /* Maximum outstanding connection requests */

void DieWithError(char *errorMessage); /* Error handling function */

void main(int argc, char *argv[])
{
short runtype; /* 0 for client, 1 for server*/
int serv_sock; /* Socket descriptor for server */
int clnt_sock; /* Socket descriptor for client */
struct sockaddr_in serv_addr; /* Server address */
struct sockaddr_in clnt_addr; /* Client address */
unsigned short port=9797; /* Port for communication */
unsigned int clnt_len; /* Length of client address data structure */
char msg[1024]; /* For chat message */
int msg_len;
int bytes; /* Byte count for received data */
WSADATA wsaData; /* Structure for WinSock setup communication */


switch(argc){
case 1:
runtype=0;
break;
case 2:
runtype=1;
break;
default:
printf("Invalid use of application. Usage: %s [<ip_addr>]",argv[0]);
exit(1);
break;
}

if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) /* Load Winsock 2.0 DLL */
{
fprintf(stderr, "WSAStartup() failed");
exit(1);
}


if (runtype==0){
/* Create socket for incoming connections */
if ((serv_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");

/* Construct local address structure */
memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */
serv_addr.sin_family = AF_INET; /* Internet address family */
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
serv_addr.sin_port = htons(port); /* Port */

/* Bind to the local address */
if (bind(serv_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
DieWithError("bind() failed");

/* Mark the socket so it will listen for incoming connections */
if (listen(serv_sock, MAXPENDING) < 0)
DieWithError("listen() failed");

/* Set the size of the in-out parameter */
clnt_len = sizeof(clnt_addr);
/* Wait for a client to connect */
printf("Waiting for a user to connect...\n");
if ((clnt_sock = accept(serv_sock, (struct sockaddr *) &clnt_addr, (int *)&clnt_len)) < 0)
DieWithError("accept() failed");
printf("Connected to %s. Type message and press enter to send. Ctrl+C to terminate.\n\n", inet_ntoa(clnt_addr.sin_addr));
while(1){
/* Receive message from client */
if ((bytes = recv(clnt_sock, msg, 1024, 0)) < 0)
DieWithError("recv() failed");
/*Put a null terminator at the last byte*/
msg[bytes]='\0';
printf("%s says: %s\n",inet_ntoa(clnt_addr.sin_addr),msg);
printf("You say: ");
gets(msg);
msg_len=strlen(msg);
if (send(clnt_sock, msg, msg_len, 0) != msg_len)
DieWithError("send() failed");
}
}
else if(runtype==1){
char *serv_ip;
serv_ip=argv[1];
/* Create a reliable, stream socket using TCP */
if ((clnt_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* Construct the server address structure */
memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */
serv_addr.sin_family = AF_INET; /* Internet address family */
serv_addr.sin_addr.s_addr = inet_addr(serv_ip); /* Server IP address */
serv_addr.sin_port = htons(port); /* Server port */
/* Establish the connection to the chat server */
if (connect(clnt_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
DieWithError("connect() failed");
printf("Connected to %s. Type your message and press enter to send. Ctrl+C to terminate.\n\n",argv[1]);

while(1){
printf("You say: ");
gets(msg);
msg_len = strlen(msg); /* Determine input length */
/* Send the string, including the null terminator, to the server */
if (send(clnt_sock, msg, msg_len, 0) != msg_len)
DieWithError("send() sent a different number of bytes than expected");
if ((bytes = recv(clnt_sock, msg, 1024, 0)) <= 0)
DieWithError("recv() failed or connection closed prematurely");
msg[bytes]='\0';
printf("%s says: %s\n", argv[1], msg); /* Print the message */
}
}
}
void DieWithError(char *errorMessage)
{
fprintf(stderr,"%s: %d\n", errorMessage, WSAGetLastError());
exit(1);
}

Tuesday, April 6, 2010

For the undergraduates

Not only B.E./B.Tech, but there are several courses out there that teach C/C++ in 1st or 2nd semester. Students who don't have slightest idea of this language at this tender age run helter-skelter to complete their assignments. For them, I'm posting here all the programs that I developed/wrote/coded for assignments when I was in second semester, thats long back in first half of 2007. Copy these, learn these, understand these, throw these, I don't care. I'm upping them here with a hope that they will be of some use to someone in great need indeed.

Disclaimer: These are programs, not software(if you consider IEEE definition of software) so these don't have any documentation, nor do I guarantee their successful run in all test cases. Its up to you to edit, modify, improve the programs. At the time of posting I didn't check the programs, so I won't be liable for any bugs. ANother thing is that these programs should be bug free. If you are getting any error from your compiler then it may be some trivial issues like conio.h or anything like that. In such a case do some research and elliminate the bug yourself, this will help you in your academics. But if you aren't able to do, then post a comment here and tell me which program is giving what error in which compiler and I'll post the solution.

Here I start, from easy to tougher:

1. Program to print the table of a user entered number.

#include <iostream.h>
int a, i;
int main()
{
cout<<"Enter the number whose table u want to print:\n ";
cin>>a;
for(i=1;i<=10;i++)
{
cout<<a<<" * "<<i<<"="<<a*i<<"\n";
}
return (0);
}


2. Program to find factorial of a number using recursion

#include <iostream.h>
long double fact(long int num){
if (num==1){
return (1);
}
else{
return (double)(num*fact(num-1));
}
}
int main(){
long int a;
cout<<"Enter number:\n";
cin>>a;
cout<<fact(a)<<endl;
return (0);
}



3. Program to find sum of digits of a number

#include <iostream.h>
#include <conio.h>
void main(){
int a, s=0, i, r;
cout<<"Enter the number: ";
cin>>a;
for(i=0; a>=9; i++){
r=a%10;
a=(a/10);
s=s+r;
}
cout<<"The sum of digits is: "<<s+a;
getch();
}



4. Program to simplify a rational number to fractions(e.g. 6/8 to 3/4)

#include<iostream.h>
void fract(int a, int b){
int min=a;
if(b<min){
min=b;
}
for(int n=1; n<=min; n++){
if((a % n == 0) && (b % n == 0)){
a=a/n;
b=b/n;
min=min/n;
n=1;

}
}
cout<<"The required fraction is "<<a<<"/"<<b;
}

void main()
{
int x, y;
cout<<"Enter the numerator:";
cin>>x;
cout<<"Enter the denominator:";
cin>>y;
fract(x, y);
}



5. Pogram to find whether a string is a palindrome or not

#include <stdio.h>
//#include <conio.h>
#include <process.h>
void main(){
char input[20];
int length=0;
printf("Enter the word for palindrome test:\n");
gets(input);
//Find the length of entered string
while(input[length]!='\0'){
length++;
}
//Now check for palindrome status
for (int i=0; i<=length--; i++){
if (input[i]!=input[length]){
printf("Entered word isn't a palindrome.");
exit(0);
}
}
printf("Entered word is a palindrome.");
// getch();
}


6. Program to print all prime numbers upto the number input by the user

#include <iostream.h>
#include <math.h>
int main(){
int i=0, n, j=0, flag=0, mid;
cout<<"Enter the number upto where you want prime numbers to be displayed:\n";
cin>>n;
cout<<"Following are the required prime numbers:\n2\n3\n";
for(i=2;i<=n;i++){
mid = floor(sqrt(i));
for(j=2;j<=mid;j++){
if(i%j==0){
flag=0;
break;
}
else{
flag=1;
}
}
if(flag==1){
cout<<i<<"\n";
}
}
return (0);
}

7. Your own strlen function. Program to find the length of a user input string

#include <iostream.h>
int i;
int strlen(char *input){
for(i=0; input[i]!='\0'; i++){
}
return i;
}
int main(){
char *data;
cin>>data;
cout<<strlen(data);
return (0);
}


8. Your own strrev function. Program to reverse a user input string

#include <iostream.h>
#include <stdio.h>
int main(){
char *name;
cout<<"Enter the string:";
gets(name);
int count=0;
for(int i=0; name[i]!='\0'; i++){
count++;
}
for (int i=count; i>=0; i--){
cout<<name[i];
}
return (0);
}

9. Program to reverse a number

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
int y=1,revs=0;
cout<<"No daalo";
cin>>a;
while(y>0)
{
b=a%10;
a=a/10;
revs=revs*10+b;
y=a;
}
cout<<revs;
getch();
}


10. Demonstrate a practical use of switch case

#include<iostream.h>
#include<conio.h>
int main()
{
float r,a;
char n;
cout<<"To find area of circle press C and for sphere press S:";
cin>>n;
switch(n)
{
case 'c':
{
cout<<"Enter the radius of the circle: ";
cin>>r;
a=3.1414*r*r;
cout<<"Area of the circle is " <<a;
break;
}
case 's':
{
cout<<"Enter the radius of the sphere: ";
cin>>r;
a=4*3.1414*r*r;
cout<<"Area of the sphere is " <<a;
break;
}
default:
cout<<"invalid entry!!!!!!!";
}
getch();
return(0);
}



11. Program to compute the union of 2 or more sets

#include <iostream.h>
int b;
int howmany(){
cout<<"How many elements you want to enter in this set";
cin>>b;
return b;
}
void main(){
int a, c[100], i=0, j=0, k=0;
cout<<"How many sets do you want to enter?";
cin>>a;
if (a<2){
cout<<"Blah blah! Enter at least two sets moron, for computation of union!";
}

for(int m=k;k<a;m++){
j=j+howmany();

cout<<"Enter the elements of this set one by one\n";
for(int n=i;i<j;n++)
{
cin>>c[i];
i++;
}
k++;
}

int temp=0;
for(a=0;a<i;a++){
for(b=a+1;b<i;b++){
if(c[a]==c[b]){
c[b]=0;
}

}
}
/////////////////////
cout<<"The union of all the sets above is:\n";
for (a=0;a<i;a++){
if (c[a]!=0){
cout<<c[a]<<"\n";
}
}
}



12. Program for matrix addition and multiplication using operator overloading and classes and ADT

#include <iostream.h>
int i, j, k, num;
class matrix{
int element[3][3];
public:
void display(){
for (int i=0;i<=2;i++){
for(int j=0; j<=2; j++){
cout<<element[i][j];
cout<<"\t";
}
cout<<"\n";
}
}
void getdata(){
cout<<"Enter the elements of matrix row wise:\n";
for (int i=0;i<=2;i++){
for(int j=0; j<=2; j++){
cin>>element[i][j];
}
cout<<"\n";
}
}

matrix operator +(matrix target){
matrix temp;
for(int i=0;i<=2;i++){
for(int j=0;j<=2;j++){
temp.element[i][j] = element[i][j]+target.element[i][j];
}
}
return temp;
}
matrix operator *(matrix target){
matrix temp;
int num=0;
for (i=0;i<=2;i++){
for(j=0;j<=2;j++){
for(k=0;k<=2;k++){
num = ((element[i][k])*(target.element[k][j]) + num);
}
temp.element[i][j] = num;
num=0;
}
}
return temp;
}
};
void main(){
matrix a, b,c ,d;
a.getdata();
b.getdata();
c.getdata();
d=a*b+c;
d.display();

}



13. Program to find the age difference between two dates using operator overloading and classes and ADT (Note that, calculating age difference is not as simple as normal subtraction other 3 part data like KM,M and CM trio)

#include <iostream.h>
#include <process.h>
class date{
int day;
int month;
int year;
bool leap;
public:
void getdata(void){
cout<<"Enter year(eg. 1988): \n";
cin>>year;
if((year%100)==0){
if((year%400)==0){
leap=true;
}
}
else if((year%4)==0){
leap=true;
}
else leap=false;
inmonth:
cout<<"Enter month(eg. 11): \n";
cin>>month;
if((month>12) || (month<1)){
cout<<"Invalid month entered. Please re-enter:\n";
goto inmonth;
}
inday:
cout<<"Enter day(eg. 25):\n";
cin>>day;
if((day>31) || (day<1)){
cout<<"Invalid day entered. Please re-enter:\n";
goto inday;
}
else if(((4==month)||(6==month)||(9==month)||(11==month))&&(day>30)){
cout<<"This month can't have more than 30 days. Please re-enter:\n";
goto inday;
}
else if((2==month)&&(leap==true)&&(day>29)){
cout<<"February can't have more than 29 days in a leap year. Please re-enter:\n";
goto inday;
}
else if((2==month)&&(leap==false)&&(day>28)){
cout<<"February can't have more than 28 days in a non-leap year. Please re-enter:\n";
goto inday;
}
}
void disp(){
cout<<year<<" years "<<month<<" months "<<day<<" days\n";
}
date operator-(date target){
int last_day_diff;
date result;
if(target.year>year){
cout<<"Please enter a higher date to subtract.";
exit(0);
}
if(target.day<=day){
result.day=day-target.day;
}
else if(target.day>day){
switch (month){
case 4:
case 6:
case 9:
case 11:
last_day_diff=30-target.day;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
last_day_diff=31-target.day;
break;
}
if ((true==leap)&&(2==month)){
last_day_diff=29-target.day;
}
else if((false==leap)&&(2==month)){
last_day_diff=28-target.day;
}
result.day=last_day_diff+day;
month--;
}
if(target.month<=month){
result.month=month-target.month;
}
else if(target.month>=month){
result.month=12-target.month+month;
year--;
}
result.year=year-target.year;
return result;
}
};


int main() {
date a, b, result;
cout<<"Enter higher date:\n";
a.getdata();
cout<<"Enter lower date:\n";
b.getdata();
result=a-b;
result.disp();
return 0;
}



14. Program to add and multiply two complex numbers using class, operator overloading, ADT

#include <iostream.h>

int abs(int input){
if (input>=0){
return input;
}
else{
return (-1*input);
}
}

class complex{
public:
int number[2]; //array to store real and imaginary part
complex(){ //constructor to intialize to zero
number[0]=0;
number[1]=0;
}

void display(){
if (number[1]>0){
cout<<number[0]<<"+"<<number[1]<<"i";
}
if (number[1]<0){
cout<<number[0]<<"-"<<abs(number[1])<<"i";
}
cout<<"\nReal part is: "<<number[0]<<" and imaginary part is: "<<number[1];

}

void getdata(){
cout<<"Enter real part:";
cin>>number[0];
cout<<"Enter imaginary part:";
cin>>number[1];

}

complex operator +(complex target){
complex temp;
temp.number[0] = number[0]+target.number[0];
temp.number[1] = number[1]+target.number[1];
return temp;
}

complex operator *(complex target){
complex temp;
temp.number[0] = (number[0]*target.number[0])-(number[1]*target.number[1]);
temp.number[1] = (number[0]*target.number[1])+(number[1]*target.number[0]);
return temp;
}

};
void main(){
complex a, b, c ,d;
a.getdata();
b.getdata();
c.getdata();
d=a*b+c;
d.display();

}



15. Program to print all ascii printable characters in a file instead of screen

#include <iostream.h>
#include <fstream.h>
int main(){
char i;
char path[255];
cout<<"Enter path:\n";
cin>>path;
ofstream file(path);
for(i=48; i<=122; i++){
file<<i<<"\n";
}
cout<<"Data written. Exiting";

return (0);
}