SlideShare a Scribd company logo
• Understand the problem
• Write the solution in plain English
• Break the problem into chunks
• Create a flow / write a pseudo-code
• Trace the solution with the test
cases/dry run - define the test
cases
• Write code
• Evaluate - Dry run
Building a near to
ideal solution
Problem: Find the longest word in the sentence
Input String : "The cat sat on the mat with another cat"
Step 1 Understanding the problem
Problem: Find the longest word in the sentence
To find the longest word we need to accept the
input from the user, and break the sentence
into words. Compare the length of each word
to find the word with the longest length.
Return the longest word as output.
Step 2 Writing the solution in plain English
Problem: Find the longest word in the sentence
Step 3 Breaking the problem into chunks
Identifying the pieces of the solution to solve
the problem.
- Take input
- Validate input
- Split the sentence into words
- Compare the length of the words
Step 4
Creating
the flow /
writing
pseudocode
Step 4 Creating the flow / writing pseudocode
Problem: Find the longest word in the sentence
1. Read sentence
2. Validate input
3. Init longestWordLength as 0
4. Check that the sentence has a word to process read word
from the sentence as currentWord
5. Check currentWordLength is greater than
longestWordLength, if yes, then record currentWord as
longestWord and its length in longestWordLength
6. Repeat step 3 to 5 until sentence has words to process
7. Return longestWord
Step 5
Trace the solution with the test cases/dry run - define
the test cases
Test Input Expected Output
Invalid input Do not provide input,
Press enter
Sentence is not provided.
Provide single word Hello The longest word is: Hello
Provide sentence with
single longest word
Satyamev Jayate
Provide sentence with
multiple longest word
The first longest word will
be provided
Hi Ajay , Hi Uday
The longest word is: Satyamev
The longest word is: Ajay
Test sentence provided
in problem statement
The cat sat on the mat
with another cat
The longest word is: another
Problem: Find the longest word in the sentence
Step 6
Writing code
Problem:
Find the
longest
word in the
sentence
/*
1. Read sentence
2. Validate input
3. Take longestWordLength as 0
4. Check sentence has word to process
Read word from sentence as currentWord
5. Check currentWord length is greater than longestWordLength
If yes, then record currentWord as longestWord and its length in longestWordLength
6. Repeat step 3 to 5 untill sentence has words to process
7. Return longestWord
*/
#include <stdio.h>
#include <string.h>
/*
Return next word from sentence
Input:
inputSentence: Input sentence to read word
wordStartPos: Start position of next word
word: Function keep word in it.
Return: nextWordStartPos
*/
int getWord(char* inputSentence, int wordStartPos, char* currWord)
{
int nextWordStartPos = 0;
int i = 0;
int j = 0;
// Start reading word from wordStartPos
for (i = wordStartPos; i <= strlen(inputSentence); i++)
{
// Skip the space, new line and end of line characters
if (inputSentence[i] != ' ' && inputSentence[i] != 'n' && inputSentence[i] != '0')
{
// Record current word
currWord[j++] = inputSentence[i];
Step 6
Writing code
Problem:
Find the
longest
word in the
sentence
}
else
{
// Found space, new line or end of line characters
// Finished reading word
// Terminate word by adding 0
currWord[j] = '0';
// Record current position of inputSentence as nextWordStartPos, we will use it in next pass
nextWordStartPos = i + 1;
// Skip rest of the sentence as we finished with reading word
break;
}
}
return nextWordStartPos;
}
/*
Check sentence has more words to process
Input:
inputSentence: Input sentence to read word
nextWordStartPos: Position in inputSentence untill we prcossed
Return:
hasMoreWords: 0 If we processed all words in sentence
hasMoreWords: 1 If word is available to process
*/
int hasMoreWords(char* inputSentence, int nextWordStartPos)
{
int hasMoreWords = 1;
if((nextWordStartPos >= strlen(inputSentence)) || inputSentence[nextWordStartPos] == '0')
{
// We reached end of sentence
// No more words to process
hasMoreWords = 0;
}
return hasMoreWords;
}
Step 6
Writing code
Problem:
Find the
longest
word in the
sentence
/*
Return longest word from sentence
Input:
inputSentence: Input sentence to read word
longestWord: Keep longest word in it.
*/
void getLongestWord(char* inputSentence, char* longestWord)
{
char currWord[64];
int i = 0;
int j = 0;
int currLongestWordLen = 0;
int nextWordStartPos = 0;
while(hasMoreWords(inputSentence, nextWordStartPos) == 1)
{
// Sentence has words which are still not processed
// Get next word from sentence
// Record next word start position which will be rquired in next pass
nextWordStartPos = getWord(inputSentence, nextWordStartPos, currWord);
if (strlen(currWord) > currLongestWordLen)
{
// Current word lenth is rater than current longest word, so we have new longest word record
it
strcpy(longestWord, currWord);
// Record length of new lonest word
currLongestWordLen = strlen(longestWord);
}
}
}
/*
Validate program input
Input:
inputSentence: Input sentence to read word
Step 6
Writing code
Problem:
Find the
longest
word in the
sentence
Return:
isValid: 0 If input is valid
isValid: 1 I input is not valid
*/
int validateInput(char* inputSentence)
{
int isValid = 1;
// Check input string is provided
// we are comparing the length to be greater then 1 as fgets puts the enter/return as well in the input while accepting
the input.
if(strlen(inputSentence) > 1)
{
isValid = 0;
}
return isValid;
}
}
int main()
{
// Boundaries
// Handling the sentence of max legnth 512
// Handling longest word of upto legnth 64
char inputSentence[512], longestWord[64];
// Read input sentence from command line
printf("Enter a string:n");
fgets(inputSentence, sizeof(inputSentence), stdin);
if(validateInput(inputSentence) == 1)
{
// Input is invalid
printf("Sentence is not provided.n");
return 1;
}
Step 6
Writing code
Problem:
Find the
longest
word in the
sentence
// Find Longest word in sentence
// The longest word will be returned in parameter longestWord
getLongestWord(inputSentence, longestWord);
printf("The longest word is: ");
puts(longestWord);
return 0;
}
Problem: Find the longest word in the sentence
Test Input Expected Output
Invalid input Do not provide input,
Press enter
Sentence is not provided.
Provide single word Hello The longest word is: Hello
Provide sentence with
single longest word
Satyamev Jayate
Provide sentence with
multiple longest word
The first longest word will
be provided
Hi Ajay , Hi Uday
The longest word is: Satyamev
The longest word is: Ajay
Test sentence provided
in problem statement
The cat sat on the mat
with another cat
The longest word is: another
Step 7 Evaluate - Dry run

