AD1

Friday, 22 December 2017

Reverse words in a given string

Problem

https://practice.geeksforgeeks.org/problems/reverse-words-in-a-given-string/0

Solution

#problem link
# https://practice.geeksforgeeks.org/problems/reverse-words-in-a-given-string/0
#code
T=int(input())#Test cases
for t in range(0,T):#looping through all test cases
string=[x for x in input().split(".")]
print(*string[::-1],sep='.')
view raw T1.py hosted with ❤ by GitHub
 

Sunday, 17 December 2017

Key Pair
Problem :
 https://practice.geeksforgeeks.org/problems/key-pair/0
Solution
#code
T=int(input())#Test cases
for t in range(0,T):#looping through all test cases
N_X = [int(x) for x in input().split()]
flag=0
A=[int(y) for y in input().split()]#read elements separated by space
for a in range(N_X[0]):
if N_X[1]-A[a] in A:#if number complement found in A[] print yes
print("Yes")
flag=1
break
if(flag==0):
print("No")
view raw KeyPair.py hosted with ❤ by GitHub

Saturday, 23 September 2017

Count pairs with given sum

Problem :

Solution :

#include <iostream>
using namespace std;
int main()
{
int T;
cin>>T;
for(int i=0;i<T;i++)
{
int N,K;
int counter=0;
cin>>N>>K;
int array[N];
for(int j=0;j<N;j++)
{
cin>>array[j];
}
for(int m=0;m<N-1;m++)
{
for(int l=m+1;l<N;l++)
{
if(array[m]+array[l]==K)
{
counter++;
}
}
}
cout<<counter<<endl;
}
return 0;
}
view raw pairs.cpp hosted with ❤ by GitHub

Monday, 18 September 2017

Matrix Transpose

Given a 2D array A, your task is to convert all rows to columns and columns to rows.
Input:
First line contains 2 space separated integers, N - total rows, M - total columns.
Each of the next N lines will contain M space separated integers.
Output:
Print M lines each containing N space separated integers.
Constraints:
1N10
1M10
0A[i][j]100 where 1iN and 1jM

Solution

 
#include <iostream>
using namespace std;
int main()
{
int row,col;
cin>>row>>col;
int m[row][col];
int mt[col][row];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>m[i][j];
mt[j][i]=m[i][j];
}
}
for(int k=0;k<col;k++)
{
for(int l=0;l<row;l++)
{
cout<<mt[k][l]<<" ";
}
cout<<endl;
}
return 0;
}
view raw trans.cpp hosted with ❤ by GitHub

Saturday, 16 September 2017

Count frequency of each element in array

Write a program to count the frequency of each element in array , as example if we have 
int a[10]={5, 10, 2, 5, 50, 5, 10, 1, 2, 2};
the output should be 
number     frequency
5          3
10         2
2          3
50         1
1          1

#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int a[10]={5, 10, 2, 5, 50, 5, 10, 1, 2, 2};
int flag[10]={0};
//count frequency of each number
int counter=1;
for(int i=0;i<=9;i++)
{
for(int j=i+1;j<=9;j++)
{
if (a[i]==a[j]){counter++;flag[j]=1;}
}
if(flag[i]!=1){cout<<a[i]<<"\t"<<counter<<endl;}
counter=1;
}
return 0;
}
view raw freq.cpp hosted with ❤ by GitHub

Tuesday, 22 August 2017

Monk and Lucky Minimum

Problem
https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/monk-and-lucky-minimum-3/

Solution

#include <iostream>
#include <cstdlib>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char** argv) {
unsigned int T;
cin>>T;
unsigned long int occ=0;
for(unsigned int i=0;i<T;i++)
{
unsigned long int N;
cin>>N;
unsigned long int a[N];
for(long int j=0;j<N;j++)
{
cin>>a[j];
}
unsigned long int min=a[0];
for(long int l=0;l<N;l++)
{
if(a[l]<min){min=a[l];}
}
//compute minimum occurance
for(long int k=0;k<N;k++)
{
if(a[k]==min){occ++;}
}
if(occ%2==0){cout<<"Unlucky"<<endl;}
else {cout<<"Lucky"<<endl;}
occ=0;
}
return 0;
}
view raw lucky.cpp hosted with ❤ by GitHub

Friday, 18 August 2017

Micro and Array Update

Problem 
https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/micro-and-array-update/

Solution


#include <iostream>
#include <cstdlib>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char** argv) {
unsigned int T;
cin>>T;
for(unsigned int i=0;i<T;i++)
{
unsigned long int N,K;
cin>>N>>K;
unsigned long int a[N];
for(long int j=0;j<N;j++)
{
cin>>a[j];
}
unsigned long int min=a[0];
for(long int l=0;l<N;l++)
{
if(a[l]<min){min=a[l];}
}
if(K>min){cout<<K-min<<endl;}
else {cout<<0<<endl;}
}
return 0;
}

