Showing posts with label Assignment. Show all posts
Showing posts with label Assignment. Show all posts

RDBMS Past Paper Questions and Answers

Relational Database Management System Questions and Answer

Question 1
i) Convert the following ER diagram to table structure in a relational database. The attribute capacity may have values such as captain, vice captain, member etc.

RDBMS Past Paper Questions and Answers

Based on the table Structures obtained above answer the below questions.

ii) Write an SQL statement to get a list of sports that do not have captains.
iii) Write an SQL statement to obtain a list of students (StudentID and Name) who participate in any sport as a captain.


Answer

i)
Student(StudentID, Name)
Sport(SportID, Name)
StudentSport(StudentID, SportID, Year, Capacity)

ii)
Select distinct SportID from StudentSport where capacity <> "captain"

iii) Select Student.ID, Student.Name from Student, StudentSport where Student.StudentID=StudentSport.StudentID and StudentSport.Capacity="captain"


Question 2
The candidates who have been selected for university entrance should register for the given academic year with the university given to them. Candidate who do not register before the Last date announced by each university will lose their university entrance. Once a candidate registers with given university , the candidate becomes a registered student of that university. Registered students can apply for financial support. A student can get many financial support. These financial supports could be either full or partial. All registered students will receive a laptop. However, its ownership cannot be transferred to another student. The user requirements of the above system are listed below. A user shall be able to obtain.
i) a list of students registered for a given academic year with a given university.
ii) information (such as model, serial number, warranty period) about the laptops given to each student.
iii) list of students who applied for financial support.

Draw an entity Relationship(ER) diagram required to design a database to represent the above system description and to satisfy the user requirements. State all your assumptions clearly.

Answer

RDBMS ERD QUESTIONS ANSWERS



Combinational circuits Design Questions and Answers

ICT Questions and Answers

Question 1
A digital circuit takes four digits as an input, and produce 'X' as its output. If the decimal value represented by the four binary digit is a prime number. If it is prime output is 1 otherwise 0. Assume that all four binary digit represent positive decimal values.

i) Draw a truth table for the above problem.
ii) Write the Boolean expression in the sum of product form.
iii) Design a logic circuit for the Boolean expression, which is obtained above.
iv) Simplify the expression using Boolean algebra/ Karnaugh map.

Answer
i) Truth Table

ABCDX
00000
00010
00101
00111
01000
01011
01100
01111
10000
10010
10100
10111
11000
11011
11100
11110


ii) X= A'B'CD' + A'B'CD + A'BC'D + A'BCD + AB'CD + ABC'D

iii)
Combinational Circuit to detect prime numbers


iv)
Combinational Circuit Questions and Answers



Question 2
Consider the logic circuit shown here to answer the below questions.

Combinational Circuit Design ICT A/L

i) Write and simplify the Boolean expression for the above circuit using Boolean algebra . Show all the workings and algebraic rules used for the simplification.

ii) Construct the logic circuit using combination of only AND, OR and NOT gates for the simplified Boolean expression obtained above.

Answer
i)
ABC + A'BC + ABC'
BC(A+A') + ABC'
BC + ABC'
B(C+AC')
B(A+C)

ii)

Combinational Past Paper ICT Answer


Web page development Questions and Answers 2

Learn Web Development By Examples

Web Development Questions and Answers

A HTML document of the file "circket.html" which generates the above web page. Write HTML with the appropriate tags to render the above web page.
Consider the following when you write HTML.

  1. When the user clicks on the phrase "Sri lankan national cricket team", it should display the document named "team.html".
  2. Name of the source file of the image displayed on the above webpage is "cricket.jpg".
  3. The link to the image "cricket.jpg" should have an alternative description "cricket".


Answers

 
<html>
<head>
<title>Test Cricket</title>
</head>
<body>
<h2>Sri Lankan Test cricket records</h1>
<hr/>
<p>The<a href="team.html">
Sri Lankan national cricket team </a>
played their first Test match on 17 February 1982 against England.
</p>
<p><b>Record Groups</b></p>
<ul>
<li> Team records</li>
<li>Individual records</li>
<li>Partnership records</li>
</ul>
<h2>Partnersbip records</h2>
<p><img src="cricket.jpg" alt="crickekt"> <br/>Sri Lanka holds the most
number of partnership records in Test cricket,
with the records for the second, third, fourth, and sixth wickets.
South Africa and Pakistan are ranked second with two records each.
</p>
<table border="1">
<caption>Highest wicket partnerships</caption>
<tr>
<th>Runs</th>
<th>Wicket</th>
<th colspan = "2">Partners</th>
</tr>
<tr>
<td>335</td>
<td>1st wicket </td>
<td>Marvan Atapattu</td>
<td>Sanath Jayasuriya</td>
</tr>
<tr>
<td>576</td>
<td>2nd wicket</td>
<td>Sanath Jayasuriya</td>
<td>Roshan Mahanama</td>
</tr>
</table>
</body>
</html>



Web Design Questions and Answers 1

Web Page Design with HTML and CSS Questions and Answers

Questions

Environmental Institute of Colombo intends to develop a website to provide information on an art competition for students. A web page from this website and another web page with entry form to register for the competition are shown in figure below.

Web design Questions and Answers 1


Web Design
  1. Using appropriate HTML, tags, create a HTML file required to render the web page as shown in pic-1. your code shuold satisfy the following requirements.It is required to format the text of the list in 'Calibri' font, 14 points high, in red color. The list should be bulleted with squares. Format the list by using internal or external style sheet only. Further, when a user clicks on the hypetext 'online entry form' on the web page, the entry from given in pic-2 should be rendered on a new tab/page. Assume that the name of the HTML file of the web page with the entry form is 'form.html'.

  2. Using appropriate HTML tags, create a HTML file to render the entry form given in pic-2. The option for 'Grade Category' are given in the pic-3. Your code should satisfy the following requirements. When the 'Clear your Entries' Button is clicked, all the entries of the form should be cleared. Similarly, when the 'Submit' button is clicked, the form should be submitted to the server.


Answers

 

a)
<html>
<head>
<meta charset="utf-8">
<title>Information</title>
<style>
li{font-family:calibri;font-size:14pt;color:red;list-style:square;}
</style>
</head>
<body>
<h1> Student Art Competition</h1>
<h2>Theme: Litter on the environment</h2>
<h3>PRIZES<h3>
<ul>
<li>1st place Rs. 10,000/=</li>
<li>2nd place Rs. 7,500/=</li>
<li>3rd place Rs. 5,000/=</li>
</ul>
<h3>Entry Form</h3>
<p>Please fill and submit this <a href="form.html" target="_blank">online entry form</a> to enter the competition.</p>
</body>
</html>

b)
<html>
<head>
<meta charset="utf-8">
<title>Entry Form</title>
</head>
<body>
<h1>Art Competition Online Entry Form 2017</h1>
<h3>Theme:Litter on the environment</h3>
<form method="get" action="abc.php">
Name: <input type="text" name="name">
<p>Gender:
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female">Female
</p>
<p>Grade Category
<select name="ageGroup">
<option value="g1">Grade 1-2</option>
<option value="g2">Grade 3-6</option>
<option value="g3">Grade 7-10</option>
<option value="g4">Grade 11-13</option>
</select>
</p>
<p>Art media </p>
<input type="checkbox" name="media1" value="Colour">Water Colurs <br>
<input type="checkbox" name="media2" value="Pencils">Colur Pencils<br>
<input type="checkbox" name="media3" value="Crayon">Crayon<br>
<input type="checkbox" name="media4" value="Chalk">Chalk<br>
<p> <input type="reset" value="Clear your Entries"></p>
<p> <input type="submit" value="Submit"></p>
</form>
</body>
</html>



