Showing posts with label variable. Show all posts
Showing posts with label variable. Show all posts

C and C++ Program for Swapping Two Numbers Without Third Variable

This post contains C and C ++ programs for swapping two given numbers without using any temporary variable. Only the two variables are required, not a third.

C Program
#include<stdio.h>
void main()
{

C and C++ swapping numbers

The following are C and C++ programs to swap the values of two variables using a third variable.

C Program:
#include<stdio.h>
void main()
{
int x,y,temp;
printf("Enter the value of xand y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\n x= %d\n y = %d\n",x,y);
temp = x;
x= y;
y = temp;
printf("After Swapping\n x= %d\ny= %d\n",x,y);
}

Sizeof operator in C

Sizeof operator is a unary operator used in both C and C++ programming languages. This operator is used to get the size of a data type, variable, object of a class, structure variable etc in bytes. In some programs it may be necessary to use the size of certain variable or data type. Such situations often occur in file handling programs. But the size of data type may vary from machine to machine. In most of the 32 bit systems, int has a size of 4 bytes. But in some systems it is 2 bytes. So, if a program is written by assuming the size to be known, it will affect the portability of the program since a change in size of a data type may result in unexpected output. In such cases, the sizeof operator helps to obtain the size of data type or variable in bytes. The argument of sizeof can be a variable of primitive days types (int, char etc), an object (of class), a structure variable, union variable, pointer variables etc. The sizeof operator is very useful in dynamic memory allocation.

C program to show working of sizeof operator:

#include<stdio.h>

struct student

{

char name[5];

int roll;

int mysize;

};

main()
{
unsigned long int b;
printf("size of variable b: %d",sizeof b);
printf("\nsize of int:%d",sizeof(int));
printf("\nsize of float:%d",sizeof(float));
printf("\nsize of char:%d",sizeof(char));
printf("\nsize of long:%d",sizeof(long));
printf("\nsize of double:%d",sizeof(double));
printf("\nsize of short:%d",sizeof(short));
struct student s1;
s1.mysize=sizeof(s1.name)+sizeof(s1.roll)+sizeof(s1.mysize);
printf("\nSizeof structure student :%d",s1.mysize);
/*see the difference shown in size of structure */
printf("\nsize of structure student : %d",sizeof(struct student));
}

Output: