Creating a character array in mips - qtspim

I need help in making the character array str[] in mips and also reading out that array. I have to functions where I ask the user to enter a base between 2 and 36 and then prompt them to enter a number in that base and that number is converted to base 10(decimal).
int convert2dec(char *str, int base)
{
int j, val;
val = 0;
j = 0;
while (str[j] > 13) {
if (str[j] > 57)
val = val * base + str[j]-87;
else
val = val * base + str[j] - 48;
j++;
}
return val;
}
int main(int argc, char *argv[])
{
int X;
char str[256];
printf("Please the base (between 2 and 36 in decimal): ");
scanf("%d", &X);
printf("Please a number base %d: ", X);
scanf("%s", str);
printf("The decimal value is %d\n", convert2dec(str,X));
return 0;
}

I can make a regular array, but im just confused with char arrays in mips. Im not asking to answer any problems for me. Im just cunfused with char arrays in mips and reading them out.

Related

Array prints random symbols

I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output
#include <stdlib.h>
#include <stdio.h>
int main(){
int i = 0;
char list1[7];
char list2[7];
char list3[7];
while(i <= 3){
char name;
int price;
printf("Give me the product \n");
scanf("%s", &name);
printf("Give the price \n");
scanf("%d", &price);
if(price == 1){
list1[i] = list1[i] + name;
} else if(price == 2){
list2[i] = list2[i] +name;
} else if(price == 3){
list3[i] = list3[i] +name;
} else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", &name);
("Give the price \n");
scanf("%d", &price);
}
i = i + 1;
}
for (int z = 0; z <= 3; z++){
printf("%s",list1);
printf("\n");
printf("%s",list2);
printf("\n");
printf("%s",list3);
printf("\n");
}
}
#include <stdlib.h>
//Need string.h library to use strcopy
#include <string.h>
#include <stdio.h>
#define MAX_CHAR_SIZE 10
int main(){
//We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a string
char list1[MAX_CHAR_SIZE];
char list2[MAX_CHAR_SIZE];
char list3[MAX_CHAR_SIZE];
char name[MAX_CHAR_SIZE];
//I prefer unsigned if you know you don't to go in negative value
unsigned int price;
//Prefer for over while if you know how many time you need to loop
for (int i = 0; i < 3; i++){
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
if(price == 1){
//Copy name in list 1, you can't copy an array of x char in a single case of another array, 1 case of an array = 1 char
strcpy(list1, name);
}
else if(price == 2){
strcpy(list2, name);
}
else if(price == 3){
strcpy(list3, name);
}
else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
}
}
//No need to loop over this 3 time only 1 is enough
printf("%s \n",list1);
printf("%s \n",list2);
printf("%s \n",list3);
}
I add comment over things I changed to make the initial objectives, IDK if it's the right goal but at least you got the same character in input and output, there was many things that wasn't right in your code you simply can't add the hexadecimal value of two character together to overwrite, you got to make something like list[I] = name[I].
And in C since we don't have the string type you got to create an array of char to make one AND BE SURE TO GET THE RIGHT SIZE TO FIT '\0'.
If it's your final exam a friendly advice, train a lot.
Looks like you forgot printf in one of your lines. Change ("Give the price\n"); to printf("give the price\n");.
It should work if I understand your question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 10
int main(){
int n; //no of products
printf("Enter no. of products: ");
scanf("%d", &n);
char name[n][MAX_LENGTH]; //create multidimensional array to store namme
unsigned int price[n]; //array to store price. index will be similar to name
for (int i = 0; i < n; i++){ //Enter details
printf("Enter name: ");
scanf("%s", name[i]);
printf("Enter price: ");
scanf("%u", &price[i]);
}
int N = n;
while (N > 0){ //Run loop until index bigger than zero
char temp_string[MAX_LENGTH]; //create temporary variable
unsigned int temp_price; //to store values
int max_price_index = 0; //Index where max value is stored
for (int i = 1; i < N; i++){ //start loop from till end to search each value
if(price[i] > price[max_price_index]) //If searched value is bigger thar previous one(default at index 0)
max_price_index = i; //the replace it
}
strcpy(temp_string, name[N - 1]); //in next 7 lines name and price at max index is
strcpy(name[N - 1], name[max_price_index]); //swapped with values at index N (which is last of scope)
strcpy(name[max_price_index], temp_string);
temp_price = price[N - 1];
price[N - 1] = price[max_price_index];
price[max_price_index] = temp_price;
N--; //reduce the index by 1 making last value which was preiously maximum out of scope
}
for (int i = 0; i < n; i++){ //print details
printf("Name: %s\nPrice: %u\n", name[i], price[i]);
}
}