C# Program for Database Connection with MySQL

Sample C# Windows application program to connect MySql Database to do operation such as Select, Add, Edit, Delete and update.

Database Name : Viber
Table Name : Viber_Users
Columns in Table : Member_Id, Member_Name, State, Country

Screen Design


   
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace WinApp
{
    public partial class Viber2 : Form
    {
		Database db = new Database();
		public Viber2()
        {
            InitializeComponent();
        }

        private void Viber2_Load(object sender, EventArgs e)
        {

        }


		class Database
		{
			private MySqlConnection con;
			private MySqlCommand cmd;
			private MySqlDataAdapter da;

			public Database() // Default Constructor
			{
				con = new MySqlConnection("server=localhost;user=ganesh;database=viber;password=DSHUc4kzLJCp1Gho");
			}
			public void openConnection()
			{
				con.Open();
			}

			public void closeConnection()
			{
				con.Close();
			}

			public int save_update_delete(string a)
			{
				openConnection();
				cmd = new MySqlCommand(a, con);
				int i = cmd.ExecuteNonQuery();
				closeConnection();
				return i;
			}
			public DataTable getData(string a)
			{
				openConnection();
				da = new MySqlDataAdapter(a, con);
				DataTable dt = new DataTable();
				da.Fill(dt);
				closeConnection();
				return dt;
			}
		}

		private void btn_add_Click(object sender, EventArgs e)
		{
			int i = db.save_update_delete("Insert into Viber_Users values (" + Convert.ToInt16(txt_memid.Text) 
				+ ",'" 	+ txt_memname.Text + "', '" + txt_state.Text + "', '" + txt_country.Text + "')");
			if (i == 1)
				MessageBox.Show("Data Inserted Succesfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
			else
				MessageBox.Show("Data not Inserted", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		private void btn_list_Click(object sender, EventArgs e)
		{
			dataGridView1.DataSource = db.getData("select * from viber_users");
		}

		private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)		
		{
			txt_memid.Text= dataGridView1.CurrentRow.Cells[0].Value.ToString();
			txt_memname.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
			txt_state.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
			txt_country.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
		
		}

		private void btn_edit_Click(object sender, EventArgs e)
		{
			DialogResult dr = MessageBox.Show("Do you really want to Update?", "Infromation", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

			if (dr.ToString() == "Yes")
			{
				int i = db.save_update_delete("Update Viber_Users set Member_Name= '" + txt_memname.Text
					+ "', State= '" + txt_state.Text
					+ "', Country= '" + txt_country.Text + "'"
					+ " where Member_Id= " + Convert.ToInt16(txt_memid.Text));

				if (i == 1)
					MessageBox.Show("Data Update Successfully", "Infromation", MessageBoxButtons.OK, MessageBoxIcon.Information);
				else
					MessageBox.Show("Data Cannot Update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btn_delete_Click(object sender, EventArgs e)
		{
			DialogResult dr = MessageBox.Show("Do you really want to Delete?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

			if (dr.ToString() == "Yes")
			{
				int i = db.save_update_delete("Delete from Viber_Users where Member_Id= " + Convert.ToInt16(txt_memid.Text));
				if (i == 1)
					MessageBox.Show("Data Delete Successfully", "Infromation", MessageBoxButtons.OK, MessageBoxIcon.Information);
				else
					MessageBox.Show("Data Cannot Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btn_search_Click(object sender, EventArgs e)
		{
			if (txt_search.TextLength > 0)
			{
				if (rbn_id.Checked == true)
				{
					dataGridView1.DataSource = db.getData("select * from Viber_Users where Member_Id =" + Convert.ToInt16(txt_search.Text));
				}
				else
				{
					dataGridView1.DataSource = db.getData("select * from Viber_Users where Member_Name like '" + txt_search.Text + "%' ");
				}
			}
			else
			{
				dataGridView1.DataSource = db.getData("select * from Viber_Users");
			}
		}
	}
}
  



Data Structure and Algorithm Doubly Linked List

Write a java program to
a) Input marks of 10 students marks into a doubly linked list.
b) Output marks in the doubly linked list according to the input order.
c) Output marks in the doubly linked list according to the reverse order.

 
import java.util.Scanner;
public class DoublyLinkedList 
{
	//define Node for Linked list
	class Node
	{
		int data;
		Node previous;
		Node next;
		public Node(int data) 
		{
			this.data = data;
		}
	}  
    	Node head, tail = null;
	//add element to linked list(double)
	public void addNode(int data)
	{
		Node newNode = new Node(data); 
		if(head == null) 
		{
			head = newNode;
			tail = newNode;
			head.previous = null;
			tail.next = null;
		}
		else
		{
			tail.next = newNode;  
          		newNode.previous = tail;
			tail = newNode;
			tail.next = null;
		}  
    	}
	//method to print all element from head
	public void display()
	{
		Node current = head;  
		if(head == null) 
		{  
			System.out.println("List is empty");  
			return;  
        	}
        	System.out.println("doubly linked list from head");  
        	while(current != null) 
		{  
			System.out.print(current.data + " "); 
			current = current.next;  
        	}  
    	}  
	//method to print all element from tail
	public void displayReverse()
	{
		Node current = tail;  
		if( tail == null) 
		{  
			System.out.println("List is empty");  
			return;  
                }
        		System.out.println("Linked list Reverse order: ");  
        	while(current != null) 
		{  
			System.out.print(current.data + " "); 
			current = current.previous;  
                }  
       }

  	//main method
	public static void main(String[] args) 
	{
		Scanner myObj = new Scanner(System.in);
		int i;
		DoublyLinkedList dList = new DoublyLinkedList();  
        
		//Add module marks of 10 student to linked list
		for (i=0; i < 10; i++)
		{
			System.out.println("Enter a Module marks of a Student?"); 
			int mark = Integer.parseInt(myObj.nextLine());
        	dList.addNode(mark);  
		}
        	//Displays the all students mark from head 
        	dList.display();  
			System.out.println();
        	//Displays all student marks from tail(Reverse) 
        	dList.displayReverse();  
    }  
}  
 

C Program Assignments and Answers 2

Question 

Write a menu driven program in C to process the sales data in branches (Use arrays).
a) A function to input number of cars sold in each branch.
b) A function to display the highest and the lowest number of cars sold.
c) A function to display the total number of cars sold.
d) A function to display the number of cars sold in each branch.
e) A function which display the no. Of branches which have achieved the monthly target.



Answer
 #include <studio.h>
#define MAX 20
#define TARGET 15

void InputSale(char c[], float s[]);
void printSale(char c[],float s[]);
void printComp(char c[]);
void printLowHigh(float s[]);
void printTotSale(float s[]);
void printTarget(float s[]);

main()
{
    int T;
    char choice;
    T = 1;
    char comp[MAX];
    float sales[MAX];

    while (T != 0)
    {
        printf("%s\n", "1 -Input Branch and Sales ");
        printf("%s\n", "2 -Display the highest and the lowest number of cars sold ");
        printf("%s\n", "3 -Display the total number of cars sold. ");
        printf("%s\n", "4 -Display the number of cars sold in each branch. ");
        printf("%s\n", "5- Display the no. Of branches which  achieved  target");
        printf("%s\n", "6 -Display Branches");
        printf("%s\n", "7 -Exit ");
        printf("%s\n", "Enter a Selection 1 -7 ?");
        scanf_s(" %c", &choice);
        switch (choice)
        {
        case '1':
            InputSale(comp, sales);
            break;
        case '2':
            printLowHigh(sales);
            break;
        case '3':
            printTotSale(sales);
            break;
        case '4':
            printSale(comp, sales);
            break;
        case '5':
            printTarget(sales);
            break;
        case '6':
            printComp(comp);
            break;
        case '7':
            T = 0;
            break;
        default:
            printf("%s", "invalid selection please enter correct selection");
            break;
        }
    }  
    getch();
}

void InputSale(char c[], float s[])
{
    int i;
    for ( i = 0; i < MAX; ++i)
    {
        printf("%s", "Enter Branch ?");
        scanf_s(" %c", &c[i]);
        printf("%s", "Enter Sales ?");
        scanf_s("%f", &s[i]);

    }
}
void printSale(char c[],float s[])
{
    int i;
    for (i = 0; i < MAX; ++i)
    {
        printf(" %c - %f\n", c[i],s[i]);
    }
}

void printTotSale(float s[])
{
    int i;
    float Tot = 0;
    for (i = 0; i < MAX; ++i)
    {
        Tot = Tot + s[i];
    }
    printf("Total Sales %f \n", Tot);
}

void printTarget(float s[])
{
    int i;
    int C = 0;
    for (i = 0; i < MAX; ++i)
    {
        if (s[i] > TARGET)
            C = C + 1;
    }
    printf("Number of Companies Acheived Target %d \n", C);
}

void printComp(char c[])
{
    int i;
    for (i = 0; i < MAX; ++i)
    {
        printf("%c\n", c[i]);
    }
}
void printLowHigh(float s[])
{
    int i;
    float L, H;
    L = s[0];
    H = s[0];
    for (i = 1; i < MAX; ++i)
    {
        if (s[i] > H)
            H = s[i];
        if (s[i] < L)
            L = s[i];
    }
    printf("Highest sales Value is %f\n", H);
    printf("Lowestest sales Value is %f\n",L);
}

C Program Assignments and Answers

Question 1
Determine the output and value of each variable after the execution of each code. All variables have the value of 2 before execution of each statement
a) printf(“ %d %d ”,++c+x++,c);
b) printf(“ %d ”,sum+c-2);
c) printf(“%d”, ++sum+x+c--);
d) printf(“ %d %d %d”,--sum+x , ++c , x);

 Answers:

a)
#include <stdio .h="" >
int main()
{
    int c, x;
    c = 2;
    x = 2;
    printf("%d %d", ++c + x++, c);   
}

Answer
5  3

b)
#include <stdio .h> 
int main()
{
    int sum, c;
    sum = 2;
    c = 2;
    printf("% d", sum + c - 2);
}
Answer
2

c)
#include <stdio .h>
int main()
{
    int sum, x, c;
    sum = 2;
    x = 2;
    c = 2;
    printf(" % d", ++sum + x + c--);
}

Answer
7

d)
#include <stdio .h>
int main()
{
    int sum, x, c;
    sum = 2;
    x = 2;
    c = 2;
   printf(" %d %d %d", --sum + x, ++c, x);
}


Answer
3 3 2

Question 2
Write a single C statement for each of the following:
a) Decrease the value of A by 1, decrease the value of B by 1 and divide A from B. Assign the result to R.
b) Reduce the value of P by 1, then subtract P from Q and then decrease the value of Q by 1. Assign the result to Z.
c) Increase the value of A and B by 1 and multiply A from B. Assign the result to C.
d) Reduce 1 from A and deduct 1 from B and add A and B. Assign the result to X.

 a)
Answer for the Question
    R = --A / --B;

//Testing Program
#include <stdio .h>
int main()
{
    /*Decrease the value of A by 1, decrease the value of B by 1
    and divide A by B.Assign the result to R.*/
    int A, B, R;
    A = 7;
    B = 3;
    R = --A / --B;
    printf("%d", R);
}

Answer Testing Program
3

 b)
Answer for the Question
    Z = Q-- - --P;

//Testing Program
#include <stdio .h> 
int main()
{
    /*Reduce the value of P by 1, then subtract P from Q 
    and then decrease the value of Q by 1. Assign the result to Z. */
    int P, Q, Z;
    P = 7;
    Q = 10;
    Z = Q-- - --P;
    printf("%d %d", Z,Q);
}


Answer Testing Program
4  9


c)
Answer for the Question
    C = ++A * ++B;

//Testing Program
#include <stdio .h>
int main()
{
   /*Increase the value of A and B by 1 and multiply A from B. 
   Assign the result to C. */
    int A, B, C;
    A = 2;
    B = 3;
    C = ++A * ++B;
    printf("%d", C);
}

Answer Testing Program
12

 d)
Answer for the Question
    X = --A + --B;

//Testing Program
#include <stdio .h="" > 
int main()
{
   /*Reduce 1 from A and deduct 1 from B and add A and B. 
   Assign the result to X. */
    int A, B, X;
    A = 2;
    B = 3;
    X = --A + --B;
    printf("%d", X);
}

Answer Testing Program
3

Question 3
A Teacher conduct exam for her/his students. Write a Programme in C to input the marks of 20 students into an array and output the average marks of the class.

 #include < stdio.h >
main()
{
	int i;
	float income[5], Tot,Avg;
	i = 0;
	Tot = 0;
	Avg = 0;
	while (i < 5)
	{
		printf("%s","Enter Daily Income?");
		scanf_s("%f", &income[i]);
		Tot = Tot + income[i];
		i = i + 1;
	}
	Avg = Tot /5;
	printf("Average bus Income %10.2f", Avg);
	
}

Question 4
Write a program to:
*Input item no, quantity and price for items selected by a customer.
*Cashier should enter -99 as item number to get the final total.
* Program should display the bill as mention below.
*Customer will get a discount for their total bill as given below:
5% discount – if total bill amount > = 5,000
7% discount – if total bill amount > = 10,000
10% discount – if total bill amount > = 10,0000
*Print the bill with details of input with Total, Discount amount and Net Amount

 #include <stdio .h>
int main()
{
     
    int itemno[30], qty[30];
    float price[30];  
    double tot,Gtot, discount;
    char T,i,j;
    T = 1;
    i = 0;
    while (T != 0)
    {
        printf("%s", "Enter a Item No:");
        scanf_s("%d", &itemno[i]);
        if (itemno[i] == -99)
        {
            break;
        }
        printf("%s", "Enter a Item Qty:");
        scanf_s("%d", &qty[i]);
        printf("%s", "Enter a Item Price:");
        scanf_s("%f", &price[i]);
        i = i + 1;
    }
    tot = 0;
    Gtot = 0;
    discount = 0.00;
    printf("%s\t%s\t%s\t\%s\n", "Item", "Qty", "Price", "Total");
    for (j = 0;j <= i-1;j++)
    {
        tot = (double)qty[j] * price[j];
        printf("%d\t%d\t%f\t\%lf\n", itemno[j], qty[j], price[j],tot);
        Gtot = Gtot + tot;
   
    }
    if (Gtot >= 100000)
    {
        discount = (double)Gtot * 10 / 100;
    }
    else
    {
        if (Gtot >= 10000)
        {
            discount = (double)Gtot * 7 / 100;
        }
        else
        {
            if (Gtot >=5000)
                discount = (double)Gtot * 5 / 100;
        }
    }
    printf("%c", '\n');
    printf("Total\t\t\t%lf\n", Gtot);
    printf("Discount\t\t%lf\n", discount);
    printf("Net\t\t\t%lf\n", (double)Gtot - discount);

}


