Showing posts with label Data Structures in C. Show all posts
Showing posts with label Data Structures in C. Show all posts

Tuesday, 19 April 2022

Bit wise operators Questions in C

Bitwise And

  1. #include<stdio.h>
  2. int main()
  3. {
  4. int n;
  5. printf("Enter an integer\n");
  6. scanf("%d",&n);
  7. if ( n & 1 == 1 )
  8. printf("Odd\n");
  9. else
  10. printf("Even\n");
  11. return 0;
  12. }

Bitwise XOR 

Symbol used is ^

#include <stdio.h>
main()
{
 int x=1,y=3;
 if(x ^ y)
  printf("x is not equal to y");
 else
  printf("x is equal to y");
}

Practice Problem

https://www.codechef.com/problems/MISSP

Chef is fan of pairs and he likes all things that come in pairs. He even has a doll collection in which all dolls have paired.One day while going through his collection he found that there are odd number of dolls. Someone had stolen a doll!!!
Help chef find which type of doll is missing..

#include <stdio.h>
   
    int main()
{
        int t, n, m, b;
       
           
        scanf ("%d\n", &t);
        while (t--)
{
            b = 0;
           
            scanf("%d\n", &n);
           
            while (n--)
{
                scanf("%d\n", &m);
                b ^= m;
            }
           
            printf("%d\n", b);
        }
       
        return 0;
    }

Bitwise <<


Arithmetic, assignment,logical operator question in c

Questions on Arithmetic operators
1. A computer programming contest requires teams of 5 members each.
Write a program that asks for the number of players and then give 
the number of teams and number of players leftover?

2. Find the number of months and leftover when the number of days
are given (assume each month has only 30 days)

3. https://www.hackerrank.com/challenges/combo-meal/submissions/code/112740245

4. Number of questions on modulus operator can be explained
Questions on Assignment operator
Explanation: different types of assignments  a =10, a =b, a= b+c

1. Swap two variables
Questions on Logical Operators

// Input an integer number and check whether 
// it is divisible by 9 or 7.

#include <stdio.h>

int main()
{
    int num;
    
    //input number
    printf("Enter an integer number: ");
    scanf("%d", &num);
    
    //check the condition
    if(num%9==0 || num%7==0)
        printf("%d is divisible by 9 or 7\n",num);
    else
        printf("%d is not divisible by 9 or 7\n",num);
        
    return 0;
}
// Input gender in single character and print full gender
// (Ex: if input is 'M' or 'm' - it should print "Male").

#include <stdio.h>

int main()
{
    char gender;
    
    //input gender
    printf("Enter gender (m/M/f/F): ");
    scanf("%c", &gender);
    
    //check the condition and print gender
    if(gender=='m' || gender=='M')
        printf("Gender is Male");
    else if(gender=='f' || gender=='F')
        printf("Gender is Female");
    else
        printf("Unspecified gender");
        
    return 0;
}


Tuesday, 5 April 2022

Reverse the contents of a file and store in another file using fseek in c

 #include <stdio.h>

#include<stdlib.h>

int main()

{

    FILE *fp1,*fp2;

    fp1=fopen("input.txt","r");

    fp2=fopen("output.txt","w");

    char ch;

    fseek(fp1,-1,SEEK_END);

    while(1)

    {

        ch=fgetc(fp1);

        fputc(ch,fp2);

        if(fseek(fp1,-2,SEEK_CUR) <0) 

        break;

    }

    fclose(fp1);

    fclose(fp2);

    return 0;

}

======(OR) =====

#include <stdio.h>

#include<stdlib.h>

int main()

{

    FILE *fp1,*fp2;

    fp1=fopen("input.txt","r");

    fp2=fopen("output.txt","w");

    char ch;

    int c,i=1;

    fseek(fp1,0,SEEK_END);

    for(c=ftell(fp1);i<=c;i++)

    {

        fseek(fp1,-i,SEEK_END);

        ch=fgetc(fp1);

        fputc(ch,fp2);

    }

    fclose(fp1);

    fclose(fp2);

    return 0;

}


Sunday, 3 October 2021

c program to simulate grep command

 

1. The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern.

Example:

if geekfile.txt contains the data below:

unix is great os. unix is opensource. unix is free os.
learn operating system.

 

Then the following command

$grep -c "unix" geekfile.txt

 

will give ouput:

2

 

as option -c prints only a count of the lines that match a pattern
 
