Kjell, Chapter 24 Exercise 1 Write a program that repeatedly asks the user for a
ID: 3682359 • Letter: K
Question
Kjell, Chapter 24 Exercise 1
Write a program that repeatedly asks the user for a string and then calculates and prints out the string length. Stop the program when the string is empty (when the user hits "enter" without anything else on the line.)
Be sure to reserve enough memory in the .data for the string. Use indexed addressing to scan through the string. Strings read in with the trap handler service include a ' ' character at the end, followed by the null termination. Don't count the ' ' or the null as part of the string length.
http://chortle.ccsu.edu/AssemblyTutorial/Chapter-24/ass24programs.html
In the Settings menu of SPIM set Bare Machine OFF, Allow Pseudo Instructions ON, Load Trap File ON, Delayed BranchesOFF, Delayed Loads OFF, Mapped IO ON, Quiet OFF.
Run the programs by loading the trap handler (as explained in the chapter) and clicking SimulatorGo and then OK in the pop-up panel.
Explanation / Answer
Programme:
#include<stdio.h>
//#include<conio.h>
int string_ln(char*p) /* p=&str[0] */
{
int count = 0;
while (*p != '') {
count++;
p++;
}
return count;
}
void main() {
char str[20];
int length;
do{
printf(" Enter any string : ");
gets(str);
fflush(stdout);
length = string_ln(str);
if(length==0)
{
printf("Bye.. ");
break;
}
else
printf("The length of the given string %s is : %d ", str, length);
}while(str[0]!=' ');
}
Output:
Enter any string : ssssssssssssss
The length of the given string ssssssssssssss is : 14
Enter any string : ssss
The length of the given string ssss is : 4
Enter any string : aaaa
The length of the given string aaaa is : 4
Enter any string : a
The length of the given string a is : 1
Enter any string :
Bye..
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.