Recursively convert a given string to the number it represents

Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.
I only get the first digit of my string as the output. E.g "1234" as 1 or "231" as 2. Which makes me think there may be an error in my recursive function (the base case seems fine though) but I cant figure out what it is.
#include <math.h>
#include <cmath>
#include <iostream>
using namespace std;
int lenght (char input[]){
int count = 0;
for (int i=0 ; input[i] != '\0' ; i++){
count++;
}
return count;
}
//helper
int stringToNumber(char input[], int start ) {
int len = lenght(input);
//base case
if(start ==0){
return int (input[start]) - 48;
}
int a = stringToNumber(input , start+1);
int b = int(input[start]) - 48;
int k = pow(10, len-1);
return k*b + a;
}
int stringToNumber(char input[]) {
return stringToNumber(input, 0);
}
int main() {
char input[50];
cin >> input;
cout << stringToNumber(input) << endl;
}
Sample Input 1 :
1231
Sample Output 1:
1231
What my code generates: 1
Converting string to decimal integer - is actually converting a number from decimal to binary form. I.e. each digit is a mod of 10.
I.e. for the 1234 it can be done done like 1 * 1000 + 2 * 100 + 3 * 10 + 4
or (1*10)+2, (12*10)+3, (123*10)+4. Second algorithm can be implemented like next recursive function:
constexpr uintmax_t atou(const char* a,uintmax_t ret = 0) noexcept {
return '\0' == *a ? ret : atou(a+1, (ret * 10) + ( *a - '0') );
}
i.e. you are scanning a string for digits, until '\0' end of line character (or std::isspace for example), if more digits in the string multiply result on 10 and add the next digit to the result.
static_assert( 1234 == atou("1234"), "1234 expected" );
Try this code:
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
int convert(char c[]) {
if (c[0]=='\0') {
return 0;
} else {
int d = strlen(c) - 1;
int p = pow(10, d);
int k = int(c[0]) - 48; // ASCII value of '0' is 48
return (k * p + convert(c + 1));
}
}
int main() {
int n;
cin >> n;
char c[n];
cin >> c;
cout << convert(c);
}
public class solution {
public static int convertStringToInt(String input){
// Write your code here
if(input.length()<1)
{
return 0;
}
return input.charAt(input.length()-1)-'0'+(10*convertStringToInt(input.substring(0,input.length()-1)));
}
}