Q) Example program to simulate  grep system call
#include <stdio.h>
#include<string.h>
int main()
{
    char st[1000], word[10];
    printf("enter a sentence");
    scanf(" %[^\n]s", st);
    printf("enter a search word");
    scanf(" %s",word);
    int l = strlen(st);
    int lw=strlen(word);
    char *p;
    int i=0,c=0;
    while(i<l)
    {
        p=strstr(st+i,word);
        if(p)
        {
            c++;
            i=p-st+lw;
        }
        else
            break;
    }
    printf("%s occurred %d times",word,c);
    return 0;
}

 

Tuesday, 2 February 2021

Convert nested loops into recursion in C, patterns using recursion

 #include <stdio.h>

int main()
{
    int r,c, n,nr,nc,c1=1,c2=1;
    scanf("%d", &n);
    nr=2*n-1;
    nc=2*n-1;
    for(r=1;r<=nr;r++)
    {
        for(c=1;c<=nc;c++)
        {
            if(c<c1||c>c2)
                printf(" ");
            else
                printf("*");
        }
        if(r<n)
        {
            c1++;
            c2=c2+2;
        }
        else
        {
            c1--;
            c2=c2-2;
        }
        printf("\n");
    }
}

Consider a nested loop as shown above..
First i tried converting inner c loop into recursion and i got this code below

#include <stdio.h>

void loop(int c,int nc,int c1,int c2)
{
    if(c>nc)
        return;
    if(c<c1||c>c2)
        printf(" ");
    else
        printf("*");
    loop(c+1,nc,c1,c2);
}

int main()
{
    int r,c, n,nr,nc,c1=1,c2=1;
    scanf("%d", &n);
    nr=2*n-1;
    nc=2*n-1;
    for(r=1;r<=nr;r++)
    {
        loop(1,nc,c1,c2);
        if(r<n)
        {
            c1++;
            c2=c2+2;
        }
        else
        {
            c1--;
            c2=c2-2;
        }
        printf("\n");
    }
}

Now further converting outer r loop the program would like this as shown below

#include <stdio.h>

void loop(int c,int nc,int c1,int c2)
{
    if(c>nc)
        return;
    if(c<c1||c>c2)
        printf(" ");
    else
        printf("*");
    loop(c+1,nc,c1,c2);
}
void pattern(int r,int n,int c1,int c2)
{
    if(r>2*n-1)
        return;
    loop(1,2*n-1,c1,c2);
    if(r<n)
    {
        c1++;
        c2=c2+2;
    }
    else
    {
        c1--;
        c2=c2-2;
    }
    printf("\n");
    pattern(r+1,n,c1,c2);
    
}
int main()
{
    int r,c, n,nr,nc,c1=1,c2=1;
    scanf("%d", &n);
    nr=2*n-1;
    nc=2*n-1;
    pattern(1,n,c1,c2);
}

Further can be improved as
#include <stdio.h> void loop(int c,int nc,int c1,int c2) { if(c>nc) return; if(c<c1||c>c2) printf(" "); else printf("*"); loop(c+1,nc,c1,c2); } void pattern(int r,int n,int c1,int c2) { if(r>2*n-1) return; loop(1,2*n-1,c1,c2); if(r<n) { printf("\n"); pattern(r+1,n,c1+1,c2+2); } else { printf("\n"); pattern(r+1,n,c1-1,c2-2); } } int main() { int r,c, n,nr,nc,c1=1,c2=1; scanf("%d", &n); nr=2*n-1; nc=2*n-1; pattern(1,n,c1,c2); }

Tuesday, 29 December 2020

printing the matrix in spiral format in c