Question 5
Write a C program to input elements to 4x4 matrix and print matrix.

 Answer
#include <stdio .h>

int main() {
    /* matrix 4x4 declaration*/
    int disp[4][4];
    int i, j;
    for (i = 0; i < 4; i++) {
        for (j = 0;j < 4;j++) {
            printf("Enter matrix value [%d][%d]:", i + 1, j + 1);
            scanf_s("%d", &disp[i][j]);
        }
    }
    //Displaying array elements
    printf("Two Dimensional array elements:\n");
    for (i = 0; i < 4; i++) {
        for (j = 0;j < 4;j++) {
            printf("%d\t ", disp[i][j]);
            
            }
            printf("\n");
       
    }
    getch();
}


Question 6
A Driver Want to Calculate his Income. Write a Programme in C to input customer number, distance travelled (in kms) by his customer, charge per Kilometer and output the income received from all customers who have completed hires. A kilometer charge can be different for each customer. Use -999 for customer number to terminate and display the output

 #include < stdio.h >
#define  datacount 5
main()
{
	int Custno[datacount],C;
	float Distance[datacount],Charge[datacount],Income;

	C = 0;
	Income = 0;
	while (C < datacount)
	{
		printf("%s", "Enter a Customer no?");
		scanf_s("%d", &Custno[C]);
		if (Custno[C] == 999)
			break;
		printf("%s", "Enter a Distance Travelled?");
		scanf_s("%f", &Distance[C]);
		printf("%s", "Enter a Charge Per Kilo Meter?");
		scanf_s("%f", &Charge[C]);
		Income = Income + Distance[C] * Charge[C];
		C = C + 1;
	}
	for (int i = 0; i  < C; i++)
	{
		printf("Customer No:%d  Distanced Travelled: %10.2f _ 
        Kilometer Travelled %10.2f\n", Custno[i], Distance[i],Charge[i]);		
	}
	printf("Total Incode is : %10.2f", Income);
	
}

Note
Dynamic Memory Allocation

When we define a array we should know the size of the array. But if we don't know the size then we can allocate memory dynamically. There are some functions defined in the stdlib.h header file in C language. The functions are

malloc()
//format ptr=(castType*) malloc(size) -allocate memory without uninitialised for a given size
Example
int *ptr;
ptr=(int*) malloc(50*sizeof(int));

calloc()
//format ptr=(castType*) calloc(n,size) -allocate memory with initialised with zero
Example
int *ptr;
ptr=(int*) calloc(25,sizeof(int));

//free(ptr) free the space allocated
Example
int *ptr;
ptr=(int*) calloc(25,sizeof(int));
free(prt);

realloc()
//ptr =realloc(ptr,x) - change the size of the allocated memory size. n is reallocated size
int *ptr;
ptr=(int*) malloc(100,sizeif(int));

ptr=realloc(ptr,50,sizeif(int));

free(ptr);

if we use the dynamic memory allocation for the above program than C Program will be as follows:

 #include < stdio.h >
#include <stdlib.h>
#define  datacount 5
main()
{
	int* Custno,C;
	float * Distance, * Charge, Income;	
	Custno = (int*)calloc(datacount, sizeof(int));
	Distance = (float*)calloc(datacount, sizeof(float));
	Charge = (float*)calloc(datacount, sizeof(float));

	C = 0;
	Income = 0;
	while (C <datacount)
	{
		printf("%s", "Enter a Customer no?");
		scanf_s("%d", Custno+C);
		if (*(Custno+C) == 999)
			break;
		printf("%s", "Enter a Distance Travelled?");
		scanf_s("%f", Distance+C);
		printf("%s", "Enter a Charge Per Kilo Meter?");
		scanf_s("%f", Charge+C);
		Income = Income + *(Distance+C) * *(Charge+C);
		C = C + 1;
	}
	for (int i = 0; i < C; i++)
	{
		printf("Customer No:%d  Distanced Travelled: %10.2f -
        Charge per km % 10.2f\n",Custno[i], Distance[i],Charge[i]);		
	}
	printf("Total Incode is : %10.2f", Income);
	free(Custno);
	free(Distance);
	free(Charge);
}


Question 7

Write a program in C to calculate the discount amount and display the discounted amount. Use separate functions to

a) Input amount and discount amount
b) Calculate discount amount
c) Display the Calculated Amount
provide meaning full names for functions and parameters.

 #include <stdio.h>

void billInput(float *amt, float *discount);
float calculateDiscount(float amt, float discount);
void displayDiscountAmt(float Amount, float amt);

main()
{
	float Amount, Discount;
	billInput(&Amount, &Discount);
	displayDiscountAmt(Amount, Discount);
}

void billInput(float *amt, float *discount)
{
	printf("Enter the Bill Amount ?");
	scanf_s("%f", amt);
	printf("Enter the Discount Amount ?");
	scanf_s("%f", discount);
}

float calculateDiscount(float amt, float discount)
{
	float d;
	d = amt * discount / 100;
	return d;
}

void displayDiscountAmt(float amt, float amount)
{
	float disAmt;
	disAmt = amt - calculateDiscount(amt, amount);
	printf("Discounted Amount=%10.2f",disAmt);
}

Menu Driven C Program to Matrix Manipulation

Write a menu driven program in C for the following:
a) A function to input data to a Matrix A and B of length 4 by 4.
b) A function to display the addition of A and B.
c) A function to display the multiplication of A and B.

Answer

 #include <stdio.h>

#define ROWS 4
#define COLS 4
void  arrInput(int mat[][COLS]);
void  arrPrint(int mat[][COLS]);
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);
void matrixMul(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);

int main() {
    char T,Sel;
    int M1[ROWS][COLS];
    int M2[ROWS][COLS];
    int M1PM2[ROWS][COLS];
    int M1MM2[ROWS][COLS];
    T = 1;
    //menu Start
    do
    {

        printf("%s", "Enter 1 for Add Elements to Matrix A and B\n");
        printf("%s", "Enter 2 for Print Matrix A and B\n");
        printf("%s", "Enter 3 for Add Matrix A and B and Print new Matrix\n");
        printf("%s", "Enter 4 for Multiply Matrix A and B and Print new Matrix\n");
        printf("%s", "Enter 5 Exit\n");
        printf("%s", "Enter a Select : 1 - 5 ?");
        scanf_s("%c", &Sel);
        switch (Sel)
        {
        case '1':
            printf("%s\n", "Enter Elements for Matrix A");
            arrInput(M1);
            printf("%s\n", "Enter Elements for Matrix B");
            arrInput(M2);
            break;
        case '2':
            printf("%s\n", "Matrix A");
            arrPrint(M1);
            printf("%c", "\n");
            printf("%s\n", "Matrix B");
            arrPrint(M2);
            break;
        case '3': 
            matrixAdd(M1, M2, M1PM2);
            printf("%s\n", "After Add  A and B");
            arrPrint(M1PM2);
            break;
        case '4':
            matrixMul(M1, M2, M1MM2);
            printf("%s\n", "After Multiplied  A and B");
            arrPrint(M1MM2);
            break;
        case '5':
            T = 0;
            break;
        default:
            printf("%s", "Invalid Selection Enter again!...");
            continue;

        }
    }while (T == 1);
    //menu end
}

//function to input matrix data
void  arrInput(int mat[][COLS])
{
    int i, j;
    for (i = 0; i < 4; i++) {
        for (j = 0;j < 4;j++) {
            printf("Enter matrix value for arr[%d][%d]:", i + 1, j + 1);
            scanf_s("%d", &mat[i][j]);
        }
    }   
}

