Minggu, 23 Maret 2014

3.34 (Hollow Square of Asterisks) 

Modify the program you wrote in Exercise 3.33 so that it prints a hollow square. 

C Program:
#include <stdio.h>
int main(){

    int size, i, j;

    size = 5;

    for(i=1; i<=size; i++){

       if(i==1 || i==size){

          for(j=1; j<=size; j++){

             printf("*");

          }

       }

       else{

          for(j=1; j<=size; j++) {

             if(j==1 || j==size) printf("*"); else printf(" ");

          }

       }

       printf("\n");

    }

    system("pause");

}
Output:







3.35 (Palindrome Tester)

A palindrome is a number or a text phrase that reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit integer and determines whether or not it’s a palindrome. [Hint: Use the division and remainder operators to separate the number into its individual digits.]

C Program: 
#include <stdio.h>
int main()

{

  int n, reverse=0, rem,temp;

  printf("Enter an integer: ");

  scanf("%d", &n);

  temp=n;

  while(temp!=0)

  {
     rem=temp%10;
     reverse=reverse*10+rem;

     temp/=10;

  }

/* Checking if number entered by user and it's reverse number is equal. */

  if(reverse==n)

      printf("%d is a palindrome.",n);

  else

      printf("%d is not a palindrome.",n);

      system("pause");

  return 0;

}
Output:








3.36 (Printing the Decimal Equivalent of a Binary Number)

Input an integer containing only 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent. [Hint: Use the remainder and division operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the decimal number system, in which the rightmost digit has a positional value of 1, and the next digit left has a positional value of 10, then 100, then 1000, and so on, in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8 or 13.]

C Program: 
#include <stdio.h> int binary_conversion(int);int main(){   int num, bin;   printf("Enter a decimal number: ");   scanf("%d", &num);   bin = binary_conversion(num);   printf("The binary equivalent of %d is %d\n", num, bin);   system("pause");} int binary_conversion(int num){    if (num == 0)    { return 0; }    else    { return (num % 2) + 10 * binary_conversion(num / 2);  }}
Output:

0 komentar:

Posting Komentar