What I want the program to do is to evaluate the 2 consecutive integers after another in a set of array, then convert these integers to a corresponding character.
For example, if I have array[10] = {4 2 3 2 5 3 5 3 6 3}, the first 2 ints 4 2 will be converted into "H", 3 2 = E, 5 3 = L and so on until it prints the word HELLO. The program should accept a list of integers.
This is what I've done so far..
#include <stdio.h>
#include <stdlib.h>
int main() {
int i=0, j=0, k=0;
int array[1000];
char space;
printf("Input integers to convert into a string: ");
do {
scanf("%d%c", &array[i], &space);
i++;
} while(space != '\n');
for(/*what should I include here?*/)
if (array[0] == 2 && array[1] == 1)
printf("A");
else if (array[0] == 2 && array[1] == 2)
printf("B");
/* and so may else ifs*/
}
Something like this should work. Instead of going through the for loop one int at a time, it would probably be best to do two at a time.
for(int i = 0; i < 1000; i += 2){
if (array[i] == 2 && array[i + 1] == 1)
printf("A");
else if (array[i] == 2 && array[i + 1] == 2)
printf("B");
/* and so may else ifs*/
}
I would create a function that converts the integers to the characters.
char int_to_char(int val)
{
if(val == 21)
return 'A';
if(val == 22)
return 'B';
if(val == 42)
return 'H';
if(val == 32)
return 'E';
if(val == 53)
return 'L';
if(val == 63)
return 'O';
// I don't see you pattern, so I don't know which value
// is which character
return '?';
}
I don't see your pattern here.
Then your loop would look like:
// i is the number of entered values
// making sure that the end condition is even
for(int j = 0; j < i&1 ? i - 1 : i; j += 2)
{
printf("%c", int_to_char(array[j] * 10 + array[j+1]));
}
This would print HELLO with the input 4 2 3 2 5 3 5 3 6 3.
Related
The problem I was given to solve is "The number of students who will take the exam is entered from the keyboard, and then the IDs of all the students who will take the exam are entered. The program should divide the students into three groups: students with IDs ending in the digits 0, 1, and 2, students with IDs ending in the digits 3, 4, 5, and students with IDs ending in the digits 6, 7, 8, 9 .The program should print the IDs for each group, in the same order as they were entered. The maximum number of students that can be entered is 1000.".
The code that I can come up with is
#include <stdio.h>
int main() {
int n,br,gr1,gr2,gr3;
scanf("%d",&n);
for (int i = 0; i < n; ++i) {
scanf("%d", &br);
if (br % 10 == 0 || br % 10 == 1 || br % 10 == 2)
{
gr1 = br;
}
else if (br % 10 == 3 || br % 10 == 4 || br % 10 == 5)
{
gr2 = br;
}
else if (br % 10 == 6 || br % 10 == 7 || br % 10 == 8 || br % 10 == 9)
{
gr3 = br;
}
}
printf("Grupa 1\n%d\n",gr1);
printf("Grupa 2\n%d\n",gr2);
printf("Grupa 1\n%d\n",gr3);
return 0;
}
Instead of printing all the IDs and sorting them into groups it is only printing the last input number and group number.
I am in no way an experienced programmer so I can't really tell what is wrong with the way I have written this or how to solve it. I would appreciate it if you can guide me through
The output I am expecting is:
Grupa 1
20010 20581 19452
Grupa 2
20145 19873 19825 20653
Grupa 3
20147 20139 19458
The output I am getting is
Grupa 1
19452
Grupa 2
20653
Grupa 3
19458
Your gr1,gr2,gr3 int variables can only store one values at a time (here, the last value that was assigned to it so its showing only one result.) Make them something like an array eg gr1[],gr2[],gr3[], which will be able to hold multiple values at a time and will be able to print them out at the end.
The way you format you code makes it harder for yourself to figure out what is going on. You need to stash in a data in an ordered data structure (array, linked list etc):
#include <stdio.h>
#include <stdlib.h>
#define MAX_STUDENTS 1000
typedef size_t student_id;
enum group {
GROUP_1 = 1,
GROUP_2,
GROUP_3
};
enum group group_student(student_id id) {
switch(id % 10) {
case 0: case 1: case 2:
return GROUP_1;
case 3: case 4: case 5:
return GROUP_2;
default:
return GROUP_3;
}
}
int main(void) {
student_id ids[MAX_STUDENTS];
size_t n = 0; // required below
for(; n < sizeof ids / sizeof *ids; n++) {
if(scanf("%zu", ids + n) != 1) {
break;
}
}
for(enum group group = GROUP_1; group <= GROUP_3; group++) {
printf("Grupa %d\n", group);
for(size_t j = 0; j < n; j++) {
if(group == group_student(ids[j]))
printf("%zu ", ids[j]);
}
printf("\n");
}
}
and here is an example run:
$ echo '20010 20581 19452 20145 19873 19825 20653 20147 20139 19458' | ./a.out
Grupa 1
20010 20581 19452
Grupa 2
20145 19873 19825 20653
Grupa 3
20147 20139 19458
When you type this in, end input with ctrl-D. I used a enum group here as it's an identifier (not a number) and documents by virtue of the return type that you change the enum you want to change the function group_student(), too.
How can I print numbers from 1 to the limit the user puts in? But above 9 the 10 just print a green 1 and 1,2,3,4,.. and then for 20 a green 2 and so on ...
like this:
-123456789112345689212345....-
and so on.
My current code:
int o;
do {
for(o = 0; o < width+2;o++) {
if(o != 0 || o != width+1)
if(o % 10 != 0)
printf("%d", o);
else
printf("\033[032m%d\033[0m", o);
}
} while(o<width);
printf("-");
Current output
It should start to print with zero and end with 19 (because the player here input was 19).
Perhaps as simple as
// Iterate to `width`
for (int i = 0; i <= width; i++) {
if (i % 10 || i == 0) {
printf("%d", i % 10); // Print only the one's digit.
} else {
printf("\033[032m%d\033[0m", (i/10)%10); // Print only the ten's digit.
}
}
I am trying to write a C program that takes a string input from a user and then looks into the input to count the frequency of all the integers in the string. So suppose if the user gives the input:
a11472o5t6
the output would be :
0 2 1 0 1 1 1 1 0 0
my approach involves comparing every character of the string to all 10 digits one by one and if any the character is equal to the digit, it would increment the isdigit number by 1.
the code I wrote for the same is as follows:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int is1 = 0; //initialise integers for checking
int is2 = 0;
int is3 = 0;
int is4 = 0;
int is5 = 0;
int is6 = 0;
int is7 = 0;
int is8 = 0;
int is9 = 0;
int is0 = 0;
int main()
{
char s[100]; //initialise array for string
scanf("%s", s); //scan string input
//now all characters of the string are stored in the array s
for (int i = 0; i < strlen(s); i++) //loop to iterate over all the elements in the array
{
if (strcmp(&s[i], "0") == 0)
{
is0 = is0 + 1;
}
if (strcmp(&s[i], "1") == 0)
{
is1 = is1 + 1;
}
if (strcmp(&s[i], "2") == 0)
{
is2 = is2 + 1;
}
if (strcmp(&s[i], "3") == 0)
{
is3 = is3 + 1;
}
if (strcmp(&s[i], "4") == 0)
{
is4 = is4 + 1;
//printf("%d", is4);
}
if (strcmp(&s[i], "5") == 0)
{
is5 = is5 + 1;
}
if (strcmp(&s[i], "6") == 0)
{
is6 = is6 + 1;
}
if (strcmp(&s[i], "7") == 0)
{
is7 = is7 + 1;
}
if (strcmp(&s[i], "8") == 0)
{
is8 = is8 + 1;
}
if (strcmp(&s[i], "9") == 0)
{
is9 = is9 + 1;
}
}
printf("%d ", is0);
printf("%d ", is1);
printf("%d ", is2);
printf("%d ", is3);
printf("%d ", is4);
printf("%d ", is5);
printf("%d ", is6);
printf("%d ", is7);
printf("%d ", is8);
printf("%d ", is9);
}
I expected the code to iterate over and over for the entire length of the string and and update values of the isdigit series every time a number was successfully found. However whenever I run the code only the last digit seems to find its place in the output .
for example if I type 54 as an input the expected output is
0 0 0 0 1 1 0 0 0 0
however the output my code seems to be giving is
0 0 0 0 1 0 0 0 0 0
likewise the number 45 also has the same expected output
0 0 0 0 1 1 0 0 0 0
but the output I am receiving is
0 0 0 0 0 1 0 0 0 0
which looks like the code overwrites any operation that occurred in the previous iteration, but I can't seem to understand why and how to fix it.
On my part I checked if the characters were being called properly one by one and that all characters were being compared, where I found no problem. I also looked up other answers on stack overflow and elsewhere, but was I am a beginner and most answers were written in reference to languages that I can't understand, so I was unable to relate to the solution they were being told. the closest I got was someone who was using a single variable repetitively thus overwriting it in each iteration. however I have declared sufficient variables( one for each digit from 0-9), so that shouldn't be the problem in my code either.
while I know this question could be solved easily using arrays, I would like to know what I was doing wrong here to avoid any such mistakes in the future.
When you do if (strcmp(&s[i],"1")==0) you are comparing strings, not individual characters, which is why only the last character is counted. It's the only one matching.
Example:
If s == "a11472o5t6" and you use strcmp(&s[1], "1"), you would be comparing the string "11472o5t6" with the string "1", which clearly will not be equal.
You want if(s[i] == '1') etc. to do the comparisons of individual characters instead.
And you are correct about using arrays instead. It'd certainly be easier.
Example:
#include <ctype.h>
#include <stdio.h>
int main() {
const char *str = "a11472o5t6";
int ints[10] = {0};
for (const char *chptr = str; *chptr != '\0'; ++chptr) {
if(isdigit((unsigned char) *chptr)) ++ints[*chptr - '0'];
}
for (int i = 0; i < 10; ++i) printf("%d %d\n", i, ints[i]);
}
Output:
0 0
1 2
2 1
3 0
4 1
5 1
6 1
7 1
8 0
9 0
This is kind of strange, imo, I have a for loop that does a comparison
using the return value from a function.
for (size_t i = 0; i < func(val); i++) {
printf("Value from array modified in func = %u", values[i]);
}
The issue is the loop seems to run before the function is finished, if have a printf in the called function some output occurs before the output of the loop, expected, and some after, not expected. The function is only called in the for loop comparison so output should all happen before for loop's output. If I use a var instead such as:
size_t temp = func(val);
for (size_t i = 0; i < temp; i++) {
printf("Value from array modified in func = %u", values[i]);
}
Then everything works correctly, this is rather odd to me, I'm not using threads so this should all be synchronus right? So why would the loop not wait for func(val) to return?
Here's the original code (cutting out a bunch of comments):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
#define SUITS 4
#define FACES 13
#define CARDS 52
#define HAND 5
typedef struct {
unsigned int suit;
unsigned int face;
} card;
size_t checkX(card hand[HAND], unsigned int faces[HAND], unsigned int num);
int main() {
card hand[HAND] = {{1,1},{1,7},{1,1},{1,4},{1,7}};
const char *suit[SUITS] = {"Hearts", "Diamonds", "Clubs", "Spades"};
const char *face[FACES] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
unsigned int matchingFaces[HAND] = {0};
for (size_t i = 0; i < checkX(hand, matchingFaces, 2); ++i) {
printf("Pair of %s%s\n", face[matchingFaces[i]], matchingFaces[i] == 5 ? "es" : "s");
}
}
size_t checkX(card hand[HAND], unsigned int faces[HAND], unsigned int num) {
size_t facePos = 0;
for (size_t i = 0; i < HAND - 1; i++) {
size_t count = 1;
for (size_t j = i + 1; j < HAND; j++) {
printf("%u == %u && %u != %u\n", hand[i].face, hand[j].face, hand[i].face, faces[facePos]);
if (hand[i].face == hand[j].face && hand[i].face != faces[facePos]) count++;
}
faces[facePos] = hand[i].face;
if (count == num) facePos++;
}
return facePos;
}
Some of this isn't my code, I was given a basic card shuffling type of program and told to modify it to deal a hand and check for pairs/three of a kind. Like I said this does work when I set the return value of checkX as a variable and then compare i to that instead of directly, I just don't know why. I've tried disabling gcc optimization, which didn't seem to make a difference.
Output from direct func comparison:
1 == 7 && 1 != 0
1 == 1 && 1 != 0
1 == 4 && 1 != 0
1 == 7 && 1 != 0
7 == 1 && 7 != 0
7 == 4 && 7 != 0
7 == 7 && 7 != 0
1 == 4 && 1 != 0
1 == 7 && 1 != 0
4 == 7 && 4 != 1
Pair of Deuces
1 == 7 && 1 != 1
1 == 1 && 1 != 1
1 == 4 && 1 != 1
1 == 7 && 1 != 1
7 == 1 && 7 != 1
7 == 4 && 7 != 1
7 == 7 && 7 != 1
1 == 4 && 1 != 7
1 == 7 && 1 != 7
4 == 7 && 4 != 1
Output from indirect comparison of func using variable:
1 == 7 && 1 != 0
1 == 1 && 1 != 0
1 == 4 && 1 != 0
1 == 7 && 1 != 0
7 == 1 && 7 != 0
7 == 4 && 7 != 0
7 == 7 && 7 != 0
1 == 4 && 1 != 0
1 == 7 && 1 != 0
4 == 7 && 4 != 1
Pair of Deuces
Pair of Eights
I know this code isn't the nicest but I had to work with what was given and just need to make it work, so this question is just out of curiosity.
for (size_t i = 0; i < func(val); i++) {
printf("Value from array modified in func = %u", values[i]);
}
func(val) gets called multiple times here, each time a decision needs to be made whether to continue the loop or not, you can picture it as
size_t i = 0;
if (i < func(val)) {
printf(.....);
i++;
if (i < func(val)) {
printf(.....);
i++;
if (i < func(val)) {
printf(.....);
i++;
if (i < func(val)) {
printf(.....);
i++;
....and so on......
}
}
}
}
So you can see, func(val) may get called multiple times.
A rather good, but a little out of date, section of the great book "The C Programming Language", by Kernighan and Ritchie, re-state a for loop to the equivalent:
{
size_t i = 0;
while (i < func(val)){
printf("Value from array modified in func = %u", values[i]);
i++;
}
}
(The outer braces are mine and are necessary since you can now declare a variable inside the first "expression" in the for loop.)
If you write the loop this way, it's plain to see that func(val) is re-evaluated on each iteration. That is what is causing the effects you observe. (Note that not all languages do this, VBA and VB6 are two examples where the end condition of the for loop is not re-evaluated.)
Because of this, if func(val) is an expensive function and your algorithm doesn't require repeated evaluation, you might want to consider pre-computing the value in advance. Some compilers may optimise out the re-evaluation especially if you are using a standard function like strlen for example, but such an optimisation is a very tricky science.
#include <stdio.h>
void main(){
int i, j, n;
int num[5];
int serial;
for(i=0; i<5; ++i){
scanf("%d",&num[i]);
if(num[i]==num[i-1])
serial=i;
else
continue;
}
printf("Serial number of equal numbers next to each other:%d. %d.", serial-1, serial);
}
This may be hard to understand because I'm not a native English speaker.
If the numbers next to each other are equal the program should print the serial number of those numbers.
For example:
Input: 1 2 3 7 7 7 6;
Output: 3. 4. 5.
Input: 5 5 5 5 5
Output: 0. 1. 2. 3. 4.
I made some changes now it prints the serial of two equal numbers.
I: 1 2 2 3 4 - O: 1. 2.
But what if all the numbers are equal?
// ...
// deal with index 0
if (num[0] == num[1]) printf("0. ");
// deal with indexes 1 .. N - 2
for (int k = 1; k < n - 1; k++) {
if ((num[k - 1] == num[k]) || (num[k] == num[k + 1])) {
printf("%d. ", k);
}
}
// deal with index N - 1
if (num[n - 2] == num[n - 1]) printf("%d. ", n - 1);
// ... possibly with a printf("\n"); somewhere
You can solve this without storing the numers in an array, but you must keep track of how many equal numbers have been read before reading the present one:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i = 0; // running index
int prev = 0; // previously read number
int iprev = 0; // start of range of equal numbers previously read
int n; // currently read number
while (scanf("%d", &n) == 1) {
if (n != prev) {
if (i - iprev > 1) {
while (iprev < i) printf("%d\n", iprev++);
}
iprev = i;
prev = n;
}
i++;
}
if (i - iprev > 1) {
while (iprev < i) printf("%d\n", iprev++);
}
return 0;
}
You consider stretches of equal numbers only after you read a number that terminates the current range of equal numbers. When all numbers are different, the size of that range is 1 and we don't print anything. If the range is larger than 1, print all indices in question.
Because you don't notice a change after reading the last number, you must check the last range separately after the main loop.
If you can put a non-numeric character in the [0] element of your array, you won't need a different test for the first element
int main (void)
{
/* non-numeric in position 0 of data array */
char myList[] = {'.','1','2','2','3','4','4','4','5','6','6'};
int listSz = strlen(myList) -1;
int n;
/* check everything except last */
for (n = 1; n < listSz; n++) {
if(( myList[n] == myList[n +1]) || ( myList[n] == myList[n -1] )) {
printf("%d . ", n);
}
}
/* check last */
if( myList[listSz] == myList[listSz -1] ) {
printf("%d", n);
}
printf("\n");
}
Output: 2 . 3 . 5 . 6 . 7 . 9 . 10