//function to print Matrix
void  arrPrint(int mat[][COLS])
{
    int i, j;
    printf("Print Matrix elements:\n");
    for (i = 0; i < 4; i++) {
        for (j = 0;j < 4;j++) {
            printf("%d\t ", mat[i][j]);
        }
        printf("\n");

    }
}

//function to add two matrices
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS])
{
    int i, j;
    for (i = 0; i < ROWS; i++)
    {
        for (j = 0; j < COLS; j++)
        {
            res[i][j] = mat1[i][j] + mat2[i][j];
        }
    }
}

//function to multiply matrices
void matrixMul(int mat1[][COLS], int mat2[][COLS], int res[][COLS])
{
    int i, j, k;
    printf("multiply of the matrix=\n");
    for (i = 0;i < ROWS;i++)
    {
        for (j = 0;j < COLS;j++)
        {
            res[i][j] = 0;
            for (k = 0;k < COLS;k++)
            {
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

C++ Questions and Answers 3

Question 1
What is the output of the following program given in Listing ? In your answer use "\0" to indicate the null character output by the program.

 
#include <iostream> 
using namespace std;   
int main() 
{
	int n = 1, * p;
	p = &n;
	char aString[] = { "student" };
	for (int i = 0;i < 5; i++)
		cout<< " i= " << i << " n*n= " << n * n << " n++= " << n++ << " *p= " << *p << endl;"
	for (int i = 0;i <= 7;i++)
		cout<< "Element at index " << i << " is " << aString[i] << endl;
	return 0;"
}

Answer 

i= 0 n*n= 4 n++= 1 *p= 2
i= 1 n*n= 9 n++= 2 *p= 3
i= 2 n*n= 16 n++= 3 *p= 4
i= 3 n*n= 25 n++= 4 *p= 5
i= 4 n*n= 36 n++= 5 *p= 6
Element at index 0 is s
Element at index 1 is t
Element at index 2 is u
Element at index 3 is d
Element at index 4 is e
Element at index 5 is n
Element at index 6 is t
Element at index 7 is "\0"

Question 2
As appropriate amend the following C++ program given below, in order to define and use a struct data structure called Driver, which will hold a given driver Age, claims and premiumDue variables. Their data type should remain the same as in the current version of this program. Amendments are given as questions a), b), c) and d)

 
#include <iostream>
using namespace std;
int main() 
{
	int driverAge, claims;
	double premiumDue = 75.32;
	cout << "Enter the driver age: ";
	cin >> driverAge;
	cout <<"\nEnter the number of insurance claims the driver made in the last 3 years: ";
	cin >> claims;
	if (driverAge < 26)
	{
		claims < 3 ? (premiumDue += 100) : (premiumDue += 170);
	}

	else if (driverAge < 70) 
	{
		cout << " 70 bractket";
		claims >= 3 ? (premiumDue += 70) : (premiumDue += 50);
	}

	cout << "\n your premium is :" << premiumDue << endl;
	return 0;
}

a)
After line 7 in the above program) add an if else statement to only accept values for the driverAge variable which are between 16 and 70 inclusive.

 
Answer
#include <iostream>
using namespace std;
int main()
{
	int driverAge, claims;
	double premiumDue = 75.32;
	cout << "Enter the driver age: ";
	cin >> driverAge;
	if ((driverAge < 16) || (driverAge > 70)) 
	{
		cout << "Invalid age please reenter";
	}

	else 
	{
		cout << "\nEnter the number of insurance claims the driver made in the last 3 years: ";
		cin >> claims;
		if (driverAge < 26) 
		{
			claims < 3 ? (premiumDue += 100) : (premiumDue += 170);
		}

		else if (driverAge < 70) 
		{
			cout << " 70 bractket";
			claims >= 3 ? (premiumDue += 70) : (premiumDue += 50);
		}

		cout << "\n your premium is :" << premiumDue << endl;
		return 0;
	}
}

b)
Based on the program given above, you are required to include a while loop after line 9 to only accept values for the claims variables which are between 0 and 5 inclusive. Also the program should loop until the user has entered a value for the claims variable.

 
Answer
#include <iostream>
using namespace std;
int main() 
{
	int driverAge, claims;
	double premiumDue = 75.32;
	cout << "Enter the driver age: ";
	cin >> driverAge;
	if ((driverAge < 16) || (driverAge > 70)) 
	{
		cout << "Invalid age please reenter";
	}
	else 
	{
		cout << "\nEnter the number of insurance claims the driver made in the last 3 years: ";
		cin >> claims;
		while ((claims <0)|| (claims > 5))
		{
			cout << "Invalid enter value between 0 -5 ";
			cin >> claims;
		}

		if (driverAge < 26) 
		{
			claims < 3 ? (premiumDue += 100) : (premiumDue += 170);
		}
		else if (driverAge < 70) 
		{
			cout << " 70 bractket";
			claims >= 3 ? (premiumDue += 70) : (premiumDue += 50);
		}
		cout << "\n your premium is :" << premiumDue << endl;
		return 0;
	}
}

c)
Based on the program defined above, you are now required to introduce a function, which implements the behaviour defined from line 6 to Line 9. The function should be declared as follows.
It should be called userInput.
It should have void as its return type.
Should take (02) arguments: &driverAge and &claims (reference variables)
The function should be called from the main function.
The function prototype and implementation should be contained in the same file as the main function.

 
Answer
#include <iostream>
using namespace std;
void userInput(int & driverAge, int & claims);
int main() 
{
	int driverAge, claims;
	double premiumDue = 75.32;
	userInput(driverAge, claims);
	if (driverAge < 26) 
	{
		claims < 3 ? (premiumDue += 100) : (premiumDue += 170);

	}

	else if (driverAge < 70) 
	{
		cout << " 70 bractket";
		claims >= 3 ? (premiumDue += 70) : (premiumDue += 50);
	}

	cout << "\n your premium is :" << premiumDue << endl;
	return 0;
}


void userInput(int & driverAgeand, int & claims)
{
	cout << "Enter the driver age: ";
	cin >> driverAge;
	if ((driverAge < 16) || (driverAge > 70)) 
	{
		cout << "Invalid age please reenter";
	}
	else 
	{
		cout << "\nEnter the number of insurance claims the driver made in the last 3 years: ";
		cin >> claims;
		while ((claims < 0) || (claims > 5))
		{
			cout << "Invalid Number Enter value between 0 -5 ";
			cin >> claims;
		}
	}
}

d)
Define a class called Driver, which has the following:
Three private data members: int driverAge, int claims, float premiumDue.
A set of public member functions including:
userInput with an implementation similar to that of the function you have developed in Previous Qusetion Though, you can vary the return type and argument list to suit your needs.
A constructor function (with argument list of your choice).
A required setters and getters functions, anything else can be ignored for this question.




 
Answer
#include <iostream>
using namespace std;

Class Driver
{

private:
	int driverAge, claims;
	double premiumDue = 75.32;
public:
	
	Driver(float pDue= 75.32)
	{
		premiumDue = pDue;
	}

	void userInput(int driverAge, int claims)
	{
		cout <<"Enter the driver age: ";
		cin >> driverAge;
		if ((driverAge < 16) || (driverAge > 70)) 
		{
			cout << "Invalid age please reenter";
		}

		else 
		{
			cout << "\nEnter the number of insurance claims the driver made in the last 3 years: ";
			cin >> claims;
			while ((claims < 0) || (claims > 5))
			{
				cout << "Invalid enter value between 0 -5 ";
				cin >> claims;
			}
		}
	}
}

