Tuesday, August 28, 2018

INTERMEDIATE LEVEL PROGRAMS FOR C


PROGRAM TO PRINT ALTERNATE POSITION OF LETTERS IN UPPERCASE:

STATEMENT:

A str‌ing S (only alphabets) is passed as input. The printed output should contain alphabets in odd positions in each word in uppercase and alphabets in even positions in each word in lowercase.

PROGRAM:

#include <stdio.h>

int main()

{
   char input[100];

   fgets(input,100,stdin);


  char *ptr = input;

  int offset;

  char word[100];

     while(sscanf(ptr,"%s%n",word,&offset) == 1){

      int index=1;

      int wordLength=strlen(word);

      while(index <= wordLength){

          char charToPrint;

          if(index%2 != 0){

              charToPrint = toupper(word[index-1]);

          }else{

              charToPrint = tolower(word[index-1]);

          }

          printf("%c",charToPrint);

          index++;

      }

   
      printf(" "); //Space after each word.

      ptr+=offset;

  }
   
}

Input:
FLoweR iS beauTIFUL

Output:
FlOwEr Is BeAuTiFuL



PROGRAM TO ARRANGE THE ALPHABETS IN THE STRING IN DESCENDING ORDER:

STATEMENT:

A string (with only alphabets) S is passed as input. The program should print the alphabets in the string in descending order. Assume all alphabets will be in lower case.



PROGRAM;

#include<stdio.h>

#include<stdlib.h>

int main()
{
 
    char input[100];

    fgets(input,100,stdin);

    char *ptr = input;

    int present['z'];

    char ch='a';

    while(ch <= 'z')

    {

        present[ch] = 0;

        ch++;

    }

    //Now mark alphabets which are present.

    while(*ptr != '\0' && *ptr != '\n' && *ptr != '\r')
    {

        if(*ptr >= 'a' && *ptr <= 'z')
        {

            present[*ptr]=1;
        }


        ptr++;
    }

    //Now print in reverse order

    ch = 'z';

    while(ch >= 'a')
    {
        if(present[ch])

        {
            printf("%c",ch);
        }

        ch--;
    }


}

INPUT/OUTPUT:

If the input is "cake", the output should be "keca"
If the input is "innovation", the output should be "vtonia" (n or o or i should not be repeated)

Sunday, August 26, 2018

FEW MORE PYTHON SAMPLE PROGRAMS

PROGRAM TO PRINT THE PATTERN OF THE INPUT GIVEN:

STATEMENT:

The number of rows N is passed as the input. The program must print the half pyramid using the numbers from 1 to N.

PROGRAM:

N = int(input())
for ctr in range(1,N+1):
    for printnum in range (1, ctr+1):
        print (printnum, end=" ")
    print ("")


Input:
5

Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

PROGRAM TO COUNT THE COMMON CHARACTERS IN TWO STRINGS:

STATEMENT:

Two string values S1 and S2 are passed as input. The program must print the count of common characters in the strings S1 and S2. Assume the alphabets in S1 and S2 will be in lower case.

PROGRAM;

str1 = input().strip()
str2 = input().strip()
uniquechars = set(str1)
commoncount = 0
for ch in uniquechars:
    if ch in str2:
        commoncount+=1

print (commoncount)

Input:
energy
every

Output:
3

Explanation:
The common characters are e,r,y

Friday, August 24, 2018

SAMPLE PYTHON PROGRAMS FOR BEGINNERS

PROGRAM TO PRINT THE DIFFERENCE BETWEEN THE LENGTH OF THE RECTANGLES:

STATEMENT:

Alen and Tim both own a tennis grass court and they decide to mow the lawn in and around the court which will cost them Rs.5 per square feet. Given the amount they spent to mow the lawn and the width of the court, find the difference between the length of the courts.


PROGRAM:

