Tampilkan postingan dengan label alpro. Tampilkan semua postingan

6.3. Membuat algoritma untuk menentukan nilai maksimum dari n bilangan.



Mencari rata-rata dari n bilangan bulat dengan menggunakan array.

 Flowchart:




#include< iostream.h >
class HitungRATA {
     friend ostream& operator<<(ostream&,HitungRATA&);
     friend istream& operator<<(istream&,HitungRATA&);
public:
    float rata();
private:
   int n;  //banyaknya data 
   int A[20];//aray untuk menyimpan data 
};

istream& operator<<(istream& in,HitungRATA& a);
{
   cout<<"banyaknya data :";
   in>>a.n;
   for(int i=0;i
  {

             cout<<"masukkan data ke-:"<>";
    in>>a.A[i];
}
   return in;
}
float HitungRATA::rata()
{
   float total=0;
   for(int i=0;i
   raturn(total/n);
}

ostream& operator<<(ostream& out,HitungRATA& a);{
   out<<"Rata-rata dari"<
     <
   return out;
}

main(){
   HItung RATA run;
   cin>>run;
   cout<
  return 0;
}










Menghitung Nilai x(pangkat) y secara Rekursif

Flowchart :


 
Program C++ :


#include < cstdlib >
#include < iostream >


using namespace std;


class Pangkat{
friend istream& operator>>(istream&, Pangkat&);
friend ostream& operator<<(ostream&, Pangkat&);
public:
Pangkat();
int proses(int x,int y);
int output();
private:
int x,y,i;
int hasil;
};
Pangkat::Pangkat() {
cout<<"mencari X pangkat Y"<}
istream& operator>>(istream& in, Pangkat& masukan){
cout<<"masukan x:";
in>>masukan.x;
cout<<"masukan y:";
in>>masukan.y;
}
int Pangkat::proses(int x, int y){
if(y==1)
return x;
else if (y==0)
return 1;
else
return x*proses(x,y-1);
}
int Pangkat::output(){
hasil=proses(x,y);
cout<<"Maka hasilnya adalah:"<return hasil;
}
int main()
{
Pangkat X;
cin>>X;
X.output();
cout<
cout<<"Created by : Aditya Sumantri ";
system ("Pause");
return EXIT_SUCCESS;
}

Kasus 3.5 Konversi Hari


Konversikan hari ke 1 adalah hari senin sampai dengan hari ke-7 adalah hari minggu


Flowchart :



Program C++ :


#include< iostream.h >

#include< conio.h >

using namespace std;

main(){

int hari_keberapa;
char *hari;
cout<<"Masukkan hari ke-";cin>>hari_keberapa;

switch(hari_keberapa){
case 1: strcpy(hari, "Senin");break;
case 2: strcpy(hari, "Selasa");break;
case 1: strcpy(hari, "Rabu");break;
case 1: strcpy(hari, "Kamis");break;
case 1: strcpy(hari, "Jumat");break;
case 1: strcpy(hari, "Sabtu");break;
default: strpy(hari, "Minggu");break;
}

cout<<"Hari ke-"<

return 0;
}

Kasus 3.4 Konversi Nilai.

Flowchartnya :




Program C++ :
#include < cstdlib >
#include  < iostream >

using namespace std;

class NILAI{
      public:
            
             void konversikan();
            
     
private:
        float nilai;
       
};

void NILAI::konversikan(){
     cout<<"\n\n \t\t KONVERSI NILAI";
    cout<<"\n\nmasukkan nilai = ";cin>>nilai;
    if((nilai>0)&&(nilai<=20))
    cout<<"Nilai E"<
    else if((nilai>20)&&(nilai<=40))
    cout<<"Nilai D"<
    else if((nilai>40)&&(nilai<=60))
    cout<<"Nilai C"<
    else if((nilai>60)&&(nilai<=80))
    cout<<"Nilai B"<
    else if((nilai>80)&&(nilai<=100))
    cout<<"Nilai A"<
    else
    cout<<"salah memasukkan angka (angka>100)"<
}



int main(int argc, char *argv[])
{
    pick:
    NILAI;
    int q;
    cout<<"======================PILIHAN====================="<
    cout<<"1. Konversi nilai"<
    cout<<"2. Keluar/Exit"<
    cout<<"masukkan pilihan anda = ";cin>>q;
   
    switch(q){
              case 1: ku.konversikan();goto pick;
              break;
              case 2: return EXIT_SUCCESS;
              break;
             
              default: cout<<"\n\n \t\t PILIHAN SALAH"<
              }
system("pause");
return EXIT_SUCCESS;

}



Kasus 3.3.

Carilah akar-akar persamaan kuadrat.

Analisis :
Persamaan kuadrat adalah persamaan dengan bentuk umum Ax2 + Bx + C = 0, dan tentu saja dengan A ¹ 0. Akar persamaan kuadrat diperoleh dengan rumus :



Bila B2 -4AC < 0 akan diperoleh akar imajiner.


Input : koefisien A, B dan C bilangan real
   Proses : ada tiga alternatif pilihan dari harga   Yaitu harganya 0, positif atau negatif
Output : Nilai akar berdasarkan rumus

Raptornya :



Bahasa C++ :

#include < iostream >
#include < string >
#include < math.h >
using namespace std;
int main()
{
   string raptor_prompt_variable_zzyz;
   int a,b,c;
   float disk,x1,x2;

   raptor_prompt_variable_zzyz ="masukan nilai a";
   cout << raptor_prompt_variable_zzyz << endl;
   cin >> a;
   raptor_prompt_variable_zzyz ="masukan nilai b";
   cout << raptor_prompt_variable_zzyz << endl;
   cin >> b;
   raptor_prompt_variable_zzyz ="msukan nilai c";
   cout << raptor_prompt_variable_zzyz << endl;
   cin >> c;
   disk =(b*b)-(4*a*c);
   if (disk>0)
   {
      x1 =-b+sqrt(disk)/2*a;
      x2 =(-b)-sqrt(disk)/2*a;
      cout << x1 << endl;      cout << x2 << endl;   }
   else
   {
      if (disk==0)
      {
         x1 =-b/2*a;
         x2 =x1;
         cout << x1 << endl;         cout << x2 << endl;      }
      else
      {
         cout << "akar imajiner" << endl;      }
   }

system("pause");
   return EXIT_SUCCESS;
}



Kasus 3.2.
Menentukan bilangan terbesar antara 3 bilangan bulat.

Analisis
   Input : misalkan x, y dan z, semua integer
   Proses : kita harus membandingkan ketiga bilangan tersebut (caranya?)
   Output : bilangan terbesar



Flowchart :

Program c++:

#include < cstdlib >
#include < iostream >

using namespace std;

int main(int argc, char *argv[])
{
   int a,b,c;
   cout<<"masukkan nilai a: ";cin>>a;
   cout<<"masukkan nilai b: ";cin>>b;
   cout<<"masukkan nilai c: ";cin>>c;
   if (a>b)
   {
   cout<<"bilangan terbesar adalah :"<
   else
   {
   if (a>c)
   {cout << "bilangan terbesar adalah :"<
   else
   {
   if (b>c)
   {
   cout << "bilangan terbesar adalah :"<
   else    
   {
   if (b>a)
   {
   cout << "bilangan terbesar adalah :"<
   else
   {
   cout << "bilangan terbesar adalah: "<
   }
   }
   }
   
    system("PAUSE");
    return EXIT_SUCCESS;


Kasus 3.1.
Tentukanlah bilangan terbesar antara dua bilangan bulat.

Analisis :
   Input : misalkan A dan B, keduanya integer
   Proses : bandingkan A dan B
        Jika A > B maka A terbesar (output)
        Sebaliknya B terbesar (output)




#include < iostream.h >
 main()
{
   int a,b;
   cout<<"Masukkan bilangan pertama: ";
   cin>>a;
   cout<<"Masukkan bilangan kedua: ";
   cin>>b;
   if(a>b)




Counting

Problem

Given a set of n students' examination marks (in the range 0 to 100) make a count of the number of students that passed the examination. A pass is awarded for all marks of 50 and above.


Algorithm development
Counting mechanisms are very frequently used in computer algorithms. Generally a count must be made of the number of items in a set which possess some particular property or which satisfy some particular condition or conditions. This class of problems is typified by the "examination marks" problem.

As a starting point for developing a computer algorithm for this prob­lem we can consider how we might solve a particular example by hand.

Suppose that we are given the set of marks
55, 42, 77, 63, 29, 57, 89


Current_count therefore becomes 4. Similarly when we get to the next mark (i.e. 89) the current_count of 4 must assume the role of previous_count. This means that whenever a new current_count is generated it must then assume the role of previous _count before the next mark is considered. The two steps in this process can be represented by



Before any marks have been examined the count must have the value zero. To complete the algorithm the input of the marks and the output of the number of passes must be included. The detailed algorithm is then as described below.




Algorithm description
1.    Prompt then read the number of marks to be processed.
2.    Initialize count to zero.           
3    While there are still marks to be processed repeatedly do
(a)    read next mark,
(b)    if it is a pass (i.e. >=50) then add one to count.
4.    Write out total number of passes.


Notes on design
1.    Initially, and each time through the loop, the variable count represents the number of passes so far encountered. On termination (when n) count represents the total number of passes in the set. Because i is incremented by 1 with each iteration, eventually the condition iwill be violated and the loop will terminate.
2.     It was possible to use substitution to improve on the original solution to the problem. The simplest and most efficient solution to a problem is usually the best all-round solution.
3.    An end-of-line test is included to handle multiple lines of data.


Latihan Individu ALPRO Minggu ke-2

1. Buatlah algoritma dan program untuk mencari titik tengah sebuah garis yang ujung titiknya adalah A(x1,y1) dan B(x2,y2).

2. Buatlah algoritma dan program untuk memisahkan bilangan integer yang kurang dari 1000 menjadi komponen- komponennya. Sebagai contoh :
                        127 = 1 ratusan + 2 puluhan + 7 satuan 


3. Buatlah algoritma dan program untuk menghitung determinan matriks berordo 2x2





Overviews of Computers and Programming in C
In developed countries, life in the twenty-first century is conducted in a veritable sea of computers. From the coffeepot that turns itself on to brew your morning coffee to the microwave that cooks your breakfast to the automobile that yon drive to work to the automated teller machine you stop by for cash, virtually every aspect of your life depends on computers. These machines which receive, store, process, and output information can deal with data of all kinds: numbers, text, images, graphics, and sound, to name a few.
The computer program's role in this technology is essential; without a list of instructions to follow, the computer is virtually useless. Programming languages allow us to write those programs and thus to communicate with computers.
You are about to begin the study of computer science using one of the most versatile programming languages available today: the C language. This chapter introduces you to the computer and its components and to the major categories of programming languages. 11 discusses how C programs are processed by a computer. It also describes a systematic approach to solving programming problems called tin-software development method and shows you how to apply it.

1.1 Electronic Computers Then and Now

In our everyday life, we come in contact with computers frequently, .some of as using computers for creating presentations and other documents, tabulating data in spread¬sheets, or even having studied programming in high school. But it wasn't always this way. Not so long ago, most people considered computers to be mysterious devices whose secrets were known only by a few computer wizards.
The first electronic computer was built in the late 1930s bv Dr. John Atanasoff and Clifford Berrv at Iowa State University. Atanasoff designed his computer to assist graduate students in nuclear physics with their mathematical computations.
The first large-scale, general-purpose electronic digital computer, called the EN I AC, was completed in 1946 at the University of Pennsylvania with funding from the U.S. Army. Weighing 30 tons and occupying a 30-by-50-foot space, the ENIAC was used to compute bill lis tics tables, predict the weather, and make atomic energy calculations.
These earlv computers used vacuum tubes as their basic electronic component. Technological advances in the design and manufacture of electronic components led to new generations of computers that were considerably smaller, faster, and less expensive than previous ones.

1.2 Computer Hardware
Despite significant variations in cost, size, and capabilities, modern computers resemble one another in many basic ways. Essentially, most consist of the following components:
Main memory
Secondary memory, which includes storage devices such as hard dusks. CDs,
DVDs, and flash drives
Central processing unit
Input devices, such as keyboards. mouses, touch pads, scanners, joysticks
Output devices, such as monitors, printers, and speakers

1.3 Computer Software
In the previous section, we surveyed the components of a computer system, compo¬nents referred to collectively as hardware. We also studied the fundamental opera¬tions that allow a computer to accomplish tasks: repeated fetching and execution of instructions. In this section we focus on these all-important lists of instructions called computer programs or computer software. We will consider first the software that makes the hardware friendly to the user. We will then look at the various levels of computer languages in which software is written and at the process of creating and running a new program.
Operating System
The collection of computer programs that control the interaction of the user and the computer hardware is called the operating system (OS). The operating sys¬tem of a computer is often compared to the conductor of an orchestra, for it is the software that is responsible for directing all computer operations and managing all computer resources. Usually part of the operating system is stored permanently in a read-only memorv (ROM) chip so that it is available as soon as the computer is turned on. A computer can look at the values in read-only memory, but can¬not write new values to the chip. The ROM-based portion of the OS contains the instructions necessary for loading into memory the rest of the operating system code, which typically resides on a dusk. Loading the operating system into memory is called hooting the computer.
Application Software
Application programs are developed to assist a computer user in accomplishing specific tasks. For example, a word-processing application such as Microsoft Word or OpenOffice.org Writer helps to create a document, a spreadsheet application such as Microsoft Office Excel helps to automate tedious numerical calculations and to generate charts that depict data, and a database management application such as Microsoft Office Access or BASE assists in data storage and quick keyword-based access to large collections of records.
Computer users typically purchase application software on CDs or by down¬loading files from the Internet and install the software by copying the programs to the bard disk. When buying software, you must always check that the program vou are purchasing is compatible with both the operating system and the computer hardware you plan to use. We have already discussed some of the differences among operating systems; now we will investigate the different languages understood by different processors.
Computer Languages
Developing new software requires writing lists of instructions for a computer to execute. However, software developers rarely write in the language directly under¬stood by a computer, since this machine language is a collection of binary numbers. Another drawback of machine language is that it i.\s not standardized: There is s a different machine language for every type of CPU. This same drawback also applies.


1.4   The Software Development Method
Programming is a problem-solving activity. If you are a good problem solver, you have the potential to become a good programmer. Therefore, one goal of this book is to help you improve your problem-solving ability. Problem-solving methods are covered in many subject areas. Business students learn to solve problems with a systems approach while engineering and science students use the engineering and scientific method. Programmers use the software development method.

1.5    Applying the Software Development Method
Throughout this book, we use the first five steps of the software development method to solve programming problems. These example problems, presented as Case Studies. begin with a problem statement As part of the problem analysis, we identify the data requirements for the problem, indicating the problem inputs and the desired outputs. Next, we design and refine the initial algorithm. Finally, we implement the algorithm as a C program. We also provide a sample run of the pro¬gram and discuss how to test the program.
We walk you through a sample case study next. This example includes a running commentary on the process, which you can use as a model in solving other problems.


Chapter Review
1.  The basic coponents of a computer are main memory and secondary storag the CPU, and input and output devices.
2.     All data manipulated by a computer are represented digitally, as base 2 numbers  composed of strings of the digits 0 and 1.
3.   Main memory is organized into individual storage locations called memory cells.
■      Each memory cell has a unique address.
■      A memory cell is a collection of bytes; a byte is a collection of 8 hits.
■      A memory cell is never empty, hut its initial contents may he meaningless to your program.
■     The current contents of a memory cell are destroyed whenever new infor¬mation is stored in that cell.
■      Programs must be loaded into the memory of the computer before they can be executed.
■      Data cannot be manipulated by the computer until the)- are first stored in memory.
4.   Information in secondary storage is organized into files: program files and data files. Secondary storage provides a low-cost means of storing large quantities of information in semipermanent form.
5.  A CPU runs a computer program by repeatedly fetching and executing simple machine-code instructions.
6.  Connecting computers in networks allows sharing of resources—local resources on LANs and worldwide resources on a WAN such as the Internet
7.  Programming languages range from machine language (meaningful to a com¬puter) to high-level language (meaningful to a programmer).
8.  Several system programs are used to prepare a high-level language program for execution. An editor enters a high-level language program into a file. A compiler translates a high-level language program (the source program) into machine language (the object program). The linker links thus object program to other object files, creating an executable file, and the loader loads the exe¬cutable file into memory. All of these programs are combined in an integrated development environment (IDE).



Introduction
In order to choose a course of study and eventually a desirable career path, we may ask many important questions. Why would we choose this field? Will we be good at it? Will there be jobs for us when we finish our education? Will we enjoy our work? This chapter sheds some light on these types of questions for anyone contemplating a degree in computer science or a related field.

Reasons to Major in Computer Science

Almost everything we do is influenced by computing. Today's generation of college students, dubbed the Millennials, are not surprised by this statement. They have grown up with computers, the Internet, instant communication, and electronic entertainment. They embrace new technology and expect it to do fantastic things.
However, previous generations are not as comfortable with technology and try to solve problems without always thinking of technology first. Many people in the workforce resist the changes that technology requires. They often turn to the young­est employees to take over technology issues and to make choices that will have important consequences.
This difference among generations creates a great environment for bright and dedicated students to choose to major in computer science or a related field. The computer industry is one of the fastest growing segments of our economy and promises to continue to see growth well into the future. In order to be competitive, businesses must continue to hire well-trained professionals not only to produce high quality products for the present, but also to plan creative scientific and engineering advances for the future.


Computer Science

Computer science as a discipline encompasses a wide range of topics from theoreti­cal and algorithmic foundations to cutting-edge developments. The work computer scientists are trained to do can be arranged into three categories:
•      Designing and implementing useful software.
•      Devising new ways to use computers.
•      Developing effective ways to solve computing problems.









Computer Engineering

The computer engineering curriculum includes courses on the theories, prin­ciples, and practices of traditional electrical engineering as well as mathematics through the standard calculus sequence and beyond. This knowledge is then applied in courses dealing with designing computers and computer-based devices. In addi­tion, programming courses are required so that the computer engineer can develop software for digital devices and their interfaces.
Currently, an important area for computer engineers involves embedded sys­tems. This involves the development of devices that have software and hardware embedded in them such as cell phones, digital music players, alarm systems, medical diagnostic devices, laser surgical tools, and so on. The devices a computer engineer might work with are limitless as he or she applies his or her knowledge of how to integrate hardware and software system.

Information System

The information systems (IS) field focuses on integrating technology into businesses and other enterprises to manage their information in an efficient and secure man­ner. In this area, technology is viewed as an instrument for generating, processing, and distributing information. Therefore, the focus in this field is on business and organizational principles.
IS specialists must understand both technical and organizational factors, and must be able to help an organization determine how to use information and technol­ogy to provide a competitive edge. These professionals serve as a bridge between the technical community and the management community within an organization. They are called on to determine the best way to use technology, organize informa­tion, and communicate effectively.

Information Technology

An Information Technology (IT) program prepares students to meet the computer technology needs of business, government, healthcare, schools, and other organiza­tions. IT has its emphasis on the technology itself, more than on the information handled, the theory behind it, or how to design hardware or software. IT profes­sionals work with computer systems to ensure they work properly, are secure, are upgraded and maintained, and are replaced as appropriate.
Because computers have become integral parts of the work environment for all employees at all levels of the organization, many enterprises must maintain depart­ments of IT workers. Organizations of every kind are dependent on information technology on a daily basis and the need for qualified workers is great.


An Information Technology (IT) program prepares students to meet the computer technology needs of business, government, healthcare, schools, and other organiza­tions. IT has its emphasis on the technology itself, more than on the information handled, the theory behind it, or how to design hardware or software. IT profes­sionals work with computer systems to ensure they work properly, are secure, are upgraded and maintained, and are replaced as appropriate.
Because computers have become integral parts of the work environment for all employees at all levels of the organization, many enterprises must maintain depart­ments of IT workers. Organizations of every kind are dependent on information technology on a daily basis and the need for qualified workers is great.

Software Engineering
Software engineering (SE) is the discipline of developing and maintaining large software systems. These systems must behave reliably and efficiently, be affordable, and satisfy all requirements defined for them. SE seeks to integrate the theory of computer science and mathematics with the practical engineering principles devel­oped for physical objects.
An SE degree program is closely related to the computer science degree program, and they are usually offered within the same department. In fact, most computer science curricula require one or more software engineering courses. An SE degree can be considered a specialized degree within the confines of the field of computer science.

New Careers Constantly on the Horizon
It is clear that there will be a healthy need for computer professionals in the career paths that are known about today. For the student just starting to plan a career, there will surely he opportunities that have not even been imagined yet. The possibili­ties are amazing and the rewards are many.
One such window into the future can be seen in the work of Bruce Donald, a professor of Computer Science and of Biochemistrv at Duke University. Through bus research. Professor Donald has developed microscopic robots that can be con­trolled individually or as a group. These robots are measured in microns (millionths of a meter) and are almost 100 times smaller than any previous robotic designs of their kind. "Our work constitutes the first implementation of an untethered. multi-microrohotic system." Each robit can respond differently to the same single "global control signal" as voltages charge and discharge on their working parts. A budding computer scientist should set- many fantastic applications for these devices!
The student who chooses to major in computer science or a related field can look forward to challenging and interesting classes. The job market will lx- wide open upon graduation, with the assurance that such degrees will be highly market­able. A new employee or researcher will have opportunities to lx- at the forefront of innovative technology in a constantly changing world. The prospects are limited only by the imagination.


EXCHANGING THE VALUES OF TWO VARIABLE

Problem: Given two variable, a and b, exchange the values assigned to them.
Algorithm development
The problem of interchanging the values associated with two variables involves very fundamental mechanism that occurs in many sorting and data manipulation algorithms. To define the problem more clearly we will examine a specific example.
                Considers that the variables a and b are assigned values as outlined below. That is :




This means variable a contains the value 721, and variable b contains 463. Our tash is to replace the contents of a with 463, and contents of b with 721. We want to end up with the cinfuguration below :





To change the values of a variable we can use the assignment operator. Because we want a to assume the value currently belonging to b, and b too. We could perhaps make the exchange with the following assignment




Where “:=” is the assignment operator. In (1) “:=” causes the value stored in memory cell b to be copied into memory cell a. We started out with the configuration




Then after execution of the assignment a:=b we have




In executing step (2) a is not changed while b takes on the values that currently belongs to a.  The Problem arises because in making the assignment:



It is this value that we want b to finally assume. Our problem must therefore be stated more carefully as:


                     

New value  of b  := new value of a.
To solvethis exchange problem we need to find a way of not destroying “the old value of a”  when we make the assignment



The Steps to do this are:


After these:





It is this value that we need for assignment to b. We can therefore make the assignment             :




                         Now we see that a and b have now been interchanged as required. The exchange procedure can now be outlined.

Algorithm description
1.       Save the original value of a in t
2.       Assign to a the original value of b.
3.       Assign to b the original value of a that is stored in t



Notes on design

1.       The use of an intermediate temporary variable allows the exchange of two variables to proceed correctly.
2.       This example emphasizes that at any stage in a computation a variable always assumes that value dictated by the most recent assignment made to that variable.
3.       Working through the mechanism with a particular example can be a useful way to detecting design faults.
4.       A more common application of exchange involves two array elements (e.g. a[i] and a[j]).