Imperative programming: Difference between revisions

Content deleted Content added
AnomieBOT (talk | contribs)
Rescuing orphaned refs ("cpl_3rd-ch2-37" from Computer program)
 
(48 intermediate revisions by 39 users not shown)
Line 1:
{{Short description|Type of programming paradigm in computer science}}
{{more citations needed|date=October 2011}}
{{Programming paradigms}}In [[computer science]], '''imperative programming''' is a [[programming paradigm]] of [[software]] that uses [[Statement (computer science)|statement]]s that change a program's [[state (computer science)|state]]. In much the same way that the [[imperative mood]] in [[natural language]]s expresses commands, an imperative program consists of [[command (computing)|command]]s for the [[computer]] to perform. Imperative programming focuses on describing ''how'' a program operates step by step (with general order of the steps being determined in [[source code]] by the placement of statements one below the other),<ref>{{Cite web |last=Jain |first=Anisha |date=2022-12-10 |title=Javascript Promises— Is There a Better Approach? |url=https://medium.datadriveninvestor.com/javascript-promises-is-there-a-better-approach-dd6a0a329131 |access-date=2022-12-20 |website=Medium |language=en |archive-date=2022-12-20 |archive-url=https://web.archive.org/web/20221220020247/https://medium.datadriveninvestor.com/javascript-promises-is-there-a-better-approach-dd6a0a329131 |url-status=live }}</ref> rather than on high-level descriptions of its expected results.
 