Friday, 14 July 2017

Maximum AND

Problem
https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/maximum-and/

Solution

#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int T;
long int A,B;
long int max=0;
cin>>T;
for(int i=0;i<T;i++)//input test cases
{
cin>>A>>B;//input A,B
for(int j=A;j<B;j++)// loop all pairs between A,B
{
for(int k=j+1;k<=B;k++)
{
if((k&j)>max){max=(k&j);}
}
}
cout<<max<<endl;
max=0;//reset max for next test case
}
return 0;
}
view raw maxand.cpp hosted with ❤ by GitHub

Wednesday, 12 July 2017

Toggle bits given range

Problem 
http://practice.geeksforgeeks.org/problems/toggle-bits-given-range/0

Solution

#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int t;
int N,L,R;
cin>>t;// test cases
for(int i=0;i<t;i++)
{
cin>>N>>L>>R;
for(int i=L-1;i<R;i++)
{
N^=1<<i;
}
cout<<N<<endl;
}
return 0;
}
view raw gr.cpp hosted with ❤ by GitHub


Tuesday, 11 July 2017

Monk and his Friend

Problem 

https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/monk-and-his-friend/

Solution

#include <iostream>
#include <cstdlib>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char** argv) {
long int N,P;
long int XOR;
int counter=0;
int t;
cin>>t;// test cases
for(int i=0;i<t;i++)
{
cin>>N>>P;
XOR=N^P;
for(int i=0;i<=31;i++)
{
if(XOR&(1<<i)){counter++;}
}
cout<<counter<<endl;
counter=0;
}
return 0;
}
view raw x.cpp hosted with ❤ by GitHub

Saturday, 8 July 2017

Monk and the box of cookies

Problem

https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/monk-and-the-box-of-cookies/

Solution

#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int t,N,b;
int p=0;
cin>>t;
int record[32];//record for every position
for(int i=0;i<t;i++)
{
for(int x=0;x<31;x++){record[x]=0;}//intialize records
cin>>N;
for(int j=0;j<N;j++)
{
cin>>b;
for(int k=0;k<31;k++)
{
if(b&(1<<k)){record[k]++;}//if position k has set bit , increment its record
}
}
int max=record[0];
for(int x=0;x<31;x++)
{
if(max<record[x]){max=record[x];p=x;}//find most occurring position has set bit
}
cout<<p<<endl;
}
return 0;
}
view raw monk.cpp hosted with ❤ by GitHub

Friday, 7 July 2017

The Great Kian

Problem
https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/the-great-kian/

Solution
#include <iostream>
#include <cstdlib>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char** argv) {
long long int n;
cin>>n;
long long int a[n];
long long int s1=0;
long long int s2=0;
long long int s3=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int j=0;j<n;j+=3)
{
s1+=a[j];
}
cout<<s1<<" ";
for(int j=1;j<n;j+=3)
{
s2+=a[j];
}
cout<<s2<<" ";
for(int j=2;j<n;j+=3)
{
s3+=a[j];
}
cout<<s3;
return 0;
}
view raw gk.cpp hosted with ❤ by GitHub



Little Jhool and psychic powers

Problem

https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/psychic-powers/

Solution


#include <iostream>
#include <cstdlib>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char** argv) {
string s;
cin>>s;
int i=0;
int sum=0;
int flag=0;
while(s[i]!='\0')// loop all elements
{
for(int j=i;j<=i+5;j++)// check every 6 consecutive numbers
{
sum+=s[j];
}
if(sum==288||sum==294)// if you found 6 consecutive ones or zeros (sum is ascii , because input is string)
{
flag=1;break;
}
i++;// move to next element
sum=0;//reset sum
}
if(flag){cout<<"Sorry, sorry!"<<endl;}
else if(flag==0){cout<<"Good luck!";}
return 0;
}

Count Digits

Problem 

https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/count-digits-1/

Solution

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char** argv) {
string s;
cin>>s;
int i=0;
int c[10]={0,0,0,0,0,0,0,0,0};
while(s[i]!='\0')
{
switch(s[i])
{
case 48:c[0]++;i++;break;
case 49:c[1]++;i++;break;
case 50:c[2]++;i++;break;
case 51:c[3]++;i++;break;
case 52:c[4]++;i++;break;
case 53:c[5]++;i++;break;
case 54:c[6]++;i++;break;
case 55:c[7]++;i++;break;
case 56:c[8]++;i++;break;
case 57:c[9]++;i++;break;
}
}
// print count of each digit
for(int j=0;j<=9;j++)
{
cout<<j<<" "<<c[j]<<endl;
} return 0;
}
view raw c.cpp hosted with ❤ by GitHub