Learn Java By Example

Java Exercise for
Class, Inheritance, Interfaces, Packages, Access Modifiers, Constant in Java

Question 1
Interface Bill has a method calculate(float price,int unitsconsumed) .
class Mobile should implement method calculate(float price, int unitsconsumed) and calculate the bill amount of one mobile;
hint: bill amount =unit price * units consumed.

Answer


interface Bill 
{
	public float calculate(float price,int unitsconsumed);  
  
}

public class Mobile implements Bill
{
	public float calculate(float price,int unitsconsumed) //method override
	{
		float billAmount;
		billAmount=price* unitsconsumed;
		return billAmount;
	
	}

	public static void main(String arg[])
	{
		float tot;
		Mobile Mon1=new Mobile();
		tot=Mon1.calculate(10.2f,250);
		System.out.println("Your charge=" + tot);
	}
}

Question 2
Interface shape has a constant double type variable A=3.22;

class Circle has a method findArea(int r) to calculate the area of the circle. class circle implements interface shape and used A to calculate area.
hint :area= A*r*r
Answer

interface Shape
{
	final float A=(float)3.22;   
}
public class Circle implements Shape
{
	public float findArea(int r) 
	{
		float fArea;
		fArea=A*r*r;
		return fArea;	
	}

	public static void main(String arg[])
	{
		float area;
		Circle Cir1=new Circle();
		area=Cir1.findArea(7);
		System.out.println("Area=" + area);
	}
}


Question 3
Write a java program which has package studentinfo with a class called Student. The class student has a public method showData(String index, String firstname) which receives student index, student name as values and display them.
The application (out of studentinfo) which has class Main with main method imports class Student and call the method showData(String index, String firstname) to display one student information.
Answer
compile below and copy the Student.class into subfolader Student


package studentinfo;
public class Student
{
	public void showData(String index, String firstname) 
	{
		System.out.println(index +"\n"+ firstname);
	}
}
import studentinfo.Student;
public class Mystudent
{
	public static void main(String arg[])
	{
		Student s1=new Student();
		s1.showData("S0001","Peter");
	}
}


Question 4
Write a java program to add public class called Result which has a public method getResult(int mark) to the previous package studentinfo. This method receives a module mark of a student and display the status as “pass” or “fail”. [Pass mark is 50]
Answer

package studentinfo;
public class Result
{
	public void getResult(int mark)
	{
		String s1;
		if (mark <50)
			s1="Fail";
		else
			s1="Pass";
		System.out.println(s1);
	}
}

import studentinfo.Result;
public class Myresult
{
	public static void main(String arg[])
	{
		Result r1=new Result();
		r1.getResult(60);
	}
}

Question 5
Write a java program which has package info with a class called Item. The class Item has a static variable price =10. The application (out of info package) which has class Bill imports class Item. The method calculateBill(int quantitybought) of the class Bill used value of item price to calculate the bill amount of the item.
Hint: bill amount=price * quantity bought
Use the class Menu with main method to call method calculateBill(int quantitybought).

Answer

package Inventory;

public class Item
{
	public static int price=10;
}


import Inventory.Item;
public class Bill1
{

	public void calculateBill(int quantitybought)
	{
		float tot=Item.price*quantitybought;
		System.out.println("Amount:" + "\t"+ tot);
	}
	public static void main(String arg[])
	{
		Bill1 b1=new Bill1();
		b1.calculateBill(25);		
	}
}


CPP Questions and Answers 2

Learn C++ with Examples

A private telecommunication company generates monthly mobile bills for their customers. The bill includes Bill Number, Monthly Units Consumed, Charge per Unit, Monthly Rental Amount and Final Bill Amount. Assume that the monthly rental is fixed for all the bills. Write an Object-Oriented program to perform the following operations using necessary functions. Each operation requires a separate function in the program. (Hint: Final bill Amount=(Monthly Units Consumed * Charge per Unit)+ Monthly Rental Amount.

i) Input data for bill number, monthly units consumed, Monthly Rental Amount and Charge per unit of two bills.
ii) Calculate the final amount of each bill.
iii) Output the final bill amount of each bill.


#include <iostream >
using namespace std;
class Bill
{
protected:
 string bill_no;
 int unit_consume;
 double charge_per_unit;
public:
 static double monthly_rental;

 Bill(string b_no, int unit_con, double charge)
 {
  bill_no = b_no;
  unit_consume = unit_con;
  charge_per_unit = charge;
 }
 double calc_amount()
 {
  return (unit_consume * charge_per_unit) + monthly_rental;
 }
 void bill_print()
 {
  cout << "Bill No:" << bill_no<<"\t";
  cout << "Unit Consumed:" << unit_consume<<"\t";
  cout << "Charge Per Unit:" << charge_per_unit<<"\t";
  cout << "Monthly Rental:" << monthly_rental << "\t";
  cout << "Amount:" << calc_amount()<<"\n";

 }

};
double Bill::monthly_rental = 1500.00;
int main()
{
 Bill b1("A001", 10, 150.00);
 b1.bill_print();
 Bill b2("A002", 16, 200.00);
 b2.bill_print();
}

An Object-oriented application has two classes. They are class Product and class Electronic_Product. The class Product has attributes Price of the product and Quantity produced. The class Electronic_Product has an attribute Tax Rate.
Each class uses own function to assign data for given attributes. The class product has function Calculate() which calculates the total value of a product. Total value of the product =price of the product * quantity produced.
The class Electronic_Product overrides the function Calculate of class Product to calculate the Tax value of an Electronic_Product.
Tax value of the electronic product=price of the electronic product * tax rate of the electronic product.
Write an object oriented program which perform following operations.

i) Set price quantity produced and Tax rate of one electronic product.
ii) Calculate Tax Value of the electronic product.

#include <iostream >
using namespace std;
class Product
{
protected:
 double Price;
 int Quantity;
public:
 void setPrice(double p)
 {
  Price = p;
 }
 void setQuantity(int q)
 {
  Quantity = q;
 }
 virtual double Calculate()
 {
  return Price * Quantity;
 }
 void Display()
 {
  cout << "Price:" << Price << "\t";
  cout << "Quantity:" << Quantity << "\t";
  cout << "Calculate:" << Calculate() <<"\n";
 }
};

class Electronic_Product :public Product
{
protected:
 double Tax_Rate;
public:
 void setTaxRate(double tx)
 {
  Tax_Rate = tx;
 }
 double Calculate()
 {
  return Price * Tax_Rate/100;
 }
};
int main()
{
 Product p;
 p.setPrice(25);
 p.setQuantity(10);
 p.Display();
 Electronic_Product ep;
 ep.setPrice(100);
 ep.setQuantity(20);
 ep.setTaxRate(5);
 ep.Display();
}

Some more examples for inheritance, Polymorphism (Early binding)

#include <iostream >
class Animals
{
protected:
 int no_legs;
 int no_tails;
public:
 Animals()
 {
  no_legs = 4;
  no_tails = 1;
 }
 void animalSound()
 {
  cout << "animal makes sound..." << "\n";
 }
 void display()
 {
 cout << "No of legs :" << no_legs << " No of Tails" << no_tails <<"\n";
 }

};
class Cat :public Animals
{
public:
 void animalSound()
 
  cout << "Cat says mews mews..." << "\n";
 }

};

class Crow :public Animals
{
public:
 void animalSound()
 {
  cout << "crow says says ca..ca.ca..." << "\n";
 }
 Crow()
 {
  no_legs = 2;
 }

};
int main()
{
 Animals a1;
 a1.animalSound();
 a1.display();
 Cat c1;
 c1.animalSound();
 c1.display();
 Crow cc1();
 cc1.animalSound();
 cc1.display();
}