amounts = input().strip().split(" ")
widths = input().strip().split(" ")
amountAlen = int(amounts[0])
amountTim = int(amounts[1])
widthAlen = int(widths[0])
widthTim = int(widths[1])
lengthAlen = amountAlen/(5*widthAlen)
lengthTim = amountTim/(5*widthTim)
diff = abs(lengthAlen-lengthTim)
print ("%.2f" %diff)

Input:
17500 40000
50 80

Output:
30.00

Explanation:
Area of Alen's court = 17500/5 = 3500 sq.ft. Length = 3500/50 = 70
Area of Tim's court = 40000/5 = 8000 sq.ft. Length = 8000/80 = 100
Hence the difference = 100-70 = 30.00


PROGRAM TO CONCATENATE STRING ALPHABETICALLY:

STATEMENT:

Two string values S1 and S2 are passed as the input. The program must concatenate them depending on which string comes first in the alphabetical order.

PROGRAM:

s1 = input().strip()
s2 = input().strip()
values = [s1,s2]
values.sort()
for s in values:
    print (s, end="")

Input:
zoo
tiger

Output:
tigerzoo



Wednesday, August 22, 2018

VERY SIMPLE PYTHON PROGRAMS FOR BEGINNERS


PROGRAM TO PRINT THE NUMBER OF CHOCOLATES REMAINING:

STATEMENT:

Drek distributes C chocolates to school N students every Friday. The C chocolates are distributed among N students equally and the remaining chocolates R are given back to Drek.

As an example if C=100 and N=40, each student receives 2 chocolates and the balance 100-40*2 = 20 is given back.
If C=205 and N=20, then each student receives 10 chocolates and the balance 205-20*10 = 5 is given back.

Help the school to calculate the chocolates to be given back when C and N are passed as input.


PROGRAM:

C = int(input())
N = int(input())
print (C%N)

Input:
300
45

Output:
30

PROGRAM TO PRINT SUM OF EVEN NUMBERS FROM M TO N:

STATEMENT:

Two numbers M and N are passed as the input. The program must print the sum of even numbers from M to N (inclusive of M and N).


PROGRAM;

M = int(input())
N = int(input())
evensum = 0
for num in range(M,N+1):
    if num%2 ==  0:
        evensum+=num

print (evensum)

Input:
2
11

Output:
30

Explanation:
The even numbers from 2 to 11 are 2 4 6 8 10
Their sum is 30.



Saturday, August 18, 2018

INTERMEDIATE JAVA PROGRAMS FOR LEARNERS


PROGRAM TO PRINT THE DAY OF A GIVEN DATE:

STATEMENT:

The day corresponding to the first date of a given month is provided as input to the program. Then a specific date D of the month is provided. The program must  print the day (one among MON,TUE, WED, THU, FRI, SAT, SUN) of the date D.

PROGRAM;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String DAYS[] = new String[]{"SUN","MON","TUE","WED","THU","FRI","SAT"};
        List<String> DAYSLIST = Arrays.asList(DAYS);
        String dayone = sc.nextLine().trim();
        int date = sc.nextInt();
        int dayIndex = DAYSLIST.indexOf(dayone);
        for(int dateCounter=2; dateCounter <= date; dateCounter++){
            dayIndex++;
            if(dayIndex == 7){
                dayIndex=0;
            }
        }
     
        System.out.println(DAYS[dayIndex]);

    }

}

Input:
FRI
24

Output:
SUN

Explanation:
If it is Friday on 1st of the month, then 22nd will also be a Friday. Hence 24th of the month will be a Sunday. Hence SUN is printed.

REVERSE PATTERN PRINTING IN JAVA:

STATEMENT:

Based on the input value of N, the program must print the pattern described below.

Input Format:
First line will contain the value of N.

Output Format:
N lines will contain the number pattern as described below with each value separated by a single space.

PROGRAM::

import java.util.*;

public class Hello {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        for (int row = 1; row <= N; row++) {
            int printValue = N * (N + 1) / 2 - (row - 1);
            for (int col = 0; col < (N - row + 1); col++) {
                System.out.print(printValue+" ");
                printValue -= (N-col);
            }
            System.out.println("");
        }
    }

}