Saturday, 17 June 2017

C program to left rotate an array

Write a program to left rotate an array by n position
Example
Input
Input 10 elements in array: 1 2 3 4 5 6 7 8 9 10
Input number of times to rotate: 3
Output
Array after left rotation: 4 5 6 7 8 9 10 1 2 3
Solution
#include <stdio.h>
#include <stdlib.h>
#define size 5
void rotate_array_left(int *array,int times)
{
int temp=0;
for(int x=0;x<times;x++)
{
temp=array[0];
for(int i=0;i<=size-2;i++)
{
array[i]=array[i+1];
}
array[size-1]=temp;
}
}
int main(int argc, char** argv) {
int data[size]={1,2,3,4,5};
rotate_array_left(data,2);
for(int j=0;j<=size-1;j++)
{
printf("%d\t",data[j]);
}
return (EXIT_SUCCESS);
}
view raw rotatearray.c hosted with ❤ by GitHub

Count Set bits in an array of integers

assume you have an array of 5 integers and you want to count the numbers of set bits in all array elements , write a function to do that

Solution
#include <stdio.h>
#include <stdlib.h>
#define size 5
int count_set_bits(int *array)
{
int count=0;
for(int i=0;i<size;i++)
{
for(int j=0;j<32;j++)
{
if(array[i]&(1<<j))
{
count++;
}
}
}
return count;
}
int main(int argc, char** argv) {
int data[size]={1,2,3,4,5};
printf("Number of set bits in this array = %d bits \n",count_set_bits(data));
return (EXIT_SUCCESS);
}
view raw setbits.c hosted with ❤ by GitHub


Circular Bit Shift

Write two functions RL(data,n) which performs circular left shift on variable data by n bits , RR(data,n) which performs circular right shift on variable data by n bits
note: data is 1 byte variable

refer to this video to know more about circular bit shifts




Solution
#include <stdio.h>
#include <stdlib.h>
char RL(unsigned char byte,unsigned int n)
{
unsigned char temp=0;
for(int x=0;x<n;x++)
{
temp=byte&(1<<7);//save last bit
byte=byte<<1;//shift n left by 1 bit
byte|=temp;//save last bit in first position from right
}
return byte;
}
char RR(unsigned char byte,unsigned int n)
{
unsigned char temp=0;
for(int x=0;x<n;x++)
{
temp=byte&(1<<0);//save first bit
byte=byte>>1;//shift n left by 1 bit
byte|=(temp<<7);//save first bit in last position from right
}
return byte;
}
int main(int argc, char** argv) {
printf("%d\n%d\n",RL(16,2),RR(16,2));
return (EXIT_SUCCESS);
}
view raw circularshift.c hosted with ❤ by GitHub

Friday, 16 June 2017

Beautiful Matrix

Problem 
codeforces.com/problemset/problem/263/A

Solution
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
int main(int argc, char** argv) {
int input;
// read matrix
for(int r=0;r<=4;r++)
{
for(int c=0;c<=4;c++)
{
cin>>input;
if(input==1)
{
cout<<abs(r-2)+abs(c-2)<<endl;
break;
}
}
if(input==1){break;}
}
return 0;
}
view raw beautiful.cpp hosted with ❤ by GitHub


Teams Problem

Problem 
http://codeforces.com/contest/231/problem/A

Solution
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
unsigned int n;// number of problems
unsigned int o1,o2,o3;// team memebrs
unsigned int pass=0;
unsigned int fail=0;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>o1>>o2>>o3;
if(o1+o2+o3>=2){pass++;}
else if(o1+o2+3<2){fail++;}
}
cout<<pass;
return 0;
}
view raw teams.cpp hosted with ❤ by GitHub




Saturday, 3 June 2017

What is dangling pointer

The following code snippet illustrate the idea of dangling pointers


#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int *p=(int*)malloc(sizeof(int));
*p=1;
/*
* now p is an integer pointer pointes to space(4 bytes)allocated
* by malloc function , also the allocated space is initilized by 1
*/
cout<<*p<<endl;//result will be 1
//now we will free or deallocate reserved 4 bytes
free(p);
/*
* now p is a dangling pointer , pointes to deallocated space
* so data at this pointer is garbage
*/
cout<<*p;// output will be garbage
return 0;
}
view raw dangling.cpp hosted with ❤ by GitHub

Saturday, 27 May 2017

Reverse Two Arrays Of The Same Size

write a C program to reverse two array elements of the same size 
as example if we have int a[]={1,2,3,4},int b[]={5,6,7,8}
after reversing we would have int a[]={5,6,7,8},int b[]={1,2,3,4}