More Related Content

More from Mithi Software Technologies Pvt Ltd

Which of the 6 methods of email forwarding is suitable and secure for your re...
Which of the 6 methods of email forwarding is suitable and secure for your re...Which of the 6 methods of email forwarding is suitable and secure for your re...
Which of the 6 methods of email forwarding is suitable and secure for your re...
Mithi Software Technologies Pvt Ltd
 
the Mithi culture code
the Mithi culture codethe Mithi culture code
the Mithi culture code
Mithi Software Technologies Pvt Ltd
 
How to choose the right company - By Navin Kabra
How to choose the right company - By Navin KabraHow to choose the right company - By Navin Kabra
How to choose the right company - By Navin Kabra
Mithi Software Technologies Pvt Ltd
 
How to choose the right company to start your career with!
How to choose the right company to start your career with!How to choose the right company to start your career with!
How to choose the right company to start your career with!
Mithi Software Technologies Pvt Ltd
 
Preparing for a life OF work
Preparing for a life OF workPreparing for a life OF work
Preparing for a life OF work
Mithi Software Technologies Pvt Ltd
 
Academy Webinar: Approaching a problem and developing an enduring solution
Academy Webinar: Approaching a problem and developing an enduring solutionAcademy Webinar: Approaching a problem and developing an enduring solution
Academy Webinar: Approaching a problem and developing an enduring solution
Mithi Software Technologies Pvt Ltd
 
