Tag Archives: Programming in C/C++

The sizeof Operator in C

The sizeof operator is used to determine the number of bytes required to store a value of a specific data type.

#include <stdio.h>

int main() {
    int result, int_array[10];
    double double_array[10];
    
    printf("size of int = %2d bytes \n", result=sizeof(int));
    printf("size of int_array[10] = %2d bytes \n", result=sizeof(int_array));
    printf("size of float = %2d bytes \n", result=sizeof(float));
    printf("size of double = %2d bytes \n", result=sizeof(double));
    printf("size of double_array[10] = %2d bytes \n", result=sizeof(double_array));
    printf("size of long double = %2d bytes \n", result=sizeof(long double));
    return 0;
}

The output is :

The sizeof operator in C

IDE: Xcode Version 6.1.1

Compiler: Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)

Operating system: OS X Yosemite Version 10.10.1 (64-bit kernel)

Processor: Intel Core 2 Duo (64-bit processor).

Pre-increment and post-increment operators in C

#include <stdio.h>

int main(void) {
	int a=0, b=1, c=-8;
	int result=0;
	printf("1. a=%2d, b=%2d, c=%2d, result=%2d\n", a, b, c, result);
	result=8+a++;
	printf("2. a=%2d, b=%2d, c=%2d, result=%2d\n", a, b, c, result);
	b++;
	printf("3. a=%2d, b=%2d, c=%2d, result=%2d\n", a, b, c, result);
	result=++b+3;
	printf("4. a=%2d, b=%2d, c=%2d, result=%2d\n", a, b, c, result);
	++b;
	printf("5. a=%2d, b=%2d, c=%2d, result=%2d\n", a, b, c, result);
	return 0;
}

a++ post increment (it increments the value of a after the operation is over)

++b  pre increment (it increments the value of b before the operation)

The output is:

Pre-increment and post-increment operators in C

Computing and displaying the cubes and the sums of cubes of the first 10 integers in C

#include <stdio.h>
#include <stdlib.h>
#define CUBE(x) ((x)*(x)*(x))
 
int main(void) {
	int i1, running_sum=0;
	i1=1;
	while (i1<=10)
	{       // running_sum=running_sum+CUBE(i1)  
		running_sum+=CUBE(i1);
		printf("%2d  :   cube=  %4d ;   running_sum=  %4d\n", i1, CUBE(i1) , running_sum);
		++i1;
	}
	return 0;
}

The above program computes and displays cubes and sums of cubes of the first 10 integers. This program also illustrates the use of while loop.
running_sum=running_sum+CUBE(i1)
e.g. for i1=1 the running_sum=0+1=1, for i2=2 the running_sum=1+8=9

The output is:

Computing and displaying cubes and sums of cubes of the first 10 integers in C