CSE 223: C Examples Code 1-1: / *************************************************************************** **** * EXAMPLE 1.1: THIS PROGRAM WILL DISPLAY SIMPLE INPUT & OUTPUT * * AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 * *************************************************************************** ****/ #include<iostream.h> // C Style //#include<iostream> // //using namespace std; // C++ Style // int main() { int myRoll, myYear, mySemester; // Define input data type char firstName[100], lastName[100], myDept[100]; // Define input data type cout << "Enter your first name\t:\t"; // Print message on the screen cin >> firstName; // Put the 1st input cout << "Enter your last name\t:\t"; // Print message on the screen cin >> lastName; // Put the 2nd input cout << "Enter your roll number\t:\t"; // Print message on the screen cin >> myRoll; // Put the 3rd input cout << "Enter your year\t\t:\t"; // Print message on the screen cin >> myYear; // Put the 4th input cout << "Enter your semester\t:\t"; // Print message on the screen cin >> mySemester; // Put the 5th input cout << "Enter your dept name\t:\t"; // Print message on the screen 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CSE 223: C Examples
Code 1-1:
/******************************************************************************** EXAMPLE 1.1: THIS PROGRAM WILL DISPLAY SIMPLE INPUT & OUTPUT ** AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 * *******************************************************************************/
#include<iostream.h> // C Style
//#include<iostream> ////using namespace std; // C++ Style
//int main(){
int myRoll, myYear, mySemester; // Define input data typechar firstName[100], lastName[100], myDept[100]; // Define input data typecout << "Enter your first name\t:\t"; // Print message on the screencin >> firstName; // Put the 1st inputcout << "Enter your last name\t:\t"; // Print message on the screencin >> lastName; // Put the 2nd inputcout << "Enter your roll number\t:\t"; // Print message on the screencin >> myRoll; // Put the 3rd inputcout << "Enter your year\t\t:\t"; // Print message on the screencin >> myYear; // Put the 4th inputcout << "Enter your semester\t:\t"; // Print message on the screencin >> mySemester; // Put the 5th inputcout << "Enter your dept name\t:\t"; // Print message on the screencin >> myDept; // Put the 6th inputreturn 0; // Default return
}
/* Note: Can't handle space(blank) in array input *//* Note: Requires correct inputs. No check for incorrect inputs. *//* Note: cin generates a new line */
Output in Visual C++ 6:
1
Code 2-1:
/*************************************************************************** EXAMPLE 2.1: THIS PROGRAM WILL ADD TWO INTEGER NUMBERS ** AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 ***************************************************************************/
#include<iostream.h>
int main(){
int num1,num2; // Define input data typeint sum; // Define output data typecout << "Addition of two integer numbers:" << endl; // Print message on the screen
//cout << "Addition of two integer numbers:" << "\n"; // Alternate choice for new line//cout << "Addition of two integer numbers:\n"; // Alternate choice for new line
cout << "Enter first number\t:num1 = "; // Print message on the screencin >> num1; // Put the first inputcout << "Enter second number\t:num2 = "; // Print message on the screencin >> num2; // Put the second inputsum = num1 + num2; // Add two numberscout << "The sum of two numbers\t:sum = " << sum << endl; // Print message on the screenreturn 0; // Default return
}
Output in Visual C++ 6:
2
Code 3-1:
/**************************************************************** EXAMPLE 3.1: SOLVING QUADRATIC EQATIONS ** AUTHOR: RAFIUL HOSSAIN * * DATE: April, 2004 ****************************************************************/
#include<iostream.h>#include<math.h>
int main(){
double a, b, c; // Define input data typedouble x1, x2; // Define output data typecout << "Solving a quadratic equation of x:" << endl; // Print message on the screencout << "Enter first coefficient: a = "; // Print message on the screencin >> a; // Give first inputcout << "Enter second coefficient: b = "; // Print message on the screencin >> b; // Give second inputcout << "Enter third coefficient: c = "; // Print message on the screencin >> c; // Give second inputdouble sqrd = sqrt(pow(b,2) - 4*a*c); // Add two numbersx1 = (-b + sqrd) / (2*a); // Get the first rootx2 = (-b - sqrd) / (2*a); // Get the second rootcout << "The solutions are:" << endl; // Print message on the screencout << "\tx1 = " << x1 << endl; // Print the first rootcout << "\tx2 = " << x2 << endl; // Print the second rootreturn 0; // Default return
}
// Note: b^2 - 4*a*c must not be less than zero// Note: sqrt return double data type. Use of float will give warning.
Output in Visual C++ 6:
3
Code 4-0:
/********************************************************************************Example 4.0: This Program will find bigger number from two inter numbersAuthor: Rafiul HossainDate: April, 2004
{int num1, num2;cout << "Finding the bigger number from two integer numbers" << endl;cout << "----------------------------------------------------------------" << endl << endl;cout << "Enter the first number\t: ";cin >> num1;cout << "Enter the second number\t: ";cin >> num2;
int flag, biggerNum;flag = 1;
if(num1>num2) biggerNum = num1; // check num1 is biggerelse if(num2>num1) biggerNum = num2; // check num2 is bigger
else {cout << "\n*** Numbers are EQUAL! ***" << endl; // check numbers are equalflag = 0;
if(magic == guess) {cout << "*** You are RIGHT ***" << endl << endl;
}
else {cout << "!!! You are WRONG !!!" << endl << endl;
}}
return 0;}
14
Output in Visual C++ 6:
15
Code 5-3:
/********************************************************************************Example 5.3: This Program will check you luck - Version 3Author: Rafiul HossainDate: April, 2004
if(magic == guess) {cout << "*** You are RIGHT ***" << endl << endl;//flag =0;exit (0); // Alternate
}
else {cout << "!!! You are WRONG !!!" << endl << endl;cout << "Try AGAIN ? [Y/N]: ";cin >> yesNo;//if(yesNo == 'Y' || yesNo == 'y') flag = 1;if(yesNo == 'Y' || yesNo == 'y') continue; // Alternate//else flag = 0;else exit(0); // Alternate
}}
return 0;
16
}
Output in Visual C++ 6:
17
Code 6-1:
/********************************************************************************Example 6.1: This Program for Simple Menu using if-else block - Version 1Author: Rafiul HossainDate: April, 2004
cout << "\n\nDo you want to continue? [Y/N]: ";cin >> try_again;
}
return 0;}
Output in Visual C++ 6:
19
Code 6-2:
/********************************************************************************Example 6.2: This Program for Simple Menu using switch-case block - Version 2Author: Rafiul HossainDate: April, 2004
default:cout << "\nInvalid choice. Try again !\n\n";valid=1;break;
}}cout << "\n\nDo you want to continue? [Y/N]: ";cin >> try_again;}
return 0;}
Output in Visual C++ 6:
21
Code 7-1:
/***************************************************************** Example 7.1: Simple one dimensional array* Author: Rafiul Hossain* Date: May 2004****************************************************************/
#include <iostream.h>
int main(){
int myArray [10];int i;
for(i=0; i<10; i++) myArray[i] = i;cout << "The contents of the array are: " << endl;for(i=0; i<10; i++) cout << "myArray[" << i << "] = " << myArray[i] <<endl;
return 0;}
Output in Visual C++ 6:
22
Code 7-2:
/***************************************************************** Example 7.2: Simple two dimensional array* Author: Rafiul Hossain* Date: May 2004****************************************************************/
/***************************************************************** Example 7.3: Simple three dimensional array* Author: Rafiul Hossain* Date: May 2004****************************************************************/
/***************************************************************** Example 7.4: Sorting using array - Ver 1* Author: Rafiul Hossain* Date: May 2004****************************************************************/
/***************************************************************** Example 7.5: Sorting using array - Ver 2* Author: Rafiul Hossain* Date: May 2004****************************************************************/
cout << "Enter your name\t\t: ";cin.getline(myName, size1);
cout << "Enter your roll\t\t: ";cin.getline(myRoll, size2);
cout << "Enter your department\t: ";cin.getline(myDept, size1);
cout << "Enter your year\t\t: ";cin.getline(myYear, size2);
cout << "Enter your semester\t: ";cin.getline(mySemester, size2);
return 0;}
Output in Visual C++ 6:
33
Code 7-10:
#include<iostream.h>#include<string.h>
void reverse(char[]);
int main(){
const int MAX = 80;char str[MAX];
cout << "Enter a string: ";cin.get(str, MAX);
reverse(str);
cout << "Reverse string is: " << str << endl;
return 0;}
void reverse(char s[]){
int len = strlen(s);for(int i = 0; i < len/2; i++){
char temp = s[i];s[i] = s[len - i -1];s[len - i - 1] = temp;
}}
Output in Visual C++ 6:
34
Code 7-11:// Prime Number#include<iostream.h>
int main(){
int prime;int pby2;
cout << "Enter your number: ";cin >> prime;
if(prime % 2 == 0)pby2 = prime / 2;
elsepby2 = (prime - 1) / 2;
int divisor[100];int count = 0;
for(int i = 2; i <= pby2; i++){
if(prime % i == 0){
divisor[count] = i;count++;
}}
if(count > 0){
cout << prime << " is not a prime number" << endl;cout << "The number is divisible by: ";for(i = 0; i < count; i++) cout << divisor[i] << " ";cout << endl;
}
else cout << prime << " is a prime number" << endl;
return 0;}Output in Visual C++ 6:
35
Code 7-12// Prime Number from a Range
#include<iostream.h>
int main(){
int start, end;int middle;
cout << "Enter the start number: ";cin >> start;cout << "Enter the end number: ";cin >> end;
int prime[1000];int count = 0;int flag;
for(int j = start; j < end; j++){
flag = 1;if(j % 2 == 0)
middle = j / 2;else
middle = (j - 1) / 2;
for(int i = 2; i <= middle; i++) if(j % i == 0) flag = 0;
if(flag){
prime[count] = j;count++;
}
}
cout << "The prime numbers are:" << endl; for(int k = 0; k < count; k++){
double CircleArea(float r) // Function definition{
const double Pi = 3.14;double Area = Pi * r * r; // Local variable. r doesn't change MyRadius1return Area;
}
Output in Visual C++ 6:
38
Code 8-1b# Reverse an array#include<iostream.h>#include<stdlib.h>
void reverse(int a[], int n);
int main(){
int myArray[100];int i;
cout << "How many elements in the Array: ";cin >> i;
for(int j=0; j<i; j++){
myArray[j] = rand()%99;}
cout << "The original array:" << endl;
for(j=0; j<i; j++){
cout << myArray[j] << endl;}
reverse(myArray, i);
cout << endl << "The reverse array:" << endl;
for(j=0; j<i; j++){
cout << myArray[j] << endl;}
return 0;}
void reverse(int a[], int n){ int head = 0; // index of first element int tail = n-1; // index of last element while (head < tail) { int temp = a[head]; a[head] = a[tail]; a[tail] = temp; head++; tail--;
39
} return;}
Output in Visual C++ 6:
40
Code 8-2:
// Simple function: Lower case – upper case conversion
#include <iostream.h>
char lowerToUpper(char c1);
int main(){
char lower, upper;cout << "Enter a lower case character: ";cin >> lower;
upper = lowerToUpper(lower);
cout << "The upper-case equivalent is: " << upper << endl;return 0;
Code 8-5:// Convert Decimal to Binary [Max 8-bit binary]
#include<iostream.h>#include<stdio.h>
void binaryOp(int byte); /* Print a byte in binary*/
int main(){
int byte;
cout << "Enter a decimal integer number (<256): ";cin >> byte;
binaryOp(byte); /* Print a byte in binary*/return 0;
}
void binaryOp(int byte){
int count = 8; /* Number of bits in a byte*/int MASK = 1 << (count-1);
while(count--){
/*AND the high order bit (the left one) If the bit is set print a ONE*/cout << (( byte & MASK ) ? 1 : 0); /* Move all the bits LEFT*/byte <<= 1;
}
cout << endl;}
Output in Visual C++ 6:
44
Code 8-6://*************************************** // Payroll program // This program computes each employee's // wages and the total company payroll //*************************************** #include <iostream.h> #include <fstream.h> // For file I/O
void CalcPay( float, float, float& );
// Maximum normal work hours const float MAX_HOURS = 40.0; // Overtime pay rate factor const float OVERTIME = 1.5;
//***************************************** int main() { float payRate; // Employee pay rate float hours; // Hours worked float wages; // Wages earned float total; // Total payroll int empNum; // Employee ID number ofstream payFile; // Payroll file
cout << endl <<"Reordered list of strings:" << endl << endl;
for(int i = 0; i < n; i++)cout << "String " << i+1 << "\t: " << x[i] << endl;
return 0;}
void sorting(int n, char *x[]){
char *temp;int i, j;
for(i = 0; i < n - 1; i++)for(j = i + 1; j < n; j++)
if(strcmp(x[i], x[j]) > 0){
temp = x[i];x[i] = x[j];x[j] = temp;
}}
52
Output in Visual C++ 6:
53
Code 10-0// ADD, SUB, MUL, DIV Complex Numbers
#include<iostream.h>
typedef struct {float r,i;} fcomplex;
fcomplex Cadd( fcomplex a, fcomplex b);fcomplex Csub(fcomplex a, fcomplex b);fcomplex Cmul(fcomplex a, fcomplex b);fcomplex Cdiv(fcomplex a, fcomplex b);
int main(){
fcomplex cnum1, cnum2;char c1, c2;cout << "Enter the first complex number [a+jb]: ";cin >> cnum1.r >> c1 >> c2 >> cnum1.i;
if(c1 == '-') cnum1.i = -cnum1.i;
cout << "Enter the second complex number [c+jd]: ";cin >> cnum2.r >> c1 >> c2 >> cnum2.i;
if(c1 == '-') cnum2.i = -cnum2.i;
fcomplex d = Cadd(cnum1, cnum2);fcomplex e = Csub(cnum1, cnum2);fcomplex f = Cmul(cnum1, cnum2);fcomplex g = Cdiv(cnum1, cnum2);
// ---------------------------------------- main int main() { int year; // calendar year int day; // number of the day of the week int month; // number of the month cout << "Enter year for calendar: "; cin >> year; cout << "Enter day of the week for January 1," << year <<"." << endl; cout << "Enter 0 for Sunday, 1 for Monday,etc.: "; cin >> day;
// ---------------------------------- PrintMonth void PrintMonth(int month, int year, int& startDay) { int daysInMonth; // number of days in month int day; // day of the week
64
PrintMonthHeader(month, year);
daysInMonth = MonthDays(month, year);
// output empty days in first line day = 0; while (day < startDay) { cout << " "; day++; }
// output days for the month day = 1; while (day <= daysInMonth) { cout << setw(3) << day; startDay++; if (startDay % 7 == 0) // Saturday { cout << endl; startDay = 0; }
day++; } cout << endl;
} // end PrintMonth
// ---------------------------- PrintMonthHeader void PrintMonthHeader(int month, int year) { cout << endl; if (month == JAN) cout << " January " << year << endl << endl; else if (month == FEB) cout << " February " << year << endl << endl; else if (month == MAR) cout << " March " << year << endl << endl; else if (month == APR) cout << " April " << year << endl << endl; else if (month == MAY) cout << " May " << year << endl << endl; else if (month == JUN) cout << " June " << year << endl << endl;
65
else if (month == JUL) cout << " July " << year << endl << endl; else if (month == AUG) cout << " August " << year << endl << endl; else if (month == SEP) cout << " September " << year << endl << endl; else if (month == OCT) cout << " October " << year << endl << endl; else if (month == NOV) cout << " November " << year << endl << endl; else if (month == DEC) cout << " December " << year << endl << endl;
cout << " S M T W T F S " << endl; cout << " ------------------- " << endl;
} // end PrintMonthHeader
// ------------------------------------ MonthDays int MonthDays(int month, int year) { int days; // number of days in the month
if (month == JAN || month == MAR || month == MAY || month == JUL || month == AUG || month == OCT || month == DEC) days = 31; else if (month == FEB) { // leap year is a year that is divisible // by 4 but is not divisible by 400, // unless it is divisible by 2000 if ( (year % 4 == 0) && ( (year % 400 != 0) || (year % 2000 == 0) ) ) days = 29; else days = 28; } else days = 30;
rectangle rect1;float length; // Not same as in Classfloat width; // Not same as in Classcout << "Enter length of rectangle\t: ";cin >> length;cout << "Enter width of rectangle\t: ";cin >> width;rect1.getArea(length, width);rect1.showData();