Sunday, March 17, 2013

Programming Basics #2

Dynamic Memory Allocation

Very basic.  Good examples of 'for' loops and 'if/else if/else' statements:

1:  #include <iostream>  
2:    
3:  using namespace std;  
4:    
5:  int pause;  
6:    
7:  int main()  
8:  {  
9:       int num, total=0;  
10:       int *pDynam;  
11:    
12:       cout << "How many numbers to add: ";  
13:       cin >> num;  
14:       pDynam = new int[num];  
15:    
16:       cout << "Enter numbers below." << endl;  
17:    
18:       for(int i=0;i<num;i++)  
19:       {  
20:            cout << "Number " << i+1 << ": ";  
21:            cin >> pDynam[i];  
22:       }  
23:    
24:       cout << "That's it! You entered ";  
25:    
26:       for(int i=0;i<num;i++)  
27:       {  
28:            if (i == (num-1))  
29:                 cout << "and " << pDynam[i] << ".";  
30:            else if (i == (num-2))  
31:                 cout << pDynam[i] << " ";  
32:            else  
33:                 cout << pDynam[i] << ", ";  
34:       }  
35:    
36:       cout << endl << "Adding..." << endl;  
37:    
38:       for(int i=0;i<num;i++)  
39:       {  
40:            total = total + pDynam[i];  
41:       }  
42:    
43:       cout << "Total is: " << total << "." << endl;  
44:    
45:       cin >> pause;  
46:       return 0;  
47:  }  

The only new technique I used here was line 14, where the array size is dynamic (set at run-time instead of compile time) by the user.

Output:
 How many numbers to add: 5  
 Enter numbers below.  
 Number 1: 5  
 Number 2: 4  
 Number 3: 3  
 Number 4: 2  
 Number 5: 1  
 That's it! You entered 5, 4, 3, 2 and 1.  
 Adding...  
 Total is: 15.  

No comments:

Post a Comment