#include <stdio.h>
#include <stdlib.h>
#define size 4
void swap(int *x1,int *x2)
{
int temp=*x1;
*x1=*x2;
*x2=temp;
}
int main(int argc, char** argv) {
int a[size]={1, 2, 3, 4};
int b[size]={5, 6, 7, 8};
for(int j=0;j<size;j++)
{
swap(&a[j],&b[j]);
}
printf("after reversing\n");
for(int i=0;i<size;i++)
{
printf("first array element %d\t%d\n",i,a[i]);
printf("second array element %d\t%d\n",i,b[i]);
}
return (EXIT_SUCCESS);
}
view raw revarray.c hosted with ❤ by GitHub

Monday, 1 May 2017

Find the output of the following code


#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
unsigned int i=257;
int *iptr=&i;
for(int j=0;j<=3;j++)
{
printf("%d\t",*((char*)iptr+j));
}
return (EXIT_SUCCESS);
}
view raw q148.c hosted with ❤ by GitHub
Output 

1    1    0    0

Explanation






Saturday, 29 April 2017

Find the output of the following code


#include <stdio.h>
int main(int argc, char** argv) {
static int i;
while(i<=10)
{
(i>2)?i++:i--;
}
printf("%d\n",i);
return (EXIT_SUCCESS);
}
view raw q134.c hosted with ❤ by GitHub
Answer

2147483647

Explanation

i is an uninitialized static variable so its default value is zero
also i automatically promoted to unsigned int (because we did not specify if its signed or unsigned)
then 0<=10 condition true 
inside while loop 0>2 false , i-- executed 
second iteration i becomes 2147483647 (int size on my machine is 4 bytes)
2147483647 <=10 false , while loop is bypassed and 2147483647 is printed.


Complicated Declaration

what does the following declaration mean 

void (*abc(int,void(*def)()))();

Answer & Explanation 



Find the output of the following code


#include <stdio.h>
int main(int argc, char** argv) {
char *p="hello";
char c=++*p++;
printf("%c\n",c);
return (EXIT_SUCCESS);
}
view raw q125.c hosted with ❤ by GitHub
Answer
i

Explanation 

char c=++*p++
this statement will be parsed as follow 
1)p++ p which is a char pointer is post incremented so p still points to 'h'
2)*p++ p is dereferenced to get value 'h'
3)++'h' is i

note:this result is highly compiler dependent , some compilers may fail to compile this code and others may get you this output

advise : never write a code which seems to be ambiguous and compiler dependent




Tuesday, 25 April 2017

Find the output of the following code

#include <stdio.h>
#define concat(x,y) x##y
#define string(a) #a
void main()
{
int myvar=20;
printf("%d\n",concat(my,var));
printf("%s",string(C is sea));
}
view raw q38.c hosted with ❤ by GitHub
Output
20
C is sea

Explanation
in this question I introduce the concept of preprocessor operators 
concat(x,y) x##y this operator concatenate x and y 
string(a) #a #operator convert any macro constant into string
so after preprocessing this code you will have the following code

int myvar=20;
printf("%d\n",myvar);
printf("%s","C is sea");


Find the output of the following code


#include <stdio.h>
void main()
{
char programming_languages[4][10]={"C","C++","java","python"};
char *temp=programming_languages[2];
programming_languages[2]=programming_languages[3];
programming_languages[3]=temp;
for(int i=0;i<=3;i++)
{
printf("%s\n",programming_languages[i]);
}
}
view raw q33.c hosted with ❤ by GitHub
Output
lvalue required as increment operand

Explanation
after reading the code for the first time you may get tricked and say the output will be

c++
python
java 
but this not the output , because you will get compiler error in line 6 when you try to modify the base address of an array which is already a constant pointer

Find the output of the following code



void main()
{
extern int x;
x=100;
printf("value of x=%d\n",x);
}
view raw q6.c hosted with ❤ by GitHub
Output 
linker error (undefined symbol x)

Explanation 
extern keyword tells the compiler that the value of the variable x is not in this scope so the compiler does not know variable x memory location so he will not assign x memory location , otherwise during linking time if x is defined in another scope or file , its value will be printed

Find the output of the following code


void main()
{
char message[]="hello";
for(int i=0;message[i];i++)
{
printf("%c\t%c\n",message[i],i[message]);
}
}
view raw q2.c hosted with ❤ by GitHub

Output

h h 
e e
l l
l l
o o

Explanation
message[i]=i[message]
because compilers convert message[i] into *(message+i)
where message is the array base address ,also i[message] is converted into
 *(i+message)
so the two expressions are the same

Tuesday, 4 April 2017

Big endian VS little endian

Write a C program to check if your processor is big endian or little endian 

solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int data=0x11223344;
char *testptr=(char*)&data;
if(*testptr==0x11)
{
printf("big endian\n");
}
else if(*testptr==0x44)
{
printf("little endian\n");
}
}
view raw bigvslit.c hosted with ❤ by GitHub


Monday, 13 March 2017

Reverse bits of Byte

write a C function to reverse the bits of a Byte as example if we have variable unsigned char x=0x07=0b00000111 as input parameter after reversing its bits it would return 11100000

solution 


#include <stdio.h>
unsigned char reverse (unsigned char inbyte)
{
unsigned char outbyte=0;
for(int i=0;i<=7;i++)
{
if(inbyte&(1<<i))
{
outbyte|=1<<(7-i);
}
else
{
continue;
}
}
return outbyte;
}
int main(int argc, char** argv) {
unsigned char x=1;
unsigned char revx=reverse(x);
printf("%d\n",revx);
return (EXIT_SUCCESS);
}
view raw rev.c hosted with ❤ by GitHub

Tuesday, 7 March 2017

Palindrome String

Write a C code to check a String is palindrome or not , Some palindrome strings examples are "a", dad", "radar", "madam", "abcba" etc.

solution
#include <stdio.h>
#include <string.h>
int main()
{
// a program to check a string is palindrome or not
char string[20];
printf("Enter the string\n");
gets(string);
unsigned int i=0;
unsigned int j=strlen(string)-1;
unsigned int flag=0;
while(i!=j)
{
if(string[i]==string[j]){i++,j--;continue;}
else {flag=1;break;}
}
if(flag==0){printf("string is palindrome\n");}
else if(flag==1){printf("string is not palindrome\n");}
return 0;
}
view raw palin.c hosted with ❤ by GitHub



Monday, 6 March 2017

From decimal to binary

Write a C program to convert an integer from decimal to binary , using logical bitwise operators

solution
#include <stdio.h>
int main()
{
unsigned int x;
printf("enter any positive integer\n");
fflush(stdout);
scanf("%d",&x);
//sizeof(int)=4 byte on my machine
for(int i=0;i<=31;i++)
{
if(x&(0x8000>>i)){printf("%d",1);}
else {printf("%d",0);}
}
return 0;
}
view raw dtob.c hosted with ❤ by GitHub



Thursday, 2 March 2017

what is the output

what is the output of this C code 
#include <stdio.h>
union temp
{
int a;
char c;
};
int main()
{
union temp t={66,'A'};// initialize the union members
printf("%d\t%c\n",t.a,t.c);
printf("%d\n",sizeof(t));
return 0;
}
view raw union.c hosted with ❤ by GitHub
output:
66    B
4
Explanation:
union temp t={66,'A'};
this statement will initialize only the first member of the union x with 66 and the compiler will ignore the second value 'A', as one element is sufficient to initialize all union members as they share the same memory locations
sizeof(t) =4 size of largest element in memory location



Wednesday, 1 March 2017

what is the output of this C code

#include <stdio.h>
struct point
{
int x;
int y;
};
struct notpoint
{
int x;
int y;
};
int main()
{
struct point p1={10,20};
struct point p2={-10,-20};
p1=p2;
printf("%d\t%d",p1.x,p1.y);
struct notpoint p3={100,200};
p3=p1;
printf("%d\t%d",p3.x,p3.y);
if(p3>p2)
{
printf("hello\n");
}
else
{
printf("C programming\n");
}
return 0;
}
view raw s.c hosted with ❤ by GitHub
output :
compilation error in line 19 , as you can not assign two structures of different types
also there is a compilation error in line 21 as rational operators can not be applied on structures

Tuesday, 28 February 2017

compute occurrence of character in a string

write C Program print the frequency of a certain character in a string 

#include <stdio.h>
#include <string.h>
int main(void) {
printf("enter the string\n");
char string[50];char c;int i=0;int counter=0;
gets(string);
printf("enter the character you want to compute its occurrence\n");
scanf("%c",&c);
while(string[i]!='\0')
{
if(string[i]==c){counter++;i++;}
else {i++;continue;}
}
printf("%c occured %d times with frequency %f %c\n",c,counter,100*(float)counter/i,'%');
return 0;
}
view raw freq.c hosted with ❤ by GitHub

what is the output of this program


#include <stdio.h>
void f(int (*x)(int));
int myfoo(int i);
int (*foo)(int) = myfoo;
int main()
{
f(foo(10));
}
void f(int (*i)(int))
{
i(11);
}
int myfoo(int i)
{
printf("%d\n", i);
return i;
}
view raw ptof.c hosted with ❤ by GitHub
output
10 segmentation fault

explanation


Wednesday, 22 February 2017

find the output

what will be the output of the following code 