Mithi Culture Code
Mithi Culture CodeMithi Culture Code
The Mithi Culture Code
The Mithi Culture CodeThe Mithi Culture Code
The Mithi Culture Code
Mithi Software Technologies Pvt Ltd
 
Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...
Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...
Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...
Mithi Software Technologies Pvt Ltd
 
Back to Front Vision for Mithi's Collaboration Environment
Back to Front Vision for Mithi's Collaboration Environment Back to Front Vision for Mithi's Collaboration Environment
Back to Front Vision for Mithi's Collaboration Environment
Mithi Software Technologies Pvt Ltd
 
Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai
Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai
Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai
Mithi Software Technologies Pvt Ltd
 
How Vaultastic Works
How Vaultastic WorksHow Vaultastic Works
Workplace Productivity through Effective Collaboration
Workplace Productivity through Effective CollaborationWorkplace Productivity through Effective Collaboration
Workplace Productivity through Effective Collaboration
Mithi Software Technologies Pvt Ltd
 
Mithi SkyConnect Advantage
Mithi SkyConnect AdvantageMithi SkyConnect Advantage
Mithi SkyConnect Advantage
Mithi Software Technologies Pvt Ltd
 
Mithi Pre Placement
Mithi Pre PlacementMithi Pre Placement
Less effort more money - 3 easy steps to do business
Less effort more money - 3 easy steps to do businessLess effort more money - 3 easy steps to do business
Less effort more money - 3 easy steps to do business
Mithi Software Technologies Pvt Ltd
 
Product overview of SkyConnect Email and Collaboration Solution
Product overview of SkyConnect Email and Collaboration SolutionProduct overview of SkyConnect Email and Collaboration Solution
Product overview of SkyConnect Email and Collaboration Solution
Mithi Software Technologies Pvt Ltd
 
Aegon Religare - Improving Collaboration and Productivity with BYOD
Aegon Religare - Improving Collaboration and Productivity with BYODAegon Religare - Improving Collaboration and Productivity with BYOD
Aegon Religare - Improving Collaboration and Productivity with BYOD
Mithi Software Technologies Pvt Ltd
 

More from Mithi Software Technologies Pvt Ltd (20)

Which of the 6 methods of email forwarding is suitable and secure for your re...
Which of the 6 methods of email forwarding is suitable and secure for your re...Which of the 6 methods of email forwarding is suitable and secure for your re...
Which of the 6 methods of email forwarding is suitable and secure for your re...
 
the Mithi culture code
the Mithi culture codethe Mithi culture code
the Mithi culture code
 
How to choose the right company - By Navin Kabra
How to choose the right company - By Navin KabraHow to choose the right company - By Navin Kabra
How to choose the right company - By Navin Kabra
 
How to choose the right company to start your career with!
How to choose the right company to start your career with!How to choose the right company to start your career with!
How to choose the right company to start your career with!
 
Preparing for a life OF work
Preparing for a life OF workPreparing for a life OF work
Preparing for a life OF work
 
Academy Webinar: Approaching a problem and developing an enduring solution
Academy Webinar: Approaching a problem and developing an enduring solutionAcademy Webinar: Approaching a problem and developing an enduring solution
Academy Webinar: Approaching a problem and developing an enduring solution
 
Mithi Culture Code
Mithi Culture CodeMithi Culture Code
Mithi Culture Code
 
The Mithi Culture Code
The Mithi Culture CodeThe Mithi Culture Code
The Mithi Culture Code
 
Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...
Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...
Webinar: 2018 Product Roadmap for Secure, Scalable, Productive Team Collabora...
 
Back to Front Vision for Mithi's Collaboration Environment
Back to Front Vision for Mithi's Collaboration Environment Back to Front Vision for Mithi's Collaboration Environment
Back to Front Vision for Mithi's Collaboration Environment
 
Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai
Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai
Accelerating Innovation: Mithi's Journey to the Cloud | AWS Summit Mumbai
 
