User inputs a number, and program should surround it with charatchers - c

This is my code, it works but i feel i could do something different
#include <stdio.h>
int main()
{
int n;
printf("Input a number [0,9]: ");
scanf("%d", &n);
printf("*****\n");
printf("*****\n");
printf("**%d", n);
printf("**");
printf("\n*****\n");
printf("*****\n");
return 0;
}
Is this the best solution or is there something easier?

I tend to do 1 printf() per output line
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n;
printf("Input a number [0,9]: ");
if (scanf("%d", &n) != 1) exit(EXIT_FAILURE);
if ((n < 0) || (n > 9)) printf("nope\n");
else {
printf("*****\n");
printf("*****\n");
printf("**%d**\n", n);
printf("*****\n");
printf("*****\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n;
printf("Input a number [0,9]: ");
if (scanf("%d", &n) != 1) exit(EXIT_FAILURE);
if ((n < 0) || (n > 9)) printf("nope\n");
else {
for (int i = 0; i < 5; i++) {
if (i == 2) {
printf("**%d**\n", n);
} else {
printf("*****\n");
}
}
}
return 0;
}

you can do it a bit more universal way. It will print NCHARS around the number and NLINES lines of FILLER around the number. Any number is covered (including negave ones)
#include <stdio.h>
#define NCHARS 3
#define NLINES 3
#define FILLER '*'
size_t countdigits(int n)
{
size_t ndigits = n <= 0 ? 1 : 0;
while(n)
{
ndigits++;
n /= 10;
}
return ndigits;
}
void printlines(size_t nchars, char ch)
{
for(size_t before = 0; before < NLINES; before++)
{
for(size_t pos = 0; pos < nchars; pos++ )
printf("%c", ch);
printf("\n");
}
}
void printfsurrounded(int n)
{
size_t nchars = countdigits(n);
printlines(nchars + NCHARS * 2, FILLER);
for(int pos = 0; pos < NCHARS; pos++) printf("%c", FILLER);
printf("%d", n);
for(int pos = 0; pos < NCHARS; pos++) printf("%c", FILLER);
printf("\n");
printlines(nchars + NCHARS * 2, FILLER);
}
int main(void)
{
printfsurrounded(4);
printf("\n");
printfsurrounded(1024);
printf("\n");
printfsurrounded(-233445);
}
https://godbolt.org/z/hz1eq9

Related

Iterating through code to add a new line on the nth term

How would I go about adding a new line on the 10th term on this zybooks question
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
printf("%d\t", n);
while (n > 1) {
if (n % 2 == 1) {
n = 3 * n + 1;
}
else {
n = n / 2;
}
printf("%d\t",n);
}
printf("\n");
return 0;
}
This solution uses a counter variable i which increments until 10 is reached. Once it is reached a newline character (\n) is printed.
#include <stdio.h>
int main(void)
{
int n, i = 0;
scanf("%d", &n);
printf("%d\t", n);
while (n > 1) {
i++;
(n % 2 == 1) ? (n = 3*n+1) : (n = n/2);
if (i == 10) {
i = 0;
printf("\n");
}
else {
printf("%d\t", n);
}
}
printf("\n");
return 0;
}

Can someone explain how i would open a file (containg a list of numbers) and then pass them though my selection sort algorithm?

