Write all your answers for each part in a plaintext file cal

Write all your answers for each part in a plaintext file called a5p0.txt. a) A palindrome is a word (or string) that is same when read left-to-right and right-to-left. For example, mom, kayak and #!@@!# are palindromes while cat, dog and drawer are not. Think of an algorithm to test whether a given string is a palindrome or not. Write your algorithm in pseudocode. b) Briefly describe when, in general, you should use a for loop instead of a while loop and when you should use a while loop instead of a for loop. Save your program in a file called a5p0.txt and add it to your submission zip file.

Solution

// Algorithm to check a string is Pallindrome

boolean isPallindrome(String str){
  
   1. j <- length of str
   2. i <- 1 // initialize a int variable with 0

   // traverse input string from front and back using index i and j respectively

   3. while i < j do:
       // if current character from front and back are not equal then it is not pallindrome
       if str[i] != str[j]
           return false //
       i = i + 1
       j = j -1

   4. // you reach here, means str is pallindrome
   return true
}


A for loop is just a special kind of while loop, which happens to deal with incrementing a variable. You can emulate a for loop with a while loop in any language.There is no specific situation where one is better than the other (although for readability reasons you should prefer a for loop when you\'re doing simple incremental loops since most people can easily tell what\'s going on).

A for loop is used where you know at compile time how many times this loop will execute.

A while loop is normally used in a scenario where you don\'t know how many times a loop will actually execute at runtime.

For can behave like while:

while(true)
{
}

for(;;)
{
}
And while can behave like for:

int x = 0;
while(x < 10)
{
x++;
}

for(x = 0; x < 10; x++)
{
}

 Write all your answers for each part in a plaintext file called a5p0.txt. a) A palindrome is a word (or string) that is same when read left-to-right and right-

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site