How Vaultastic Works
How Vaultastic WorksHow Vaultastic Works
How Vaultastic Works
 
Workplace Productivity through Effective Collaboration
Workplace Productivity through Effective CollaborationWorkplace Productivity through Effective Collaboration
Workplace Productivity through Effective Collaboration
 
Mithi SkyConnect Advantage
Mithi SkyConnect AdvantageMithi SkyConnect Advantage
Mithi SkyConnect Advantage
 
Mithi Pre Placement
Mithi Pre PlacementMithi Pre Placement
Mithi Pre Placement
 
For sme's cloud based services is the default way forward
For sme's cloud based services is the default way forwardFor sme's cloud based services is the default way forward
For sme's cloud based services is the default way forward
 
Less effort more money - 3 easy steps to do business
Less effort more money - 3 easy steps to do businessLess effort more money - 3 easy steps to do business
Less effort more money - 3 easy steps to do business
 
About Us
About UsAbout Us
About Us
 
Product overview of SkyConnect Email and Collaboration Solution
Product overview of SkyConnect Email and Collaboration SolutionProduct overview of SkyConnect Email and Collaboration Solution
Product overview of SkyConnect Email and Collaboration Solution
 
Aegon Religare - Improving Collaboration and Productivity with BYOD
Aegon Religare - Improving Collaboration and Productivity with BYODAegon Religare - Improving Collaboration and Productivity with BYOD
Aegon Religare - Improving Collaboration and Productivity with BYOD
 

Recently uploaded

GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 

Recently uploaded (20)

GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 