Input:
3

Output:
6 3 1
5 2
4

Monday, August 13, 2018

AVERAGE LEVEL JAVA PROGRAMS

PROGRAM TO ADD THE REVERSED NUMBER OF THE DATA:

STATEMENT:

A pair of numbers (X and Y) will be passed as input. The program must reverse the numbers and find the sum S. Then the sum S must be reversed and printed as output.

- If any leading zeroes are obtained while reversing any of the numerical values they should be discarded.


PROGRAM:

import java.util.*;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();
        int sum = reverse(x) + reverse(y);
        System.out.println(reverse(sum));

    }

    private static int reverse(int x) {
        StringBuilder sb = new StringBuilder(String.valueOf(x));
        return Integer.parseInt(sb.reverse().toString());
    }
}

Input:
305
794

Output:
1

Explanation:
305 and 794 when reversed are 503 and 497.
503+497 = 1000.
1000 when reversed is 1 which is printed as output.


PROGRAM TO PRINT THE NUMBER OF STEPS NEEDED TO FILL A CAN WITH WATER;

STATEMENT:

Two cans are with capacity X and Y liters. The program must determine the number of steps required to obtain exactly Z litres of liquid in one of the cans.
At the beginning both cans are empty. The following operations are counted as "steps".

- emptying a vessel,
- filling a vessel,
- pouring liquid from larger can to the smaller, without spilling, until one of the cans is either full or empty.

If it is not possible to obtain Z liters exactly then the output must be -1.

PROGRAM:

import java.util.*;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();
        int z = sc.nextInt();
        //Larger can is made as x
        if (x < y) {
            int temp = y;
            y = x;
            x = temp;
        }
        int fillCount = -1, currCount = 1; //currCount is made 1 to fill x
        boolean isSmallerCanFilled = false; //y will be the smaller can

        for (; x >= z; x -= y) {
            if (x == z) {
                fillCount = currCount;
                break;
            } else {
                if (isSmallerCanFilled) {
                    //We need to empty smaller can in step 1 and fill from larger can as step 2
                    currCount += 2;
                } else {
                    isSmallerCanFilled = true;
                    //Only filling from larger to smaller can as step 1. This happens only one time.
                    currCount += 1;
                }

            }
        }
        System.out.print(fillCount);
    }
}

Input:
5
2
3

Output:
2

Explanation:
Here X=5, Y=2
Step 1: Pour 5 liters of liquid into 5 liter can
Step 2: Pour 2 liters from 5 liter can into 2 liter can.
Now the 5 liter can will have 3 liters which is Z. Hence 2 steps are required.



Friday, August 10, 2018

JAVA PROGRAMS PART 3 FOR BEGINNERS

PROGRAM TO PRINT THE MONTH OF THE GIVEN DATA:

STATEMENT:


A date in DD-MM-YYYY format is passed as the input. The program must print the calendar month.
01 - January, 02 - February and so on till 12 - December.

PROGRAM;

import java.util.*;

public class Hello {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String months[] = {"January", "February", "March", "April", "May", "June", "July", "August",

"September", "October", "November", "December"};

        String dateInput = sc.nextLine();

        String DDMMYYYArray[] = dateInput.split("[-]");

        int month = Integer.parseInt(DDMMYYYArray[1]); //Second string is the month


        /* Subtract 1 as array index starts from zero */

        System.out.println(months[month - 1]);

    }
}

Input:
23-12-2016

Output:
December

 PROGRAM TO PRINT THE ODD INTEGERS IN A GIVEN NUMBER:

STATEMENT:

The program must accept two integers X and Y and print the odd integers between them.


STATEMENT:

import java.util.*;

public class Hello {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int X = sc.nextInt();

        int Y = sc.nextInt();

        int from = X, to = Y;

        while (++from < to) {

            if (from % 2 != 0) {

                System.out.print(from);

                System.out.print(" ");
            }
        }
    }
}

Input:
24
30

Output:
25 27 29