Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Accept a character C and a positive integer N as input. The program must print N characters starting from C.

Boundary Condition(s):
1 <= N <= 100

Input Format:
The first line contains C and N separated by space(s).

Output Format:
The first line contains N characters.

Example Input/Output 1:
Input:
a 4

Output:
abcd

Example Input/Output 2:
Input:
z 5

Output:
zabcd

What I have tried:

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

int main()
{
    char a;
    int n,b=0;
    scanf("%c",&a);
    scanf("%d",&n);
    for( char i=a;b<n;i++){
        printf("%c",i);
        b=b+1;
    }
}
Posted
Updated 22-May-18 22:23pm
v2
Comments
[no name] 23-May-18 2:02am    
I have changed your question tag to C instead of Java, based on the code you posted.
KaranKumar P 23-May-18 2:14am    
yes sorry

Since there are 26 letters in the alphabet, you can use % 26 to start from the beginning again after z.
The character 'a' is not 0 however, so you need to subtract it first and then later re-add it.

For example:
for (int i = 0; i < n; i++) {
    printf("%c", (a - 'a' + i) % 26 + 'a');
}
 
Share this answer
 
C
for (i=0; i<n; ++i)
{
  putchar(a);
  a = (a == 'z') ? 'a' : (a + 1);
}
 
Share this answer
 
Having 2 variables in the loop os basically the idea, but your problem is the you are mixing their usage.
Keep their usage separated, have 1 variable to count printed letters, and the other variable to keep track of the letter to print.
C++
for( int i=0;i<n;i++){ // count here
    printf("%c",a);
    if (a<'z') // set next letter here
        a=a+1;
    else
        a='a';
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900