Solution Flow: Approaching a problem and developing an enduring solution

  • 1. • Understand the problem • Write the solution in plain English • Break the problem into chunks • Create a flow / write a pseudo-code • Trace the solution with the test cases/dry run - define the test cases • Write code • Evaluate - Dry run Building a near to ideal solution
  • 2. Problem: Find the longest word in the sentence Input String : "The cat sat on the mat with another cat" Step 1 Understanding the problem
  • 3. Problem: Find the longest word in the sentence To find the longest word we need to accept the input from the user, and break the sentence into words. Compare the length of each word to find the word with the longest length. Return the longest word as output. Step 2 Writing the solution in plain English
  • 4. Problem: Find the longest word in the sentence Step 3 Breaking the problem into chunks Identifying the pieces of the solution to solve the problem. - Take input - Validate input - Split the sentence into words - Compare the length of the words
  • 5. Step 4 Creating the flow / writing pseudocode
  • 6. Step 4 Creating the flow / writing pseudocode Problem: Find the longest word in the sentence 1. Read sentence 2. Validate input 3. Init longestWordLength as 0 4. Check that the sentence has a word to process read word from the sentence as currentWord 5. Check currentWordLength is greater than longestWordLength, if yes, then record currentWord as longestWord and its length in longestWordLength 6. Repeat step 3 to 5 until sentence has words to process 7. Return longestWord
  • 7. Step 5 Trace the solution with the test cases/dry run - define the test cases Test Input Expected Output Invalid input Do not provide input, Press enter Sentence is not provided. Provide single word Hello The longest word is: Hello Provide sentence with single longest word Satyamev Jayate Provide sentence with multiple longest word The first longest word will be provided Hi Ajay , Hi Uday The longest word is: Satyamev The longest word is: Ajay Test sentence provided in problem statement The cat sat on the mat with another cat The longest word is: another Problem: Find the longest word in the sentence
  • 8. Step 6 Writing code Problem: Find the longest word in the sentence /* 1. Read sentence 2. Validate input 3. Take longestWordLength as 0 4. Check sentence has word to process Read word from sentence as currentWord 5. Check currentWord length is greater than longestWordLength If yes, then record currentWord as longestWord and its length in longestWordLength 6. Repeat step 3 to 5 untill sentence has words to process 7. Return longestWord */ #include <stdio.h> #include <string.h> /* Return next word from sentence Input: inputSentence: Input sentence to read word wordStartPos: Start position of next word word: Function keep word in it. Return: nextWordStartPos */ int getWord(char* inputSentence, int wordStartPos, char* currWord) { int nextWordStartPos = 0; int i = 0; int j = 0; // Start reading word from wordStartPos for (i = wordStartPos; i <= strlen(inputSentence); i++) { // Skip the space, new line and end of line characters if (inputSentence[i] != ' ' && inputSentence[i] != 'n' && inputSentence[i] != '0') { // Record current word currWord[j++] = inputSentence[i];
  • 9. Step 6 Writing code Problem: Find the longest word in the sentence } else { // Found space, new line or end of line characters // Finished reading word // Terminate word by adding 0 currWord[j] = '0'; // Record current position of inputSentence as nextWordStartPos, we will use it in next pass nextWordStartPos = i + 1; // Skip rest of the sentence as we finished with reading word break; } } return nextWordStartPos; } /* Check sentence has more words to process Input: inputSentence: Input sentence to read word nextWordStartPos: Position in inputSentence untill we prcossed Return: hasMoreWords: 0 If we processed all words in sentence hasMoreWords: 1 If word is available to process */ int hasMoreWords(char* inputSentence, int nextWordStartPos) { int hasMoreWords = 1; if((nextWordStartPos >= strlen(inputSentence)) || inputSentence[nextWordStartPos] == '0') { // We reached end of sentence // No more words to process hasMoreWords = 0; } return hasMoreWords; }
  • 10. Step 6 Writing code Problem: Find the longest word in the sentence /* Return longest word from sentence Input: inputSentence: Input sentence to read word longestWord: Keep longest word in it. */ void getLongestWord(char* inputSentence, char* longestWord) { char currWord[64]; int i = 0; int j = 0; int currLongestWordLen = 0; int nextWordStartPos = 0; while(hasMoreWords(inputSentence, nextWordStartPos) == 1) { // Sentence has words which are still not processed // Get next word from sentence // Record next word start position which will be rquired in next pass nextWordStartPos = getWord(inputSentence, nextWordStartPos, currWord); if (strlen(currWord) > currLongestWordLen) { // Current word lenth is rater than current longest word, so we have new longest word record it strcpy(longestWord, currWord); // Record length of new lonest word currLongestWordLen = strlen(longestWord); } } } /* Validate program input Input: inputSentence: Input sentence to read word
  • 11. Step 6 Writing code Problem: Find the longest word in the sentence Return: isValid: 0 If input is valid isValid: 1 I input is not valid */ int validateInput(char* inputSentence) { int isValid = 1; // Check input string is provided // we are comparing the length to be greater then 1 as fgets puts the enter/return as well in the input while accepting the input. if(strlen(inputSentence) > 1) { isValid = 0; } return isValid; } } int main() { // Boundaries // Handling the sentence of max legnth 512 // Handling longest word of upto legnth 64 char inputSentence[512], longestWord[64]; // Read input sentence from command line printf("Enter a string:n"); fgets(inputSentence, sizeof(inputSentence), stdin); if(validateInput(inputSentence) == 1) { // Input is invalid printf("Sentence is not provided.n"); return 1; }
  • 12. Step 6 Writing code Problem: Find the longest word in the sentence // Find Longest word in sentence // The longest word will be returned in parameter longestWord getLongestWord(inputSentence, longestWord); printf("The longest word is: "); puts(longestWord); return 0; }
  • 13. Problem: Find the longest word in the sentence Test Input Expected Output Invalid input Do not provide input, Press enter Sentence is not provided. Provide single word Hello The longest word is: Hello Provide sentence with single longest word Satyamev Jayate Provide sentence with multiple longest word The first longest word will be provided Hi Ajay , Hi Uday The longest word is: Satyamev The longest word is: Ajay Test sentence provided in problem statement The cat sat on the mat with another cat The longest word is: another Step 7 Evaluate - Dry run