|
Preprocessor Sample source code in C C++
|
|
Write a program (source code) in c c++ that defines a
macro with one argument to compute the volume of a sphere. The program should
compute the volume for spheres of radius 1 to 10, and print the results in
tabular format. The formula for the volume of a sphere is ( 4.0 / 3 ) * pi * r3
where pi is 3.14159.
|
The program should define macro SUM with two arguments, x and y, and use SUM to
produce the output
The sum of 6 and 7 is 13
#define SUM( x, y ) ( ( x ) + ( y ) )
int main()
{
cout << "The sum of 6 and 7 is " << SUM( 6, 7 ) << endl;
return 0;
} |
| Write a program that uses macro MINIMUM2 to
determine the smallest of two numeric values. Input the values from the
keyboard. |
| Write a program that uses macro MINIMUM3 to
determine the smallest of three numeric values. Macro MINIMUM3 should use macro
MINIMUM2 defined in Exercise 17.6 to determine the smallest number. Input the
values from the keyboard. |
Write a program in c c++ that uses macro PRINT to print a string value
#define PRINT( s ) cout << ( s )
#define SIZE 20
int main()
{
char text[ SIZE ];
PRINT( "Enter a string: " );
cin >> text;
PRINT( "The string entered was: " );
PRINT( text );
PRINT( endl );
return 0;
}
Output will be
Enter a string: HELLO
The string entered was: HELLO
|
|
|
Write a program that uses macro PRINTARRAY to print an array of integers. The
macro should receive the array and the number of elements in the array as
arguments.
#include <iostream.h>
#include<iomanip.h>
#define PRINTARRAY( A, N )
for ( int i = 0; i < ( N ); ++i ) \ cout << setw( 3 ) << A[ i ]
#define SIZE 10 i
nt main()
{
int b[ SIZE ] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
cout << "The array values are:\n";
PRINTARRAY( b, SIZE );
cout << endl;
return 0;
}
|
Output
Th array values are: 2 4 6 8 10 12 14 16 18 20
|
Write a program in c c++ that uses macro SUMARRAY to sum the values in a numeric
array. The macro should receive the array and the number of elements in the
array as arguments.
#include < iostream.h>
#define SUMMARRAY( A, S ) for ( int c = 0; c < S; ++c ) \ 8 sum += A[ c ];
9 #define SIZE 10 10 11
int main()
{
int array[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, sum = 0;
SUMMARRAY( array, SIZE );
cout << "Sum is " << sum << endl;
return 0;
}
|