#include <stdio.h>
int main(void) {
int x=100;char y=3;float z=3.12;
int *xp=&x;char *yp=&y;float *zp=&z;
printf("%d\t%d\t%d\t%d\t%d\n",sizeof(NULL),sizeof(xp),sizeof(yp),sizeof(zp),sizeof("clu"));
return 0;
}
view raw szp.c hosted with ❤ by GitHub
output will be 
8  8  8  4
size of a pointer to any data type is type independent , size of pointer depends on your machine address bus.
sizeof("clu")  here "clu" is treated as array of characters ={'c','l','u','\0'}
so sizeof("clu") is 4 bytes

Tuesday, 14 February 2017

palindrome number

Write A program to check if a positive integer is palindrome or not

#include <stdio.h>
#include <math.h>
int main()
{
int n;scanf("%d",&n);
int digits=0;int reverse=0;
int temp1=0;
int temp2=0;
if(n<=0){printf("enter positive enteger\n");}
else
{
temp1=n;
temp2=n;
while(temp1!=0)
{
temp1/=10;
digits++;
}
for(int i=digits-1;i>=0;i--)
{
reverse+=(temp2%10)*(pow(10,i));
temp2/=10;
}
if(reverse==n){printf("palindrome\n");}
else{printf("not palindrom\n");}
}
return 0;
}
view raw palindrom.c hosted with ❤ by GitHub

Saturday, 11 February 2017

Number of words in a string

Write a C function words(string) that accepts a string as input parameter and returns the number of words in this string 
as example
words("my name is mohamed") will return 4


#include <stdio.h>
#include <string.h>
int words(char *s)
{
int i=0;
int counter=0;
if(strlen(s)==0){return 0;}
else{
while(*(s+i)!='\0')
{
if(*(s+i)==' '){counter++;i++;}
i++;
}
return counter+1;
}
}
int main(int argc, char **argv)
{
char statement[]="";
printf("number of words are\n%d\n",words(statement));
return 0;
}
view raw no_of_words.c hosted with ❤ by GitHub

Friday, 10 February 2017

What will be the output of the following program

#include <stdio.h>
int main(int argc, char **argv)
{
char s[]="Egypt";
for(int i=0;*("Egypt"+i)!='\0';i++)
{
printf("%c",s[i]);
}
return 0;
}
view raw string.c hosted with ❤ by GitHub
the output is 
Egypt 
explanation 
string name is the base address of the string variable which is an array of characters

Sunday, 5 February 2017

Even or Odd

Write a C program to check if any entered number is even or odd without the use of conditional statements (if,else)

#include <stdio.h>
int main(void) {
printf("enter your number (assume it must be positive integer)\n");
int input;
scanf("%d",&input);
char choise[2]={'E','O'};// O for Odd and E for Even
printf("%d is %c",input,choise[input%2]);
return 0;
}
view raw evenorodd.c hosted with ❤ by GitHub

No loops

Write a C program to print the numbers from 1 to 10 without using any looping statements (for/while/do while)
also do not write printf() 10 times


#include <stdio.h>
int main()
{
static unsigned int counter=1;
if(counter<=10)
{
printf("%d\t",counter);
counter++;
main();
}
return 0;
}
view raw noloop.c hosted with ❤ by GitHub

Thursday, 2 February 2017

convert to uppercase

Write a function upper() that accepts a string and converts all its characters into uppercase characters 
as example upper("c programming")=C PROGRAMMING
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool is_upper(char x)
{
if((int)x>=65&&(int)x<=90)
{
return true;
}
return false;
}
char *upper(char *base)//passing array to a function that returns a pointer to char
{
while(*base!='\0')
{
if(is_upper(*base)||*base==' '){*base++;}
else{*base-=32;base++;}
}
return base;
}
int main()
{
char array[20]="hE l lO";
upper(array);
puts(array);
return 0;
}
view raw upper.c hosted with ❤ by GitHub


reverse a string

Write a function reverse() that accepts a string and reverses it 
as example reverse("hello") would return "olleh"
#include <stdio.h>
#include <string.h>
char* reverse(char *base)// passing array to a function that returns pointer to character
{
int i=0;
int j=strlen(base)-1;
char temp;
while(i!=j)
{
temp=base[i];
base[i]=base[j];
base[j]=temp;
i++;
j--;
}
return base;
}
int main()
{
char array[5]="hello";
puts(reverse(array));
return 0;
}
view raw reverse.c hosted with ❤ by GitHub

string of numbers

write a function that accepts string of numbers and converts it to digits 
as example convert("123")=123

#include <stdio.h>
void convert(char *base)// passing array to a function
{
while(*base!='\0')
{
*base-='0';//*base=*base-'0' will give you the numeric value of character number
printf("%d",*base);
base++;
}
}
int main()
{
char num_char[5]="83461";
convert(num_char);
return 0;
}
view raw convert.c hosted with ❤ by GitHub


