Archive

Posts Tagged ‘swapping numbers’

Swapping two numbers in Python


Swapping two numbers in Python is damn easy. It doesn’t require another temporary variable or complicated assignments if the swapping to be done with in one line.

Swapping of two numbers in C with in one line Here

Swapping of two numbers in C using Bitwise operators Here

Both of the above programs do not require the additional temporary variable but I have to say, they are some what complicated but in case of Python just one assignment. Take a look at the below code

def swap(a,b):
	print 'Before swapping a=%s b=%s' %(a,b)
	a,b=b,a
	print 'Before swapping a=%s b=%s' %(a,b)

def main() :
	a=raw_input("Enter a:")
	b=raw_input("Enter b:")
	swap(a,b)

if __name__=='__main__' :
	main()

Program to extract source code from comment lines


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
char ch=’a’,ch1;
int count=1;
clrscr();
p=fopen(“cfile.c”,”r”);//this is the demonstration of comment line
if(p==NULL)
{
printf(“File not found”);
exit(1);
}
while(ch!=EOF)
{
ch=fgetc(p);
if(ch==’\n’)
count++;
else if(ch=='”‘) {
while((ch=fgetc(p))!=’\n’);
count++;
}
else if(ch==’/’)
{
if((ch1=fgetc(p))==’/’)
{
printf(“\nComment no %d:”,count);
while((ch=fgetc(p))!=’\n’&&ch!=EOF)
printf(“%c”,ch);
count++;
printf(“\n”);
continue;
}
else if(ch1==’*’)
{
printf(“\nComment %d :”,count);
while(ch!=EOF)
{
if((ch=fgetc(p))==’*’)
{
ch1=fgetc(p);
if(ch1==’/’)
break;
else
{
printf(“%c%c”,ch,ch1);
continue;
}
}
else if(ch==’\n’)
count++;
printf(“%c”,ch);
}
printf(“\n”);
}
}
}
getch();
}

Compiled on: Turbo C, gcc

Description : Extracts the program source code with out the comment lines in the given source file

program to swap two numbers with out using temporary variable with in one line


#include <stdio.h>
#include <conio.h>
int main(void)
{
int a , b;
printf(“Enter two integers: “);
scanf(“%d%d”,&a,&b);
printf(“Before swapping: a=%d,b=%d\n”,a,b);
a=(a+b)-(b=a); //This is just one line
printf(“After swapping: a=%d,b=%d”,a,b);
getch();
return 0;
}
compiled on :gcc logic :simple and tricky
If you have any doubts please add a comment

program to swap two numbers with out using temporary variable


#include < stdio.h >
#include < conio.h >
int main(void)
{
int a,b,i,j;
clrscr();
printf(“Enter two integers: “);
scanf(“%d%d”,&a,&b);
printf(“a=%d,b=%d\n”,a,b);
for(i=0;i<sizeof(int)*8;i++)
{
if((a&(1<<i))^(b&(1<<i)))
{
a=a^(1<<i);
b=b^(1<<i);
}
}
printf(“a=%d,b=%d”,a,b);
getch();
return 0;
}