How i write this c code in pep/8? - pep8-assembly

How write this c code in pep/8 anyone help I am new to this
#include
using namespace std;
int main(){
int number;
cin>>number;
if(number%2 == 0 ){
cout<<"Even\n"; }
else{
cout<<"Odd\n"; }
return 0 ;
}
and thanks in advance :)

No need i solved it by my self here is the code:
BR main
num: .EQUATE 0
main: SUBSP 2,i
DECI num,s
if: LDA num,s
ANDA 0x0001,i
BRNE else
STRO even_msg,d
BR endIf
else: STRO odd_msg,d
endIf: ADDSP 2,i
STOP
odd_msg: .ASCII "The number is: Odd\x00"
even_msg: .ASCII "The number is: Even\x00"
.END

Related

Why I cant print initials of a name?

I am trying to write a code that prints initials of a given name? I have been getting error whenever I use '/0' - to initialize the ith character of a given string. I am using it to identify initials of the 2nd word? Any suggestions to detect the 2nd word and print the initial of the 2nd word? Additionally, I am trying to write this code so that it ignores any additional spaces:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
printf ("Enter you Name:");//print name
string s = get_string(); //get input from user
printf("%c", toupper(s[0])); // use placeholder to call the string
for (int i=0, n = strlen(s); i < n; i++)
{
if (s[i] == '/0')
{
printf("%c", toupper(s[i+1]));
}
}
printf ("\n");
}
I'm not sure what your get_string() function does but this does what you're asking for.
int main(void)
{
printf ("Enter you Name:");//print name
char input[100];
cin.getline(input, sizeof(input));
string s(input);
//get input from user
printf("%c", toupper(s[0])); // use placeholder to call the string
for (int i=0, n = s.length(); i < n; i++)
{
if (isspace(s.at(i)))
{
printf("%c", toupper(s[i+1]));
}
}
printf ("\n");
}
Try to use ' ' instead of '/0'.
if (s[i] == ' ')
or if you prefer ASCII codes (Space is 0x20 or 32 as decimal):
if (s[i] == 0x20)
your code will work if there is only 1 space between names. To avoid this, the condition should also check the next char. If it's not a space then probably it's a 'letter':
if (s[i] == 0x20 && s[i+1] != 0x20) {...
Note that the for cycle should stop at i < n - 1, otherwise the loop will fail if there are trailing spaces...

How to return a int converted to char array back to main for displaying it

My doubts are as follows :
1 : how to send 'str' from function 'fun' , So that i can display it in main function.
2 : And is the return type correct in the code ?
2 : the current code is displaying some different output.
char * fun(int *arr)
{
char *str[5];
int i;
for(i=0;i<5;i++)
{
char c[sizeof(int)] ;
sprintf(c,"%d",arr[i]);
str[i] = malloc(sizeof(c));
strcpy(str[i],c);
}
return str;
}
int main()
{
int arr[] = {2,1,3,4,5},i;
char *str = fun(arr);
for(i=0;i<5;i++)
{
printf("%c",str[i]);
}
return 0;
}
how to send 'str' from function 'fun' , So that i can display it in main function.
This is the way:
char* str = malloc( size );
if( str == NULL ) {
fprintf( stderr,"Failed to malloc\n");
}
/* Do stuff with str, use str[index],
* remember to free it in main*/
free(str);
And is the return type correct in the code ?
No, Probably char** is the one you need to return.
the current code is displaying some different output.
Consider explaining what/why do you want to do ? The way you have written, seems completely messed up way to me. You're passing array of integer but not its length. How is the fun() supposed to know length of array? Another problem is array of pointers in fun().
You can't write a int to a char (See the both size). So I used char array instead.
However, I'm not sure if this is what you want to do (might be a quick and dirty way of doing it):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char**
fun(int *arr, int size)
{
char **str = malloc( sizeof(char*)*size );
if( str == NULL ) {
fprintf( stderr, "Failed malloc\n");
}
int i;
for(i=0;i<5;i++) {
str[i] = malloc(sizeof(int));
if( str == NULL ) {
fprintf( stderr, "Failed malloc\n");
}
sprintf(str[i],"%d",arr[i]);
}
return str;
}
int
main()
{
int arr[] = {2,1,3,4,5},i;
char **str = fun(arr, 5);
for(i=0;i<5;i++) {
printf("%s\n",str[i]);
free(str[i]);
}
free(str);
return 0;
}
I made these changes to your code to get it working:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **fun(int *arr)
{
char **str = malloc(sizeof(char *) * 5);
int i;
for(i = 0; i < 5; i++) {
if ((arr[i] >= 0) && (arr[i] <= 9)) {
char c[2] ;
sprintf(c, "%d", arr[i]);
str[i] = (char *) malloc(strlen(c) + 1);
strcpy(str[i],c);
}
}
return str;
}
int main()
{
int arr[] = {2, 1, 3, 4, 5}, i;
char **str = fun(arr);
for(i = 0; i < 5; i++) {
printf("%s", str[i]);
free(str[i]);
}
printf("\n");
free(str);
return 0;
}
Output
21345
I added a check to make sure that arr[i] is a single digit number. Also, returning a pointer to a stack variable will result in undefined behavior, so I changed the code to allocate an array of strings. I don't check the return value of the malloc calls, which means this program could crash due to a NULL pointer reference.
This solution differs from the others in that it attempts to answer your question based on the intended use.
how to send 'str' from function 'fun' , So that i can display it in main function.
First, you need to define a function that returns a pointer to array.
char (*fun(int arr[]))[]
Allocating variable length strings doesn't buy you anything. The longest string you'll need for 64bit unsigned int is 20 digits. All you need is to allocate an array of 5 elements of 2 characters long each. You may adjust the length to suit your need. This sample assumes 1 digit and 1 null character. Note the allocation is done only once. You may choose to use the length of 21 (20 digits and 1 null).
For readability on which values here are related to the number of digits including the terminator, I'll define a macro that you can modify to suit your needs.
#define NUM_OF_DIGITS 3
You can then use this macro in the whole code.
char (*str)[NUM_OF_DIGITS] = malloc(5 * NUM_OF_DIGITS);
Finally the receiving variable in main() can be declared and assigned the returned array.
char (*str)[NUM_OF_DIGITS] = fun(arr);
Your complete code should look like this:
Code
char (*fun(int arr[]))[]
{
char (*str)[NUM_OF_DIGITS] = malloc(5 * NUM_OF_DIGITS);
int i;
for(i=0;i<5;i++)
{
snprintf(str[i],NUM_OF_DIGITS,"%d",arr[i]); //control and limit to single digit + null
}
return str;
}
int main()
{
int arr[] = {24,1,33,4,5},i;
char (*str)[NUM_OF_DIGITS] = fun(arr);
for(i=0;i<5;i++)
{
printf("%s",str[i]);
}
free(str);
return 0;
}
Output
2413345
With this method you only need to free the allocated memory once.

CS50 - pset2 - Vigenere

I am currently struggling with pset2, specifically with vigenere.
Here is my code :
# include <cs50.h>
# include <ctype.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, string argv[])
{
//Assess the fact that there is only 1 command line argument
if(argc != 2)
{
printf("You should only have 1 command line argument !\n") ;
return 1 ;
}
string k = argv[1] ;
int klength = strlen(k) ;
for(int i = 0; i < klength; i++)
{
if(!isalpha(k[i]))
{
printf("Please make sure the argument is only composed of alphabetical characters\n") ;
return 1 ;
}
}
//Get the text to be crypted
string s = GetString() ;
int slength = strlen(s) ;
//Deliver the crypted text
for( int i = 0, j = 0 ; i < slength ; i++)
{
int kindex = j % klength ;
if(isalpha(s[i]))
{
if(isupper(s[i]))
{
if(isupper(k[kindex]))
{
int crypt = (((s[i] - 'A') + (k[kindex] - 'A') % 26)) + 'A' ;
printf("%c", crypt ) ;
}
else
{
int crypt = (((s[i] - 'A') + (k[kindex] - 'a')) % 26) + 'A' ;
printf("%c", crypt ) ;
}
}
if(islower(s[i]))
{
if(isupper(k[kindex]))
{
int crypt = (((s[i] - 'a') + (k[kindex] - 'A')) % 26) + 'a' ;
printf("%c", crypt) ;
}
else
{
int crypt = (((s[i] - 'a') + (k[kindex] - 'a')) % 26) + 'a' ;
printf("%c", crypt ) ;
}
}
j++ ;
}
else
{
printf("%c" , s[i]) ;
}
}
printf("\n") ;
return 0 ;
}
With check50, here are the errors I receive :
:( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword
\ expected output, but not "CakGon\n"
:( encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword
\ expected output, but not "CAkGOh\n"
Here is my sandbox : sandbox
I don't understand why the two outputs are not the same (cakgon vs cakoh) and why it differs from what is expected. The problem probably resides in the part "//Deliver the crypted test".
I have spent a few hours trying to figure it out without success.
Thanks in advance for any help / tip / piece of advice.
Baptiste
I finally get it.
Parentheses were missing before one of the "%26".

Setting number of columns in output window with c++

I have created a Fibonacci program that runs correctly. However I can not figure out how to format the output window the way the problem would like. The rows and spacing are correct but the program should display 6 columns, as it is now the program outputs nine with the ninth cut off. Am I doing something wrong or missing something? I am using the Visual Studio C++ compiler.
#include <iostream>
#include <iomanip>
using namespace std;
void main ()
{
int FirstNum = 1;
int SecondNum = 0;
int Count = 1;
int Answer;
do
{
Answer = FirstNum + SecondNum;
FirstNum = SecondNum;
SecondNum = Answer;
cout << FirstNum << setw (10);
Count++;
} while (Count < 40);
}
This code will generated only 6 columns.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int FirstNum = 1;
int SecondNum = 0;
int Count = 1;
int Answer;
do
{
Answer = FirstNum + SecondNum;
FirstNum = SecondNum;
SecondNum = Answer;
cout << setw (10)<< FirstNum ;
Count++;
if(Count%6==0)
cout<<endl;
} while (Count < 40);
return 0;
}

Weird define in C++ preprocessor

I've come across this
#define DsHook(a,b,c) if (!c##_) { INT_PTR* p=b+*(INT_PTR**)a; VirtualProtect(&c##_,4,PAGE_EXECUTE_READWRITE,&no); *(INT_PTR*)&c##_=*p; VirtualProtect(p,4,PAGE_EXECUTE_READWRITE,&no); *p=(INT_PTR)c; }
and everything is clear except the "c##_" word, what does that mean?
It means to "glue" together, so c and _ get "glued together" to form c_. This glueing happens after argument replacement in the macro. See my example:
#define glue(a,b) a##_##b
const char *hello_world = "Hello, World!";
int main(int arg, char *argv[]) {
printf("%s\n", glue(hello,world)); // prints Hello, World!
return 0;
}
It is called a token-pasting operator. Example:
// preprocessor_token_pasting.cpp
#include <stdio.h>
#define paster( n ) printf( "token" #n " = %d", token##n )
int token9 = 9;
int main()
{
paster(9);
}
Output
token9 = 9
That's concatenation that appends an underscore to the name passed as c. So when you use
DsHook(a,b,Something)
that part turns into
if (!Something_)
After the preprocessor, your macro will be expanded as:
if (!c_) { INT_PTR* p=b+*(INT_PTR**)a; VirtualProtect(&c_,4,PAGE_EXECUTE_READWRITE,&no); *(INT_PTR*)&c_=*p; VirtualProtect(p,4,PAGE_EXECUTE_READWRITE,&no); *p=(INT_PTR)c; }
The ## directive concatenates the value of c which you pass as a macro parameter to _
Simple one:
#define Check(a) if(c##x == 0) { }
At call site:
int varx; // Note the x
Check(var);
Would expand as:
if(varx == 0) { }
It is called Token Concatenation and it is used to concatenate tokens during the preprocessing
For example the following code will print out the values of the values of c, c_, c_spam:
#include<stdio.h>
#define DsHook(a,b,c) if (!c##_) \
{printf("c=%d c_ = %d and c_spam = %d\n",\
c, c##_,c##_spam);}
int main(){
int a,b,c=3;
int c_ = 0, c_spam = 4;
DsHook(a,b,c);
return 0;
}
Output:
c=3 c_ = 0 and c_spam = 4

Resources