Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here's my program that asks a user to enter a line of text and then shows the ASCII code it's associated with, and than after that it modifies the ASCII code by adding plus 1 to i, and it also prints out the new character associated with that new ASCII code.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main()
{
    char s[ 70 ]; // define character array of size 70
    size_t i; // loop counter

    // use gets to get text from user
    puts( "Enter a line of text: a
" );
    fgets( s, 70, stdin );

    // convert each character to ASCII and output
    puts("
 ASCII code for the characters 
");
    for ( i = 0; s[ i ] != ''; ++i )
    {
        printf(" %c:%d",(s[ i ]),(s[ i ]));
    } // end for  Uppercase ASCII

    // convert each character to modified ASCII and output
    puts( "
The line modified with progressively higher ASCII:
" );
    for ( i = 0; s[ i ] != ''; ++i )
    {
        printf( "%c", ( s[ i ] + (i+1)) );
    } // end for modified characters

    puts("");
    printf( " 
 modified  ASCII code for the entered string 

a");
    for ( i = 0; s[ i ] != ''; ++i )
    {
        printf( " %c:%d",(s[ i ] + (i+1)),(s[ i ] +(i+1)));
    } // end for  modified ASCII code
    printf( "
 	 The final value of loop variable 'i' is:%d
", i);
    puts( "" );
    system("PAUSE");
}

I'm having difficulty modifying it so that the ASCII code and characters change by the first seven prime numbers 2,3,5...17 and than after those first 7 prime numbers are up go in reverse 17,13,11,7,...2. So after the first loop say g has ASCII code 103, the modified ASCII code will now be 105 and the new letter will now be i. Can anybody help me out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
202 views
Welcome To Ask or Share your Answers For Others

1 Answer

Start by declaring an array storing your pattern (primes, in ascending order and then descending order, in such a way that reducing modulo the arrays size will cause a cycle). For example:

unsigned int prime[] = { 2, 3, 5, 7, 11, 13, 17, 13, 11, 7, 5, 3 };

Now, rather than adding (i + 1) to each character in your loop, you'll want to add prime[i % (sizeof prime / sizeof *prime)]. For example:

for (i = 0; s[i] != ''; i++)
{
     putchar(s[i] + prime[i % (sizeof prime / sizeof *prime)]);
}

P.S. Technically, it's not required to be ASCII. Think of it this way: C and ASCII go together like coffee and cows milk. Most people love it, but occasionally someone will use coconut milk or cream instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...