Subtracting ASCII character/values in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This a function of a code I wrote that subtracts two values which are both of type character over and over again to get a text, but the result is not a text of string but symbols instead.
I checked by cout that the keyLetters and analysis have both correct values in ASCII and clear letters before converting them to int.
The lengthText is correct too.
keyLetters is a word of 5 letters.
void originalText(string analysis, string keyLetters) {
int lengthText=analysis.length();
char originText[2000];
int hold;
int k;
for (int i=0; i<lengthText; i++) {
if(i%5==0)
k=0;
hold=keyLetters[k]-analysis[i];
if (hold<=0)
hold*=-1;
originText[i]=(char)hold;
cout<<originText[i];
k++;
}
}
A screenshot of the result I get:
Both keyLetters and analysis consist of characters between 'a' and 'z'.
That means the difference between characters in these two can be from -25 ('a' - 'z') up to +25 ('z' - 'a').
Then you want to represent this difference using ascii characters, multiplicing by -1 the negative case. Nothing simpler:
void originalText(string analysis, string keyLetters) {
int lengthText = analysis.length();
char originText[2000];
int hold;
int k;
for (int i = 0; i < lengthText; i++) {
if (i % 5 == 0) {
k = 0;
}
hold = keyLetters[k] - analysis[i];
if (hold < 0) {
hold *= -1;
}
originText[i] = (char)hold + 'a';
cout << originText[i];
k++;
}
}
You need shift the value in range <0,25> to printable small ascii characters <'a','z'> by adding a 'a' ascii value, that is 97. The range <0,25> in ascii are just control characters.
This will result in:
The decrypted text:
oncegpmnahioethejewasalihtpegirpehmwantedhoplacallthedacandihedidnmtcareabmuhhejshudcahallinschomlherlarenhsgetangjcatherallhhetimebutihedidnmtcareabmuhhejparentifeelingiwhethejthecareangrymriadiheeaisgchabadgirplehuinohbeashejnefejeverhakecaremfevejchhingarogndcogsharhingfjoocogrlarenhstilpcogshudieiatichooltakealpthatieriogslcbestmfpucknmtheshorcdmesnohfiniihherethereismojetmihthatgirlonedaceenhtmschomlwhichiiuniveriitcactualpcbgtleolletendhosacabogtitschmolhhatihiimojecommonandidonnohknmwanyeacthatgirlofcogriewenhtognivejsitymrcollegeifihavetmsacwhenihegohopdejlikeehenshebecameeighheenceariopdsmahuniversitcthereeaiapotmfitudcforhejtodoehichihehohallcicrewgpsmshecjiedandcriedalohahnighhsfhejshecamhmmeandherkindpajentsasqedhejabmuhthereasmnforhejunitmppabpeteajsthaheairgnningouhfjomhejeyesconhinuogspchmwevejsherefgsedtmtellmrsacanyhhingiinceiheeantedtmshayalmnehhatnighthereishwasfglfilledsoathhahnighhshesleltaloneinthedarqeihhmutanconebesideihejtmeahchhejandtmtakecajeofherinhersleepingasshedidhoherlajenhsanditgdiesehenshewascoungersmthecccpehasgothejrogndshapnotfrmmnmwherebgtbecauseofareaionandthatjeaionisbecauiehhingieillcomebackholeolleafhejthecdidhheminanctimeeihhmutanceajningmralejt
As to why this doesn't give the correct text, I leave that to OP, because i don't get this method of encryption.
The whole program:
#include <iostream>
#include <string>
#include <fstream>
#include <cmath>
using namespace std;
string encryptText(string, string);
string cryptanalyzeText(string);
void originalText(string, string);
int main() {
string text, analysis;
string key;
text = "onceuponatimetherewasalittlegirlwhowantedtoplayallthedayandshedidnotcareaboutherstudyatallinschoolherparentsgetangryatherallthetimebutshedidnotcareaboutherparentsfeelingswhethertheyareangryorsadshewassuchabadgirlletusnotbeasherneverevertakecareofeverythingaroundyoustartingfromyourparentstillyoustudiesatschooltakeallthatseriouslybestoflucknothestorydoesnotfinishherethereismoretoitthatgirlonedaywenttoschoolwhichisuniversityactuallybutpeopletendtosayaboutitschoolthatitismorecommonandidonnotknowanywaythatgirlofcoursewenttouniversityorcollegeifihavetosaywhenshegotolderlikewhenshebecameeighteenyearsoldsoatuniversitytherewasalotofstudyforhertodowhichshetotallyscrewupsoshecriedandcriedalotatnightsftershecamhomeandherkindparentsaskedheraboutthereasonforherunstoppabletearsthatwasrunningoutfromhereyescontinuouslyhoweversherefusedtotellorsayanythingsinceshewantedtostayalonethatnightherwishwasfulfilledsoatthatnightshesleptaloneinthedarkwithoutanyonebesideshertowatchherandtotakecareofherinhersleepingasshedidtoherparentsandstudieswhenshewasyoungersothecyclehasgotherroundshapnotfromnowherebutbecauseofareasonandthatreasonisbecausethingswillcomebacktopeopleaftertheydidtheminanytimewithoutanywarningoralert";
analysis = "qegegrfrafkdittgiiwmurpifvcigutcahayrrtqfkspxcpelxvyidmarrdejvhippfxcmtvebawkledukydkckelxkewctqfphqtgerqpkwgqvrrgdarxhqtrplfjvxiygsytejvhippfxcmtvebawkledrrvezvjjeqnzrgeyyittgixhqarvempxvyatjedejvaaeulghmdrhgutcpefwjrofdvestgirehgiivqtkekqerveahvzedaklizirvogpucogukerfkekfdqdcogtgerqpkwtunccogukydugjeteeysoxvroemncxhmvjiruqlwlkdvwtahcycwpfxhquksrkffiszqkjizkjlhqtvxhqtvmsyqiitakkxhmvxmrxqeidmaninfvfwctqfpwtktliewemvqtjmtkctxumnccbgvgiobnvxezfkssmarfogvzxsojfslfjrxifkjqodgtsmyqeenpkusnzqkonayrryicpxhmvxmrxqwgogtjiwqpkxogpzzeduzxyattslxgxiirkyevqvfwakyyinejvkofqchednzoeijvrstgsicmoviisjkiezavereqchsackynuxvvsuvpxhqtvaaeccstahjxupawsrtgixopqnliojjlefqkelxajgrqyltsauyicdkvhazftviqfrpofckrisjkwffgiwhqerqhaovenpjvvkuputadgexsmubidtgiebawkxhqtvesapwsrtgiynevftpmdcitqciwttckaaetlrnupxsufhismtgiiyqutsnfkeyogucchayvzeduyirqhlwepvfxexnfvsmarryfjzrgekegeejvaazvvhtaukeymnfrefjrxnuiyxhqtnmstyrwfgnwmlxguwomvklafpzkhfuyisxggxaxqeiizvyidmtbaifjfytmppsnqdvwipgjledvfaafeyledcehtavroeociiorjvvizjvvsxgvtizirwstgumdfqyirbciinfurrdevlhiqunlezuyiwmupsuzivvsavyickecihmuxsttgivogpuwhmrestrtfqnayyirqdlxbqerysqqwerqcjsnmpuxhmviiaeqemsngteuegklizijaixntsmqdrgkfqgiobnveffgixhqaumdfjvqizcectuovaifjfytmppaadpzrgatrpedv";
cout<<"\n1- The original text:\n"<<text;
cout<<"\n\nEnter a key of type string: ";
key = "cream";
cout<<endl;
cout<<"The text after it has been encrypted:\n"<<encryptText(text, key)<<endl;
cout<<"\n2- An encrpted text:\n"<<analysis;
string keyLetters= cryptanalyzeText(analysis);
cout<<"\n\nThe key is: "<<keyLetters<<endl<<endl;
cout<<"The decrypted text:\n";
originalText(analysis, keyLetters);
cout<<endl<<endl;;
return 0;
}
string encryptText(string text, string key) {
int lengthText=text.length();
int lengthKey=key.length();
int count=0;
for (int i=0; i<lengthText; i++) {
text[i]=key[count];
if (count<lengthKey-1)
count++;
else
count=0;
}
return text;
}
string cryptanalyzeText(string analysis) {
string keyLetters="aaaaa";
char ch;
int i;
int lengthText=analysis.length();
for (int keyPlace=0; keyPlace<6 ; keyPlace++) {
int alphabet[26]={0};
for (i=keyPlace; i<lengthText; i=i+5) {
ch=analysis[i];
alphabet[ch - 'a']++;
}
int max=alphabet[0];
int maxPlace=0;
for (int j=1; j<26; j++) {
if(max<alphabet[j]) {
max=alphabet[j];
maxPlace=j;
}
}
keyLetters[keyPlace]=maxPlace-4;
if (keyLetters[keyPlace]<0)
keyLetters[keyPlace]+=26+97;
else
keyLetters[keyPlace]+=97;
}
return keyLetters;
}
void originalText(string analysis, string keyLetters) {
int lengthText=analysis.length();
char originText[2000];
int hold;
int k;
for (int i = 0; i < lengthText; i++) {
if (i % 5 == 0) {
k=0;
}
hold = keyLetters[k] - analysis[i];
if (hold < 0) {
hold *= -1;
}
originText[i] = (char)hold + 'a';
cout << originText[i];
k++;
}
}
It appeared that since the encrypted text has been generated by %26 (mod 26), the values of the letters that was larger than 26 lost its original values. So when they have been decrypted, they were generated as incorrect letters. That's why I had to return the 26 they have lost, before doing the subtraction procedure, as it will be subtracted correctly.
void originalText(string analysis, string keyLetters) {
int lengthText=analysis.length();
char originText[2000];
int hold;
int k;
for (int i = 0; i < lengthText; i++) {
if (i % 5 == 0) {
k=0;
}
hold = (analysis[i]+26)-keyLetters[k];
if (hold < 0) {
hold *= -1;
}
hold%=26;
originText[i] = (char)hold + 'a';
cout << originText[i];
k++;
}
}
The result of it:

Boyer Moore dynamic array implementation

Im trying to implement the Boyer Moore(bad character heuristic) algorithm, except i want to use a dynamic array. Can anyone help me with this problem? here's my source code.
**/* Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */
# include <limits.h>
# include <string.h>
# include <stdio.h>
# define NO_OF_CHARS 256
/* Driver program to test above funtion */
int main()
{
char txt[];
char pat[];
ifstream myfile;
string filename;
cout<<"input file"<<endl;
getline(cin, filename);
myfile.open(filename.c_str());
if(myfile.is_open()){
cout<<"file not found"<<endl;
while(getline(myfile, txt))
{
cout<<txt<<endl;
}
cout<<"pls input pattern"<<endl;
cin.getline(pat[]);
search(txt, pat);
myfile.close();
}
else cout<<"file not found"<<endl:
return 0;
}**
std::string is exactly what you would need in this case. It is dynamic in size (as in it is sized appropriately when read into). Just be sure to pass the char* pointer part when necessary using the c_str() member function.
I did that like couple of days ago, if you still need the answer... Just declare a dynamic char array and pass it to the function.
Here char str parameter can take a dynamic char array, and with your badchar[NO_OF_CHARS] array you can implement bad character heuristic before you use search function.
void badCharHeuristic(char *str, int badchar[NO_OF_CHARS])
{
int size = strlen(str);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;
for (i = 0; i < size; i++)
badchar[str[i]] = i;
}
Also your search function should be something like that:
void search(char *txt, char *pat)
{
int s = 0; // s is the variable that hold how many shift we are gonna make
while (s <= (n - m))
{
int j = m - 1;
while (j >= 0 && pat[j] == txt[s + j])
j--;
if (j < 0)
{
printf("pattern occurs at shift = %d ", s);
s += (s + m < n) ? m - badchar[txt[s + m]] : 1; //if s+m < n; s = m - badchar[txt[s + m] else; s = 1
}
else
s += max(1, j - badchar[txt[s + j]]);
}
}