Remove all blank spaces in a string

Write a C program to remove all the blank spaces from a string.
as example if string is "hello world , C programming" then the output will be "helloworld,Cprogramming"

#include <stdio.h>
#include <string.h>
int main()
{
char input_string[100];char output_string[100];// two char arrays (two strings)
printf("enter string with spaces\n");
gets(input_string);// you can not use scanf() as it do not accept string with spaces
int i=0;int j=0;
while(input_string[i]!='\0')
{
if(input_string[i]!=' ')
{
output_string[j]=input_string[i];
i++;
j++;
}
else
{
i++;
}
}
output_string[j]='\0';//terminate o/p string with null character
printf("input string without spaces \n");
puts(output_string);
return 0;
}
view raw remove.c hosted with ❤ by GitHub

Wednesday, 25 January 2017

What will be the output of the following program


#include <stdio.h>
int add(int a,int b){return(a+b);}
int sub(int x,int y){return(x-y);}
int main()
{
add(10,30);
printf("%d",sub-add+main);
return 0;
}
view raw ftp.c hosted with ❤ by GitHub
output

in this program we perform math operations on the base addresses of the functions , so the output is compiler dependant 
assume the base address of sub() is 4199876 and add() 4199856 and main() is 4199894
so the output will be 4199914

Tuesday, 24 January 2017

What will be the output of the following code 


#include <stdio.h>
struct test
{
unsigned var1:5;
unsigned var2:4;
unsigned var3:2;
};
int main()
{
typedef struct test TEST;
TEST new_test={32,10,5};
printf("var1=%d\t var2=%d\t var3=%d\t ",new_test.var1,new_test.var2,new_test.var3);
return 0;
}
view raw boundry.c hosted with ❤ by GitHub

Output
var1=0    var2=10    var3=1

Explanation 

Pointers and bitfields

what will be the output of the following code

#include <stdio.h>
struct test
{
unsigned int x;
long int y: 33;
unsigned int z;
};
int main()
{
struct test t;
unsigned int *ptr1 = &t.y;
unsigned int *ptr2 = &t.z;
printf("%d", ptr2 - ptr1);
return 0;
}
view raw bitfields.c hosted with ❤ by GitHub
the code creates compilation error , as you can not create a pointer to bit fields , simply because bit fields may not start at byte boundry

Thursday, 19 January 2017

Swap structure values

Assume that you have a structure defined as follow 
struct two_integers {int n1;int n2;};
and this structure is initialized as follow
struct two_integers x={100,-100}; 
Write a C function that returns the same structure x but n1 and n2 are swapped

#include <stdio.h>
struct two_integers {int n1;int n2;};
void swap(struct two_integers *xp)// pass structure variable by reference
{
int t=xp->n1;
xp->n1=xp->n2;
xp->n2=t;
return;
}
int main()
{
struct two_integers x={100,-100};// n1=100 and n2=-100;
struct two_integers *xp=&x;
swap(xp);
printf("n1=%d\tn2=%d\n",x.n1,x.n2);
return 0;
}


Structures

In the following code , assume that the base address of the structure is 2424384 (in decimal form) , what will be the output of the program 

#include <stdio.h>
int main()
{
struct employee {int age;float salary;};
struct employee e1={40,3000};
struct employee *pointer_to_e=&e1;
printf("%d\n%d\n%d\n%d",pointer_to_e,&(e1.age),&(e1.salary),(pointer_to_e)+1);
return 0;
}
view raw struct.c hosted with ❤ by GitHub
Solution
2424384
2424384
2424388
2424392

Tuesday, 17 January 2017

Sorting 2D array

Assume you have 2D array of integers , int a[3][4]={8,7,6,5,
                                                                                                            -2,800,19,-40,
                                                                                                             1,-23,600,-500};

Write a C program to sort it in ascending order (from low to high)

Solution
#include <stdio.h>
int main()
{
int a[3][4]={8,7,6,5,
-2,800,19,-40,
1,-23,600,-500
};
int t=0;
int *p=&a[0];
for(int i=0;i<=12;i++)
{
for(int j=0;j<=11;j++)
{
if(*(p+j+1)<*(p+j))
{
t=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=t;
}
}
}
printf("after sorting in ascending order (from low to high) \n");
for(int i=0;i<=2;i++)
{
for(int j=0;j<=3;j++)
{
printf("%d\t",a[i][j]);
}
}
return 0;
}
view raw sort2d.c hosted with ❤ by GitHub

Monday, 16 January 2017

Increment all array values using pointers