The term is often used in contrast to [[declarative programming]], which focuses on ''what'' the program should accomplish without specifying all the details of ''how'' the program should achieve the result.<ref>{{Cite web |title=Imperative programming: Overview of the oldest programming paradigm |url=https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |access-date=2022-05-03 |website=IONOS Digitalguide |date=21 May 2021 |language=en |archive-date=2022-05-03 |archive-url=https://web.archive.org/web/20220503083342/https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |url-status=live }}</ref>
 
==Imperative and proceduralProcedural programming==
[[Procedural programming]] is a type of imperative programming in which the program is built from one or more procedures (also termed [[subroutine]]s or functions). The terms are often used as synonyms, but the use of procedures has a dramatic effect on how imperative programs appear and how they are constructed. Heavy procedural programming, in which [[State (computer science)|state]] changes are localized to procedures or restricted to explicit arguments and returns from procedures, is a form of [[structured programming]]. FromSince the 1960s onwards, structured programming and [[modular programming]] in general have been promoted as techniques to improve the [[maintainability]] and overall quality of imperative programs. The concepts behind [[object-oriented programming]] attempt to extend this approach.
 
Procedural programming could be considered a step toward declarative programming. A programmer can often tell, simply by looking at the names, arguments, and return types of procedures (and related comments), what a particular procedure is supposed to do, without necessarily looking at the details of how it achieves its result. At the same time, a complete program is still imperative since it ''fixes'' the statements to be executed and their order of execution to a large extent.
Line 15:
From this low-level perspective, the program state is defined by the contents of memory, and the statements are instructions in the native machine language of the computer. Higher-level imperative languages use [[variable (programming)|variable]]s and more complex statements, but still follow the same paradigm. [[Recipe]]s and process [[checklist]]s, while not [[computer program]]s, are also familiar concepts that are similar in style to imperative programming; each step is an instruction, and the physical world holds the state. Since the basic ideas of imperative programming are both conceptually familiar and directly embodied in the hardware, most computer languages are in the imperative style.
 
[[Destructive assignment|Assignment statements]], in imperative paradigm, perform an operation on information located in memory and store the results in memory for later use. High-level imperative languages, in addition, permit the [[Evaluation (disambiguation)#Computer_science|evaluation]] of complex [[Expression (programming)|expressions]], which may consist of a combination of [[Arithmetic#Arithmetic operations|arithmetic operations]] and [[function (mathematics)|function]] evaluations, and the assignment of the resulting value to memory. Looping statements (as in [[while loop]]s, [[do while loop]]s, and [[for loop]]s) allow a sequence of statements to be executed multiple times. Loops can either execute the statements they contain a predefined number of times, or they can execute them repeatedly until some condition is met. [[Conditional (programming)|Conditional]] [[Branch (computer science)|branching]] statements allow a sequence of statements to be executed only if some condition is met. Otherwise, the statements are skipped and the execution sequence continues from the statement following them. Unconditional branching statements allow an execution sequence to be transferred to another part of a program. These include the jump (called ''[[goto]]'' in many languages), [[switch statement|switch]], and the subprogram, [[subroutine]], or procedure call (which usually returns to the next statement after the call).
 
Early in the development of [[high-level programming language]]s, the introduction of the [[block (programming)|block]] enabled the construction of programs in which a group of statements and declarations could be treated as if they were one statement. This, alongside the introduction of [[subroutine]]s, enabled complex structures to be expressed by hierarchical decomposition into simpler procedural structures.
Line 25:
 
The 1980s saw a rapid growth in interest in [[object-oriented programming]]. These languages were imperative in style, but added features to support [[object (computing)|objects]]. The last two decades of the 20th century saw the development of many such languages. [[Smalltalk]]-80, originally conceived by [[Alan Kay]] in 1969, was released in 1980, by the Xerox Palo Alto Research Center ([[PARC (company)|PARC]]). Drawing from concepts in another object-oriented language—[[Simula]] (which is considered the world's first [[object-oriented programming language]], developed in the 1960s)—[[Bjarne Stroustrup]] designed [[C++]], an object-oriented language based on [[C (programming language)|C]]. Design of [[C++]] began in 1979 and the first implementation was completed in 1983. In the late 1980s and 1990s, the notable imperative languages drawing on object-oriented concepts were [[Perl]], released by [[Larry Wall]] in 1987; [[Python (programming language)|Python]], released by [[Guido van Rossum]] in 1990; [[Visual Basic (classic)|Visual Basic]] and [[Visual C++]] (which included [[Microsoft Foundation Class Library]] (MFC) 2.0), released by [[Microsoft]] in 1991 and 1993 respectively; [[PHP]], released by [[Rasmus Lerdorf]] in 1994; [[Java (programming language)|Java]], by [[James Gosling]] ([[Sun Microsystems]]) in 1995, [[JavaScript]], by [[Brendan Eich]] ([[Netscape]]), and [[Ruby (programming language)|Ruby]], by Yukihiro "Matz" Matsumoto, both released in 1995. Microsoft's [[.NET Framework]] (2002) is imperative at its core, as are its main target languages, [[VB.NET]] and [[C Sharp (programming language)|C#]] that run on it; however Microsoft's [[F Sharp (programming language)|F#]], a functional language, also runs on it.
 
 
==Examples==
 
===Fortran===
[[FORTRAN]] (1958) was unveiled as "The IBM Mathematical FORmula TRANslating system." It firstwas compileddesigned correctlyfor inscientific 1958calculations, without [[String (computer science)|string]] handling facilities.<ref name="cpl_3rd-ch2-16">{{citeAlong with [[Declaration (computer programming)|declarations]], [[Expression (computer science)|expressions]], and [[Statement (computer science)|statements]], it booksupported:
* [[Array data structure|arrays]].
* [[subroutine]]s.
* [[For loop|"do" loops]].
 
It succeeded because:
* programming and debugging costs were below computer running costs.
* it was supported by IBM.
* applications at the time were scientific.<ref name="cpl_3rd-ch2-16"/>{{cite book
| last = Wilson
| first = Leslie B.
Line 38 ⟶ 45:
| page = 16
| isbn = 0-201-71012-9
}}</ref>
}}</ref> It was designed for scientific calculations, without [[String (computer science)|string]] handling facilities. Along with ''declarations'', ''expressions'' and ''statements'', it supported:
* [[Array data structure|arrays]].
* [[subroutine]]s.
* [[For loop|"do" loops]].
 
It succeeded because:
* programming and debugging costs were below computer running costs.
* it was supported by IBM.
* applications at the time were scientific.<ref name="cpl_3rd-ch2-16"/>
 
However, non IBM vendors also wrote Fortran compilers, but with a syntax that would likely fail IBM's compiler.<ref name="cpl_3rd-ch2-16"/> The [[American National Standards Institute]] (ANSI) developed the first Fortran standard in 1966. In 1978, Fortran 77 became the standard until 1991. Fortran 90 supports:
* [[Record (computer science)|records]].
* [[Pointer (computer programming)|pointers]] to arrays.
 
===COBOL===
[[COBOL]] (1959) stands for "COmmon Business Oriented Language." Fortran manipulated symbols. It was soon realized that symbols didn'tdid not need to be numbers, so strings were introduced.<ref name="cpl_3rd-ch2-24">{{cite book
| last = Wilson
| first = Leslie B.
Line 71 ⟶ 70:
}}</ref>
 
COBOL's development was tightly controlled, so dialects didn'tdid not emerge to require ANSI standards. As a consequence, it wasn'twas not changed for 2515 years until 1974. The 1990s version did make consequential changes, like [[object-oriented programming]].<ref name="cpl_3rd-ch2-25"/>
 
===Algol===
Line 83 ⟶ 82:
| isbn = 0-201-71012-9
}}</ref> Emerging from a committee of European and American programming language experts, it used standard mathematical notation and had a readable structured design. Algol was first to define its [[Syntax (programming languages)|syntax]] using the [[Backus–Naur form]].<ref name="cpl_3rd-ch2-19"/> This led to [[Syntax-directed translation|syntax-directed]] compilers. It added features like:
* block structure, where variables were local to their block.
* arrays with variable bounds.
* [[For loop|"for" loops]].
* [[Subroutine#Functions|functions]].
* [[Recursion (computer science)|recursion]].<ref name="cpl_3rd-ch2-19"/>
 
Algol's direct descendants include [[Pascal (programming language)|Pascal]], [[Modula-2]], [[Ada (programming language)|Ada]], [[Delphi (software)|Delphi]] and [[Oberon (programming language)|Oberon]] on one branch. On another branch there's [[C (programming language)|C]], [[C++]] and [[Java (programming language)|Java]].<ref name="cpl_3rd-ch2-19"/>
 
===BasicBASIC===
[[BASIC]] (1964) stands for "Beginner's All Purpose Symbolic Instruction Code." It was developed at [[Dartmouth College]] for all of their students to learn.<ref name="cpl_3rd-ch2-30">{{cite book
| last = Wilson
Line 100 ⟶ 99:
| page = 30
| isbn = 0-201-71012-9
}}</ref> If a student didn'tdid not go on to a more powerful language, the student would still remember Basic.<ref name="cpl_3rd-ch2-30"/> A Basic interpreter was installed in the [[microcomputers]] manufactured in the late 1970s. As the microcomputer industry grew, so did the language.<ref name="cpl_3rd-ch2-30"/>
 
Basic pioneered the [[Read–eval–print loop|interactive session]].<ref name="cpl_3rd-ch2-30"/> It offered [[operating system]] commands within its environment:
* The 'new' command created an empty slate.
* Statements evaluated immediately.
* Statements could be programmed by preceding them with a line number.
* The 'list' command displayed the program.
* The 'run' command executed the program.
 
However, the Basic syntax was too simple for large programs.<ref name="cpl_3rd-ch2-30"/> Recent dialects added structure and object-oriented extensions. [[Microsoft|Microsoft's]] [[Visual Basic]] is still widely used and produces a [[graphical user interface]].<ref name="cpl_3rd-ch2-31">{{cite book
Line 129 ⟶ 128:
| isbn = 0-201-71012-9
}}</ref> C is a relatively small language -- making it easy to write compilers. Its growth mirrored the hardware growth in the 1980s.<ref name="cpl_3rd-ch2-37"/> Its growth also was because it has the facilities of [[assembly language]], but uses a [[High-level programming language|high-level syntax]]. It added advanced features like:
* [[inline assembler]].
* arithmetic on pointers.
* pointers to functions.
* bit operations.
* freely combining complex [[Operators in C and C++|operators]].<ref name="cpl_3rd-ch2-37"/>
 
[[File:Computer-memory-map.png|thumb|right|Computer memory map]]
''C'' allows the programmer to control in which region of memory data is to be stored. ''Global variables'' and ''static variables'' require the fewest [[Clock signal|clock cycles]] to store. The ''[[call stack''|stack]] is automatically used for the standard variable [[Declaration (computer programming)|declarations]]. ''[[Manual memory management|Heap'']] memory is returned to a ''[[Pointer (computer programming)|pointer variable'']] from the [[C dynamic memory allocation|<code>malloc()</code>]] function.
 
* The ''global and static data'' region is located just above the ''program'' region. (The program region is technically called the ''text'' region. It's where machine instructions are stored.)
:* The global and static data region is technically two regions.<ref name="geeksforgeeks">{{cite web
| url = https://www.geeksforgeeks.org/memory-layout-of-c-program/
| title = Memory Layout of C Programs
| date = 12 September 2011
| access-date = 25 May 2022
| archive-date = 6 November 2021
| archive-url = https://web.archive.org/web/20211106175644/https://www.geeksforgeeks.org/memory-layout-of-c-program/
| url-status = live
}}</ref> One region is called the ''initialized [[data segment]]'', where variables declared with default values are stored. The other region is called the ''[[.bss|block started by segment]]'', where variables declared without default values are stored.
:* Variables stored in the ''global and static data'' region have their [[Memory address|addresses]] set at compile-time. They retain their values throughout the life of the process.
Line 169 ⟶ 172:
:* ''Local variables'' declared using the <code>static</code> prefix are also stored in the ''global and static data'' region.<ref name="geeksforgeeks"/> Unlike global variables, static variables are only visible within the function or block. Static variables always retain their value. An example usage would be the function <code>int increment_counter(){ static int counter = 0; counter++; return counter;}</code>
 
* The ''[[Stack-basedcall memory allocationstack|stack]]'' region is a contiguous block of memory located near the top memory address.<ref name="lpi-ch6-p121">{{cite book
|title=The Linux Programming Interface
|last=Kerrisk
Line 176 ⟶ 179:
|year=2010
|isbn=978-1-59327-220-3
|page=121}}</ref> Variables placed in the stack, ironically, are populated from top to bottom.<ref name="lpi-ch6-p121"/> A [[Call stack#STACK-POINTER|stack pointer]] is a special-purpose [[processor register|register]] that keeps track of the last memory address populated.<ref name="lpi-ch6-p121"/> Variables are placed into the stack via the ''assembly language'' PUSH instruction. Therefore, the addresses of these variables are set during [[Runtime (program lifecycle phase)|runtime]]. The method for stack variables to lose their [[Scope (computer science)|scope]] is via the POP instruction.
 
:* ''Local variables'' declared without the <code>static</code> prefix, including formal parameter variables,<ref name="lpi-ch6-p122">{{cite book
Line 187 ⟶ 190:
|page=122}}</ref> are called ''automatic variables''<ref name="cpl-ch1-p31"/> and are stored in the stack.<ref name="geeksforgeeks"/> They are visible inside the function or block and lose their scope upon exiting the function or block.
 
* The ''[[Manual memory management|heap'']] region is located below the stack.<ref name="geeksforgeeks"/> It is populated from the bottom to the top. The [[operating system]] manages the heap using a ''heap pointer'' and a list of allocated memory blocks.<ref name="cpl-ch1-p185">{{cite book
|title=The C Programming Language Second Edition
|last1=Kernighan
Line 292 ⟶ 295:
// Used to allow multiple source files to include
// this header file without duplication errors.
// See: https://en.wikipedia.org/wiki/Include_guard
// ----------------------------------------------
#ifndef GRADE_H
Line 411 ⟶ 415:
public:
STUDENT ( const char *name );
~STUDENT();
GRADE *grade;
};
Line 431 ⟶ 436:
// Nothing else to do.
// -------------------
}
 
STUDENT::~STUDENT()
{
// deallocate grade's memory
// to avoid memory leaks.
// -------------------------------------------------
delete this->grade;
}
</syntaxhighlight>
Line 453 ⟶ 466:
<< student->grade->numeric
<< "\n";
 
// deallocate student's memory
// to avoid memory leaks.
// -------------------------------------------------
delete student;
 
return 0;
}
Line 482 ⟶ 501:
==See also==
* [[Functional programming]]
* [[Comparison of programming paradigms]]
* [[Reactive programming]]
* [[History of programming languages]]
Line 499 ⟶ 517:
: ''Originally based on the article 'Imperative programming' by Stan Seibert, from [[Nupedia]], licensed under the [[GNU Free Documentation License]].''
 
{{Programming languageparadigms navbox}}
{{Types of programming languages}}
 
{{Authority control}}