Embedded C Programming
1. Write an Embedded C program to multiply any number by 9 in the fastest manner.
This can be achieved by involving bit manipulation techniques - Shift left operator as shown below:
#include<stdio.h>
void main(){
int num;
printf(“Enter number: ”);
scanf(“%d”,&num);
printf(“%d”, (num<<3)+num);
}2. How will you swap two variables? Write different approaches for the same.
- Using Extra Memory Space:
int num1=20, num2=30, temp;
temp = num1;
num1 = num2;
num2 = temp;- Using Arithmetic Operators:
int num1=20, num2=30;
num1=num1 + num2;
num2=num1 - num2;
num1=num1 - num2;- Using Bit-Wise Operators:
int num1=20, num2=30;
num1=num1 ^ num2;
num2=num2 ^ num1;
num1=num1 ^ num2;- Using One-liner Bit-wise Operators:
int num1=20, num2=30;
num1^=num2^=num1^=num2;The order of evaluation here is right to left.
- Using One-liner Arithmetic Operators:
int num1=20, num2=30;
num1 = (num1+num2)-(num2=num1);Here the order of evaluation is from left to right.
3. Write a program to check if a number is a power of 2 or not.
We can do this by using bitwise operators.
void main (){
int num;
printf ("Enter any no:");
scanf ("%d", &num);
if (num & & ((num & num-1) == 0))
printf ("Number is a power of 2");
else
printf ("Number is not a power of 2");
}4. Write a program to print numbers from 1 to 100 without making use of conditional operators?
void main (){
int i=0;
while (100 – i++)
printf ("%d", i);
}5. Write a MIN macro program that takes two arguments and returns the smallest of both arguments.
#define MIN(NUM1,NUM2) ( (NUM1) <= (NUM2) ? (NUM1) : (NUM2) )
Comments
Post a Comment