Write C function INC(int array[5],int n) that accepts two parameters array of five integers and integer, and adds the integer n to all array elements , then it returns the new array , as example if array[5]={1,5,7,0,2} and n =5 after function call we have  array[]={6,10,12,5,7}
#include <stdio.h>
void INC(int *pointer,int n)
{
for(int x=0;x<=4;x++)
{
*(pointer+x)+=n;
}
return;
}
int main()
{
int N;printf("enter the number you want to add to all array elements\n");
scanf("%d",&N);
int array[5]={1,5,7,0,2};
INC(array,N);
printf("array after function call\n");
for(int i=0;i<=4;i++)
{
printf("%d\t",array[i]);
}
return 0;
}
view raw inc.c hosted with ❤ by GitHub






Saturday, 14 January 2017

Pointers and 2D arrays

Assume you have 2D array S[2][4]={{1234,56},
{1212,33},
{1434,80},
{1312,78}};
write a C program to print all the values and their corresponding addresses of this array
using pointers

#include "stdio.h"
int main()
{
int s[4][2] ={
{1234,56},
{1212,33},
{1434,80},
{1312,78}
};
int *p=&s[0];// pointer to array
for(int i=0;i<=3;i++)
{
printf("Start Address of %d th 1-D array = %d\n",i,&s[i]);
for(int k=0;k<=1;k++)
{
printf("address of elemnt %d in %d th 1-D array %d \t and its value = %d\n",k,i,p,*p);
p++;
}
}
return 0;
}
view raw 2d.c hosted with ❤ by GitHub

Pointer Arithmetic

What will be the output of the following program 


#include "stdio.h"
int main()
{
//Pointer Arithmetic
int i=4,*j;
j=&i ;printf("%d\n",j);
j=j+1 ;printf("%d\n",j);
j=j+9 ;printf("%d\n",j);
j=j-3 ;printf("%d\n",j);
return 0;
}

2424388
2424392
2424428
2424416

size of double data type

Write a program to calculate the size of a double data type in terms of Bytes , Do not use the sizeof() operator

Solution


#include "stdio.h"
int main()
{
double array[2]={0,0};
double *p1=array;
double *p2=p1+1;
printf("Size of double data type is %d Bytes\n",(int)p2-(int)p1);
return 0;
}
view raw sizeof.c hosted with ❤ by GitHub

Wednesday, 11 January 2017

what will be the output of the following program


#include "stdio.h"
int main()
{
int numbers[5];// integer array
for(int i=0;i<=4;i++)
{
printf("%d\n",numbers[i]);
}
return 0;
}
view raw array.c hosted with ❤ by GitHub
output will be garbage values
uninitialized array elements have garbage values

Tuesday, 10 January 2017

What will be the output of the following program


#include "stdio.h"
#define PRODUCT(x) (x*x)
int main( )
{
int i=3;
int j=0;
int k=0;
j=PRODUCT(i++) ;
k=PRODUCT(++i) ;
printf("j=%d\nk=%d",j,k) ;
return 0;
}
view raw pre.c hosted with ❤ by GitHub

j=12
k=49

From C file to exe file

Describe in detail how a C program is compiled and executed 

Answer

1) The preprocessor code searches for preprocessor directives (mainly #include or #define) and substitute them with their codes,the output of this step creates an expanded file (.I file)
2) the compiler takes .I file and coverts the high level code into assembly then into machine language (binary format) and generate .obj file
3) the linker takes .obj file and link it with C standard library functions in your code 
and generates the executable version of your C code



Monday, 9 January 2017

what will be the output of the following program


#include <stdio.h>
float x = 4.5 ;
int main( )
{
float y;
float f(float);
x*=2.0 ;
y=f(x) ;
printf("x=%f\ny=%f",x,y) ;
return 0;
}
float f(float a)
{
a+=1.3 ;
x-=4.5 ;
return(a+x) ;
}
view raw global.c hosted with ❤ by GitHub
x=4.5
y=14.8

What will be the output of the following program


#include <stdio.h>
int main()
{
static int count=5;
printf ("count = %d\n", --count);
if (count!= 0)
main() ;
return 0;
}
view raw static.c hosted with ❤ by GitHub
output is
count=4
count=3
count=2
count=1
count=0

Wednesday, 4 January 2017

what is the output of the following program


#include <stdio.h>
add(double a,double b)
{
return a+b;
}
void main()
{
printf("%d",add(12.3,98.2));
return;
}
view raw default.c hosted with ❤ by GitHub
output=110 
by default C functions return int values in case you did not specify the return type

what is the output of the following program


#include <stdio.h>
int add(int x,int y,int z)
{
printf("%d\n",x+y+z);
return;
}
int main()
{
add(2,3,5);
int x=add(2,3,5);
printf("%d",x);
return 0;
}
view raw garbage.c hosted with ❤ by GitHub
10
10
garbage value
if your function does not return any value , it must be declared as void