A class customer has customer number and name. The function writeData() writes number and name to file "customer". The function readData() reads and displays customer name according to the customer number.
Write an object oriented program to
i)Write customet number and name to the file "customer"
ii) Read and display the customer name when number is input.


#include <iostream>
#include <fstream>

using namespace std;
class customer
{ 
    fstream mfile;
public:  
    customer()
    {
        mfile.open("c:\\ganesh\\customer" );
    }
 
    void writeData(string custcode,string custname)
    {
        mfile << custcode + "," +custname<<endl; 
    }
   void readData(string xx)
    {
       string x,t;

       mfile.seekg(0);
       while (mfile.eof() != true)
       {
           mfile >> x;
           t = x.substr(0, 4);
          if (t == xx)
           {
               cout <<x;
               cout <<endl;
           } 
       }         
    }
    ~customer()
    {
        mfile.close();
    }
};
                    

int main() 
{   
    customer c1;
    c1.writeData("C001","Peter");
    c1.writeData("C002", "David");
    c1.writeData("C003", "White");
    c1.writeData("C004", "Black");
    c1.readData("C002");
}

CPP Basics Questions and answers


C++ Questions and Answers

Learn By Examples

Question 1
Write a C++ program to input three marks and print Total, Average, and Pass or Fail (average<40 is fail)

Answer
#include <iostream>
using namespace std; 

int main()
{
int m1, m2, m3,temp,total;
float average;
char grade;
cout << "Enter Marks 1?";
cin >> m1;
cout << "Enter Marks 2?";
cin >> m2;
cout << "Enter Marks 3?";
cin >> m3;
total = m1 + m2 + m3;
average = total / 3;
if (average > 40)
grade = 'P';
else
grade = 'F';
cout << "marks 1:" << m1 << "\tMarks 2:" << m2 << "\tMarks 3:" << m3<<endl;
cout<< "Total =" << total << "\tAverage=" << average << "\tGrade=" << grade<<endl;
return 0;
}

Question 2
Write a C++ program to input a radius of a Circle and print the area.



Answer 1
#include <iostream>
using namespace std; 

int main()
{
const float pi = 22.0 / 7.0;
float radious,area;
cout << "Enter a radious of a Circle?";
cin >> radious;
radious = float(radious);
area = pi * radious * radious;
cout << "Radious :" << radious<<endl;
cout << "Area :" << area << endl;;
return 0;
}

Answer 2
By Using OOP concepts.

#include <iostream>
using namespace std;

class MCircle
{
float  rr;

public:
//defualt constructor;
MCircle()
{
rr = 1.0;
}
//constructor with parameter
MCircle(int r)
{
rr = r;
}
MCircle(float r)
{
rr = r;
}


void setR(float r)
{
rr = r;
}

int gerR()
{
return rr;
}

double FindArea()
{
double area;
const float pi = 22.0 / 7.0;
area = pi * rr * rr;
return area;
}
};



int main()
{
int r;
MCircle c1, c2; //two different object
cout << "Enter radious for a circle" << endl;
cin >> r;
c1.setR(r);
cout << "Circle area=" << c1.FindArea() << endl;
cout <<"radious of c1:"<< c1.gerR() << endl;
cout << "Test constructor" << endl;
MCircle r2; //create object by calling default Constructor
cout <<"Area of the Circle"<< r2.FindArea() << endl;
}


Question  3
Write a C++ program to print prime numbers between 1 and 100.

Answer
#include <iostream>
using namespace std; 

int main()
{
int x, y;
bool p;
x = 2;
while (x <= 100)
{
p = true;
y = 2;
do
{
if (x % y == 0)
p = false;
y = y + 1;
} while (y < x);
if ((p == true) || (x==2))
cout << x<<endl;
x = x + 1;
}
return 0;
}

Question  4
Write a C++ program to input 3 numbers and print those numbers in an ascending order.

Answer 1
#include <iostream>
using namespace std; 

int main()
{
int n1, n2, n3,temp;
cout << "Enter first number?";
cin >> n1;
cout << "Enter second number?";
cin >> n2;
cout << "Enter third number?";
cin >> n3;
if (n1 > n2)
{
temp = n1;
n1 = n2;
n2 = temp;
}
if (n2 > n3)
{
temp = n2;
n2 = n3;
n3 = temp;
}
if (n1 > n2)
{
temp = n1;
n1 = n2;
n2 = temp;
}
cout << n1 << "\t"<<n2 << "\t" << n3;
return 0;
}

Answer 2
Using a Function with call by reference parameter

#include <iostream>
using namespace std;


void swap(int &n1, int &n2);
int main()
{
    int n1, n2, n3, temp;
    cout << "Enter first number?";
    cin >> n1;
    cout << "Enter second number?";
    cin >> n2;
    cout << "Enter third number?";
    cin >> n3;
    if (n1 > n2)
    {
        swap(n1, n2);
    }

    if (n2 > n3)
    {
        swap(n2, n3);
    }

    if (n1 > n2)
    {
        swap(n1, n2);
    } 
    cout << n1 << "\t" << n2 << "\t" << n3;
    return 0;
}
//Function for call by reference
void swap(int& n1, int& n2)
{
    int temp;
    temp = n1;
    n1 = n2;
    n2 = temp;
}

Question  5

The class Employee has attributes employee number, employee basic salary. The constructor is used assign number and basic salary of an employee. The function display() displays number and name of the employee. The destructor is used to release the memory.  write an object oriented program in c++.

Answer


#include <iostream>
using namespace std;
//Pointers in C++

class Employee
{
string *num=new string();
string *name=new string();
float *salary=new float();
public:
Employee()
{
*num = "00000";
*name ="";
*salary = 0.0;
}
Employee(string num1, string name1, float sal)
{
*num = string(num1);
*name =string(name1);
*salary =sal;
}
void Display()
{
cout << "Number :" << *num << "\tName:" << *name << "\tSalary:" << *salary<<endl;
}

~Employee()
{
delete num;
delete name;
delete salary;

}

};

int main()
{
Employee e1("00001","Gannesh",7500.00);
e1.Display();
Employee e2("00002", "Nanthan", 17500.00);
e2.Display();
}

Question  6

A shop sells apples boxes for their customers. The Apple box has number of apples and all the apples in a particular box have the same price. Each apple box has different number of apples. Calculate() function calculates the total value of the apple box and Display() function display the details of the apple box.Write an object oriented program.


Answer

#include <iostream>
using namespace std;
class AppleBox
{
int num;
float price;
public:
AppleBox()
{
num = 0;
price = 0.0;
}
AppleBox(int n, float p)
{
num = n;
price = p;
}

double Calculate()
{
return num * price;
}
void Display()
{
cout << "Num of Apples:" << num << "\tPrice :" << price << "\tTotal value :" << Calculate()<<endl;
}
};
int main()
{
AppleBox a1(23,40.00);
a1.Display();
AppleBox a2(25, 60.50);
a2.Display();

}


Question  6

In a hotel, rooms are given for their customers. Every room has a room price for a day and number of days used. But luxury room has a service charge additionally and it is varied for each luxury room. you should identify classes, member of each class and relationship between classes.  (set price for a day, number of days used and service charge. Calculate and display the total charge )



Answer

#include <iostream>
using namespace std;
class Room
{
protected:
float roomPrice;
int dayUsed;
public:
void setRoomPrice(float r)
{
roomPrice=r;
}
void setDayUsed(int d)
{
dayUsed = d;
}
double totalCharged()
{
return roomPrice * dayUsed;
}
void Display()
{
cout << "Normal Room Days Used :" << dayUsed << "\tRate:" << roomPrice << "\tTotal Amt :"<<totalCharged() << endl;
}

};

class LuxuryRoom :public Room
{
float servicedCharge;
public:
void setServiced(float s)
{
servicedCharge = s;
}
double totalCharged()
{
return (dayUsed * roomPrice) + servicedCharge;
}
void Display()
{
cout << "Normal Room Days Used :" << dayUsed << "\tRate:" << roomPrice <<"\tService:"<<servicedCharge<< "\tTotal Amt :" << totalCharged() << endl;
}

};

int main()
{
Room r1;
r1.setDayUsed(5);
r1.setRoomPrice(1500.00);
r1.Display();
LuxuryRoom lr;
lr.setDayUsed(10);
lr.setRoomPrice(5000.00);
lr.setServiced(1200.00);
lr.Display();
}


JSON JavaScript Object Notation

JSON is text, written with JavaScript object notation. It is used to transmit data between a server and web application, as an alternative to XML.

Javascript coding with a function is given below to read a text with JSON format, and print it in a table format.


<!DOCTYPE html>
<html>
<body>

<h2>JSON</h2>

<p id="demo"></p>

<script>

var text = '{"mydata":[' +
'{"firstName":"John","lastName":"Doe","age":40 },' +
'{"firstName":"Anna","lastName":"Smith","age":28 },' +
'{"firstName":"Appu","lastName":"Ganesh","age":40 },' +
'{"firstName":"Ganesh","lastName":"Pradhyumn","age":0 },' +
'{"firstName":"Peter","lastName":"Jones","age":30}]}';

function mytable(txt)
{
var mylist,i;
obj = JSON.parse(txt);
mylist="";
mylist="<table border=2 style='border-color:brown; width: 50%;height:16px; '><tr>"
for (x in obj.mydata[0])
{
mylist=mylist+"<th style='padding: 15px;'>" + x +"</th>";
}
mylist=mylist +"</tr>";
for(i=0;i<=obj.mydata.length-1;i++)
{
mylist=mylist+"<tr>";
for (x in obj.mydata[0])
{
myc=eval("obj.mydata[i]." +x)
mylist=mylist+"<td style='padding: 15px;'>";
mylist=mylist+ myc +" ";
mylist=mylist+"</td>";
}
mylist=mylist+"</tr>";
}
mylist=mylist+"</table>";

document.getElementById("demo").innerHTML =mylist;
}
</script>
<div id="mytabdiv">
</div>
<input type="button" name="myc" value="click me" onclick="mytable(text)">
</body>
</html>

Java Assignments and Answers

Create a class called MyPoint, which models a 2D point with x and y cordinates. It contains:

  1. Two instance variables x(int) and y(int)
  2. A "no-arguments" contructor that contruct a point at (0,0).
  3. A constructor that constructs a point with given x and y cordinates.
  4. Getter and setter for the instance variables x and y.
    • setX(int x): set the value of x coordinate by passing the value.
    • setY(int y): set the value of y coordinate by passing the value.
    • getX(): return the value of x coordinate.
    • getY(): return the value of y coordinate.
  5. A method setXY() to set both x and y.
  6. A toString() method that returns a string description of the instance in the format "(x,y)"
  7. A method called distance(int x, int y) that returns the distance as a double value from this point to another point at the given (x,y) cordinate.
  8. An overloaded distance(MyPoint p) that returns the distance as a double value from this point to the given Mypoint instance p.

Distance of two points as calculates as given below.
distance of two points= sqrt((x1-x2)2 + (y1-y2)2)


Answer
 
class MyPoint
{
 int x;
 int y;

 public MyPoint()
 {
  this.x=0;
  this.y=0;
 }

 public MyPoint(int x,int y)
 {
  this.x=x;
  this.y=y;
 }

 public void setX(int x)
 {
  this.x=x;
 }

 public void setY(int x)
 {
  this.y=y;
 }
 
 
 public int getX()
 {
  return this.x;
 }

 public int getY()
 {
  return this.y;
 }

 public void setXY(int x,int y)
 {

  this.x=x;
  this.y=y;
 }

 public String toString()
 {
  return "(" + this.x + "," + this.y + ")";
 }


 public double distance(int x,int y)
 {
   
  double d1;
  d1=((this.x - x)*(this.x - x)) + ((this.y -y)* (this.y -y));
  return Math.sqrt(d1);
 }

 public double distance(MyPoint p)
 {
   
  MyPoint p1=new MyPoint();
  p1=p;
  double d1;
  d1=(this.x - p1.getX())*(this.x - p1.getX())+ (this.y - p1.getY())*(this.y - p1.getY());
  return Math.sqrt(d1);
 }
}

Create a class called MyCircle, which models a circle with a center(x,y) and a radius.The MyCircle class uses an instance of MyPoint class (created in the previous exercise) as its center.
The class should contain:

  1. Two private instance variables center(an instance of MyPoint) and radius(int).
  2. A constructor that construct a  circle with the given center's(x,y) coordinate and radius.
  3. An overloaded constructor that constructs a MyCircle by giving a MyPoint instance as center, and radius.
  4. Various getters and setter.
    • setCenter(MyPoint p): set the center coordinates by passing the MyPoint instance as center.
    • getCenter(): return the coordinate of the center point as MyPoint
    • setRadius(int r): set the value of radius by passing the value
    • getRadius(): return the value of the radius


Answer
 
class MyCircle
{
 private MyPoint center;
 private int radious;

 public MyCircle(int x,int y,int r)
 {
  center=new MyPoint();
  center.setXY(x,y);
  this.radious=r;
 }

 public MyCircle(MyPoint p,int r)
 {
  center=new MyPoint();
  center.setXY(p.getX(),p.getY());
  this.radious=r;
 }


 public void setCenter(MyPoint p)
 {
  center.setXY(p.getX(),p.getY());
  
 }

 public MyPoint getCenter()
 {
  return center;
  
 }

 public void setRadious(int r)
 {
  this.radious=r;
  
 }

 public int getRadious()
 {
  return radious;
  
 }

 public String toString()
 {
    
  return " Circle @ (" + center.getX() + "," + center.getY() + ")  radious = " + radious;
 }

 public double getArea()
 {
  return (22/7)*radious*radious;
 }

}



Create a public class called TestMyCirlce and do the following:

  1. Create point p1 using no argument constructor.
  2. Set the X,Y coordinates
  3. Create point p2 using two arguments constructor.
  4. Display the distance between p1 and p2 points.
  5. Display the distance between p1 and given point by passing x,y coordinates of that point.
  6. Create a circle c1 using two arguments constructor. Pass the point p1 as the center.
  7. Display the area of the circle.
  8. Create a circle c2 using three arguments constructor.
  9. Display the area of the cirlce c2.


Answer
 
public class TestMyCircle
{
 public static void main(String arg[])
 {
  MyPoint p1=new MyPoint();
  p1.setXY(50,50);
  MyPoint p2=new MyPoint(100,100);
  System.out.println("Distance between p1 and p2  : " + p1.distance(p2));
 System.out.println("Distance between p1 and given point 200,200 : " + p1.distance(200,200));
  MyCircle c1=new MyCircle(p1,50);
  System.out.println("Area of the circle - two argument : " + c1.getArea());
  MyCircle c2=new MyCircle(250,250,150); 
  System.out.println("Area of the circle -three arguement : " + c2.getArea());

  
 }
}