So ive genertaed a list of random numbers (of varying size) that need to be sorted using selection sort, i have the selection sort algoruthm but im not sure how to open my file, read it and then pass it through my algorithm.
In my selection sort i have an array of number for temporary ue but they need to be replaced with the numbers from the file.
This is my selection sort code im using...
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, pos, s;
for (i = 0; i < (n - 1); i = i + 1) {
pos = i;
for (j = i + 1; j < n; j = j + 1) {
if (arr[pos] > arr[j])
pos = j;
}
if (pos != i) {
s = arr[i];
arr[i] = arr[pos];
arr[pos] = s;
}
}
for (i = 0; i < n; i = i + 1)
printf("%d\n", arr[i]);
return 0;
}
Here is a solution which reads the numbers from standard input. The first number in the input is the number of integers to read.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NEW_ARRAY(pointer, length) \
{ \
(pointer) = malloc((size_t) (length) * sizeof (pointer)[0]); \
if ((pointer) == NULL) { \
fprintf(stderr, "Allocating memory failed: %s\n", strerror(errno)); \
exit(EXIT_FAILURE); \
} \
}
void Read(int **numbers, int *numbersLength)
{
int count, i;
count = scanf("%d", numbersLength);
if ((count == 1) && (*numbersLength > 0)) {
NEW_ARRAY(*numbers, *numbersLength);
i = -1;
do {
i++;
count = scanf("%d", &(*numbers)[i]);
} while ((count == 1) && (i < *numbersLength - 1));
if (count != 1) {
fprintf(stderr, "Expected %d numbers but got only %d\n", *numbersLength, i);
exit(EXIT_FAILURE);
}
} else {
fprintf(stderr, "Number of integers should be a positive integer\n");
exit(EXIT_FAILURE);
}
}
void Sort(int numbers[], int numbersLength)
{
/*your sorting logic here*/
}
void Print(const int numbers[], int numbersLength)
{
int i;
for (i = 0; i < numbersLength; i++) {
printf(" %d", numbers[i]);
}
}
int main(void)
{
int numbersLength;
int *numbers;
Read(&numbers, &numbersLength);
Sort(numbers, numbersLength);
Print(numbers, numbersLength);
putchar('\n');
free(numbers);
return 0;
}
I think you'll want fgetc and fopen: https://man7.org/linux/man-pages/man3/fopen.3.html, https://man7.org/linux/man-pages/man3/fgetc.3.html. If they have varying lengths you will probably also be looping until you read EOF, the end of file character. Hope this helps and good luck!

Incorrect output using strcmp

I'm doing the day 8 of the 30 days of code in HackerRank and I am having a problem with strcmp.
The code asks the user for names of people and their numbers, then asks for other names, if a name wasn't entered before, then it outputs Not found, but if it was then it outputs the name and his number. But for some reason, the output only works in the last loop of the for statement.
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
scanf("%i", &n);
} while (n < 1 || n > 100000);
int i = 0;
phonebook people[n];
for (i = 0; i < n; i++) {
scanf("%s %i", people[i].name, &people[i].number);
}
char othernames[n][100];
for (i = 0; i < n; i++) {
scanf("%s", othernames[i]);
}
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
} else {
printf("Not found\n");
}
}
return 0;
}
You didn't find the othernames from the beginning to end to compare peopleevery time, so you need to replace
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
}
else {
printf("Not found\n");
}
}
to
bool found = false;
for (i = 0; i < n; i++) {
for ( j = 0 ; j < n ; j++ ) {
if (strcmp(othernames[j], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
found = true;
}
}
}
if ( found == false ) printf("Not found\n");
The problem is othernames should just be an array of char, not a matrix. And for each othername entered, you must scan whole phonebook to find it or display Not found. As coded, you only test if the i-th othername typed happens to correspond to the i-th entry in the phone book.
Here is a modified version:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
if (scanf("%i", &n) != 1)
return 1;
} while (n < 1 || n > 100000);
phonebook people[n];
for (int i = 0; i < n; i++) {
if (scanf("%99s %i", people[i].name, &people[i].number) != 2)
return 1;
}
for (int i = 0; i < n; i++) {
char othername[100];
if (scanf("%99s", othername) != 1)
break;
int j;
for (j = 0; j < n; j++) {
if (strcmp(othername, people[j].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
break;
}
}
if (j == n) {
printf("Not found\n");
}
}
return 0;
}
Note that it is probably not a good idea to store phone numbers as int values. Better use a char array so an initial 0 is significant and to store longer numbers.

concatinating even and odd places in a string

I'm learning basics in coding. Can any one say what went wrong with my code
Prob:Given a string, S, of length N that is indexed from 0 to N-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
char input[100], final[100];
int main()
{
int num, i, j;
char even[50], odd[50], space[] = " ";
scanf("%d", &num);
for (i = 0; i < num; i++)
{
int k = 0, p = 0;
scanf(" %[^\n]s", input);
for (j = 0; input[j] != '\0'; j++)
{
if (j % 2 == 0)
{
even[k] = input[j];
k++;
}
else
{
odd[p] = input[j];
p++;
}
}
strcat(final, even);
strcat(final, space);
strcat(final, odd);
}
printf("%s", final);
}

Replacing elements in an array

I have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}

Resources