Identify the digits in a given number.

I'm new to programming, and I'm stuck at a problem. I want my program to identify the separate digits in a given number, like if I input 4692, it should identify the digits and print 4 6 9 2. And yeah, without using arrays.
A perfect recursion problem to tackle if you're new to programming...
4692/1000 = 4
4692%1000 = 692
692/100 = 6
692%100 = 92
92/10 = 9
92%10 = 2
You should get the idea for the loop you should use now, so that it works for any number. :)
Haven't written C code in year, but this should work.
int i = 12345;
while( i > 0 ){
int nextVal = i % 10;
printf( "%d", nextVal );
i = i / 10;
}
Simple and nice
void PrintDigits(const long n)
{
int m = -1;
int i = 1;
while(true)
{
m = (n%(10*i))/i;
i*= 10;
cout << m << endl;
if (0 == n/i)
break;
}
}
Another approach is to have two loops.
1) First loop: Reverse the number.
int j = 0;
while( i ) {
j *= 10;
j += i % 10;
i /= 10;
}
2) Second loop: Print the numbers from right to left.
while( j ) {
std::cout << j % 10 << ' ';
j /= 10;
}
This is assuming you want the digits printed from right to left. I noticed there are several solutions here that do not have this assumption. If not, then just the second loop would suffice.
I think the idea is to have non reapeating digits printed (otherwise it would be too simple)... well, you can keep track of the already printed integers without having an array encoding them in another integer.
some pseudo C, to give you a clue:
int encoding = 0;
int d;
while (keep_looking()) {
d = get_digit();
if (encoding/(2**d)%2 == 0) {
print(d);
encoding += 2**d;
}
}
Here is a simple solution if you want to just print the digits from the number.
#include <stdio.h>
/**
printdigits
*/
void printDigits(int num) {
char buff[128] = "";
sprintf(buff, "%d ", num);
int i = 0;
while (buff[i] != '\0') {
printf("%c ", buff[i]);
i++;
}
printf("\n");
}
/*
main function
*/
int main(int argc, char** argv) {
int digits = 4321;
printDigits(digits);
return 0;
}
Is it correct
int main()
{
int number;
cin>>number;
int nod=0;
int same=number;
while(same){
same/=10;
nod++;
}
while(nod--){
cout<<(int)number/(int)pow10(nod)%10<<"\t";
}
return 0;
}