#include<stdio.h>
#include<string.h>
int main() 
{
    int n,i,j,r=0,co=1,c=0,nr=0,nc=0;
    scanf("%d",&n);
    int mat[n][n],nd=n;
    while(n>=1)
    {
        for(i=1;i<n;i++)
            mat[r][c++]=co++;

        for(i=1;i<n;i++)
            mat[r++][c]=co++;

        for(i=1;i<n;i++)
            mat[r][c--]=co++;

        for(i=1;i<n;i++)
            mat[r--][c]=co++;

        n=n-2;
        nr++;
        nc++;
        r=nr;
        c=nc;
    }
    if(nd%2 != 0)
        mat[--nr][--nc]=co;

    for(i=0;i<nd;i++)
    {
        for(j=0;j<nd;j++)
            printf("%3d ",mat[i][j] ); 
        printf("\n");
    }

input 

6

output:
  1   2     3   4    5     6 
 20  21  22  23  24   7 
 19  32  33  34  25   8 
 18  31  36  35  26   9 
 17  30  29  28  27  10 
 16  15  14  13  12  11

Monday, 28 December 2020

Hacker Rank Append and Delete solution in c

Problem:

https://www.hackerrank.com/challenges/append-and-delete/problem

Solution:

#include<stdio.h>

#include<string.h>

int main()
{
    char s[101],t[101];
    int k;
    scanf(" %s",s);
    scanf(" %s",t);
    scanf("%d",&k);
    int ls=strlen(s);
    int lt=strlen(t),i,ans;
    for(i=0;s[i]!='\0'&&t[i]!='\0';i++)
    {
        if(s[i]!=t[i])
            break;
    }
    ans=ls-i+lt-i;
        
    if(ans ==k||(ans < k && ans%2 == k%2)||k>=ls+lt)
        printf("Yes");
    else
        printf("No");
    
}

consider this testcase
y
yu
2
Here we can perform only one operation that is appending u
but given k is 2
so for this test case output must be No
so this is taken care by the condition
number of operations required and k must be even
as delete and append are two operations.

Also when k>=ls+lt, we can remove entire s string and append t string
as we can delete an empty string as many times as we like..so when k>=ls+lt,
output is always "YES"


Friday, 18 December 2020

John and GCD list Hacker Rank solution in C

Problem:
https://www.hackerrank.com/challenges/john-and-gcd-list/problem

Explanation:
GCD(B[1],B[2]) =A[1] that is A[1] divides B[2]
GCD(B[2],B[3]) =A[2] that is A[2] also divides B[2]

so B[2] must be divisible by both A[1] and A[2].
as LCM of A[1],A[2] will be divisible by both A[1] and A[2].
Therefore B[2] must be a multiple of LCM(A[1],A[2])
Since in the question, they wanted minimum value of B[2]
So, B[2] = LCM(A[1],A[2])


#include<stdio.h>
int gcd(int,int);
int lcm(int,int);
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,i;
        scanf("%d",&n);
        int a[n];
        for(i=0 ; i<n ; i++)
            scanf("%d",&a[i]);
        printf("%d ",a[0]);
        for(i=0 ; i<n-1 ; i++)
        {
            if(a[i+1] >a[i])
                printf("%d ",lcm(a[i+1],a[i]));
            else
                printf("%d ",lcm(a[i],a[i+1]));
        }
        printf("%d\n",a[n-1]);        
    }
    return 0;
}
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
int lcm(int a, int b)
{
    return (a*b)/gcd(a,b);
}

Tuesday, 15 December 2020

Sum The Series Problem Code: SUM1 codechef solution in c

https://www.codechef.com/problems/SUM1 

Explanation:



In the Question, it is mentioned to do %1000000007, to ensure the answer will always a number from 0 to 1000000006 

As n can take a value upto 10^16 in the question and n^2 cannot fit in even long long int, we cannot do n*n and then apply %1000000007

So we cannot do (n*n)%1000000007 so we do like this

((n%1000000007)*(n%1000000007))%1000000007

According to modular arithmetic (a*b)%m = ((a%m)*(b%m))%m

Here is the solution:

#include<stdio.h>

#define MOD 1000000007

int main() 

{

int t;

scanf("%d",&t);

while(t--)

{

    long long int n;

    scanf("%lld",&n);

    printf("%lld\n",(((n%MOD)*(n%MOD))%MOD));

}

return 0;

}

Printing Pattern Using Loops Hacker Rank Solution in C

https://www.hackerrank.com/challenges/printing-pattern-2 

Solution

#include <stdio.h>

int main() 

{

    int n,d,min;

    scanf("%d", &n);

  d=2*n-1;

    for(int i=1;i<=d;i++)

    {

        for(int j=1;j<=d;j++)

        {

            if(i<j)

                min=i-1;

            else

                min=j-1;

            if(min>d-j)

                min=d-j;

            if(min>d-i)

                min=d-i;

            printf("%d ",n-min);

        }

        printf("\n");

    }

    return 0;

}

Saturday, 31 August 2019

I Love T code chef solution in C

Read sentences until user enters 0
for each sentence, if the first character in each word in the given sentence is vowel, append T and if it is not vowel replace that character by T. 
Also only first character in each word only must be capital letter.

Sample Input:
love apples
apples are gOOOd for HelatHH
0

Sample Output:
Tove Tapples
Tapples Tare Toood Tor Telathh



#include<stdio.h>
int isvowel(char ch)
{
    if(ch >='A' && ch <= 'Z')
        ch=ch+32;
    if(ch == 'a' ||ch == 'e'||ch == 'i'||ch == 'o'||ch == 'u')
        return 1;
    else
        return 0;
}

int main()
{
    char st[1000001];
    scanf("\n%[^\n]\n",st);
    while(st[0] != '0')
    {
        int i;
        for(i=0;st[i]!='\0';i++)
        {
        if(st[i] >= 'A' && st[i] <= 'Z')
                st[i]=st[i]+32;
        if(i == 0|| (st[i-1] == ' ' && st[i] != ' '))
        {
         
            if(isvowel(st[i]))
                printf("T%c",st[i]);
            else
                printf("T");
        }
        else
            printf("%c",st[i]);
        }
        printf("\n");
        scanf("\n%[^\n]\n",st);
    }
    return 0;
 
}

Monday, 26 August 2019

Migratory Birds Hacker Rank Solution in C

Problem:

https://www.hackerrank.com/challenges/migratory-birds/problem


#include <stdio.h> int main() { int n,i,max,ans; scanf("%d", &n); int a[n],h[6]={0}; for(i = 0; i < n; i++) { scanf("%d",&a[i]); h[a[i]]++; } max=h[1]; for(i = 2; i < 6; i++) { if(max<h[i]) { max=h[i]; ans=i; } } printf("%d",ans); return 0; }

Friday, 23 August 2019

Binary Numbers Hacker Rank Solution in C

 #include <stdio.h>
int main()
{
    int n,r,c=0,t=0;
    scanf("%d",&n);
    while(n>0)
    {
        r=n%2;
        if(r==1)
        {
            c++;
            if(c>t)
                t=c;
        }
        else
            c=0;
        n=n/2;
    }
    printf("%d",t);
    return 0;

}


Find Product Hacker Earth Solution in C,Let Us Understand Computer Hacker Earth Solution in C,Count Numbers Hacker Earth Solution in C

#include <stdio.h>
#define ma 1000000007
int main(){
int num,i,a;
unsigned long long int ans=1;
scanf("%d", &num);

for(i=0;i<num;i++){
   scanf("%d", &a);
   ans=(ans*a)%ma;
}
printf("%d", ans);

}

===============or=================
#include <stdio.h>
const int ma = 1e9+7;
int main(){
int num,i,a;
unsigned long long int ans=1;
scanf("%d", &num);

for(i=0;i<num;i++){
   scanf("%d", &a);
   ans=(ans*a)%ma;
}
printf("%d", ans);

}

=============================================================
Let Us Understand Computer Hacker Earth Solution in C

#include <stdio.h>
#include <math.h>
int main()
{
unsigned long long int t;
scanf("%llu",&t);
while(t--)
{
unsigned long long int k,n,ans,i;
scanf("%lld",&n);
i=1;
while(i<=sqrt(n))
{
i=i*2;
}
if(n/i>=i/2)
ans=n-n/i;
else
ans=(n-(i/2))+1;
  printf("%lld\n",ans);
}
}

===========Count Numbers Hacker Earth Solution in C==============
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. int main()
  4. {
  5. int t,i;
  6. scanf("%d",&t);
  7. for(i=1;i<=t;i++)
  8. {
  9. int n,j,c=0;
  10. scanf("%d",&n);
  11. n++;
  12. char s[n];
  13. scanf("%s",s);
  14. for(j=0;s[j]!='\0';j++)
  15. {
  16. if(isdigit(s[j]) && !isdigit(s[j-1]))
  17. c++;
  18. }
  19. printf("%d\n",c);
  20. }
  21. return 0;
  22. }

Thursday, 22 August 2019

Finalized without bounds infix to postfix

#include<stdio.h>
#include <process.h>
#define MAX 50
char stack[MAX];
int top=-1;
int getpriority(char);
void push(char);
char pop();
main()
{
char infix[50],temp,ch,postfix[50];
int i=0,j=0;
printf("enter the infix expression\n");
scanf("%s",&infix);
while(infix[i] != '\0')
{
ch=infix[i];
if(ch == '(')
push(ch);
else if(ch == ')')
{
while(stack[top]!='(')
postfix[j++]=pop();
temp=pop();// popping the (
}
else if(isdigit(ch)||isalpha(ch))
postfix[j++]=ch;
else
{
while(getpriority(stack[top])>=getpriority(ch))
postfix[j++]=pop();
push(ch);
}
i++;
}
while(top != -1)
postfix[j++]=pop();
postfix[j]='\0';
puts(postfix);
}
int getpriority(char ch)
{
if( ch == '*'|| ch == '/'|| ch == '%')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return 0;
}
void push(char item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

char pop()
{
if(top == -1)
{
printf("stack empty");
return;
}
char temp;
temp=stack[top];
top=top-1;
return temp;
}