My program takes 3 lines of input. The first line being whether you want to sort it by odd or even, the second line being how large your array is and the third line being the integers in the array. It works until you use an array larger than 8. I believe it's to do with malloc but I've tried to debug this code for a couple of hours now and I can't fix this issue.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* sort;
int n;
int* ar;
int i;
int test()
{
int temp;
int j = 1;
//printf("%s", sort);
if (strcmp(sort, "odd") == 0) {
for (i = 0; i < n;) {
if (j != n) {
if (ar[i] % 2 != 0) {
if (ar[j] % 2 != 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
if (strcmp(sort, "even") == 0) {
for (i = 0; i < n; i++) {
if (j != n) {
if (ar[i] % 2 == 0) {
if (ar[j] % 2 == 0) {
if (ar[j] < ar[i]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
j++;
}
else {
j++;
}
}
else {
j++;
}
}
else {
j++;
i++;
}
}
else {
i++;
j = i + 1;
}
}
}
}
void main()
{
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
//printf("%s", sort);
printf("Enter the elements of the array \n");
for (i = 0; i < n; i++) {
scanf("%d", &ar[i]);
}
test();
for (i = 0; i < n; i++) {
printf("%d ", ar[i]);
}
// return 0;
}
Code is typically executed in a linear fashion, but you don't seem to be doing that. You're allocating ar using n, but don't have a value for n yet until several lines later...
ar = malloc(sizeof(int) * n);
sort = malloc(sizeof(char) + 1);
printf("Enter odd or even\n");
scanf("%s", sort);
// printf("please input odd or even\n");
printf("Enter the size of the array \n");
scanf("%d", &n);
You're also not allocating the size of sort big enough to contain any string longer than 1 character.
Related
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;
}
I'm trying to make a C program to insert elements into an array until user inputs a 0 or less number, as the title says. But when I print the array out, it doesn't show the numbers I inputted. I have tried using a while as well as do-while loops but without success.
#include <stdio.h>
int main() {
int data[100];
int i;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
int n = sizeof(data[i]);
for (int i = 0; i < n; i++) {
printf("%d ", &data[i]);
}
}
Try this:
#include <stdio.h>
int main() {
int data[100];
int i;
int counter = 0;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
counter++;
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
for (int j = 0; j < counter - 1; j++) {
printf("%d ", data[j]);
}
}
The problem was that you had printf("%d ", &data[i]); instead of printf("%d ", data[i]);.
And also you've trying to get the sizeof() of an element data[i], not the size of the whole array. That's why there's counter in my code.
int n = sizeof(data[i]);
this is wrong, you want
int n = i;
sizeof(data[i]) gives you the size of an int (4 on my machine)
On the other hand, you need to check the result of scanf, if a bad input is entered do not increment the counter, something like:
int i = 0;
while (i < 100)
{
int res = scanf("%d", &data[i]);
if (res == EOF)
{
break;
}
if (res == 1)
{
if (data[i] <= 0)
{
break;
}
i++;
}
else
{
// Sanitize stdin
int c;
while ((c = getchar()) != '\n');
}
}
Finally, scanf wants a pointer to the object, but this is not the case of printf:
printf("%d ", &data[i])
should be
printf("%d ", data[i])
Task: Converts Ohm's from 1 kOhm to 1000 Ohm etc. and find max and min values.
Example:
1 kOhm
2 Ohm
And after convert to
1000 Ohm
2 Ohm
But after input get only
1 kOhm
Ohm
Input must be with spaces. Program drops 1 char from every new line after first. I try using wscanf and other thinks but it isn't workig for me.
P.S. I must use wchar_t
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int pow(int base, int exp) {
if (exp < 0)
return -1;
int result = 1;
while (exp) {
if (exp & 1)
result *= base;
exp >>= 1;
base *= base;
}
return result;
}
int transformSize(wchar_t name) {
if (name == L'h') {
return 2;
} else if (name == L'k') {
return 3;
} else if (name == L'M') {
return 6;
} else if (name == L'G') {
return 9;
} else if (name == L'T') {
return 12;
} else if (name == L'P') {
return 15;
} else if (name == L'E') {
return 18;
} else if (name == L'Z') {
return 21;
} else if (name == L'Y') {
return 24;
}
return 0;
}
int main() {
unsigned int *numbers;
unsigned int min = 0;
unsigned int max = 0;
int n = 0;
wchar_t **array;
setlocale(LC_ALL, "");
wprintf(L"Enter n: ");
wscanf(L"%d", &n);
array = malloc(n * sizeof(wchar_t *));
numbers = malloc(n * sizeof(unsigned int *));
wprintf(L"Enter n-elements: \n");
for (int i = 0; i < n; i++) {
wchar_t temp;
array[i] = malloc(256 * sizeof(wchar_t));
wscanf(L"%c", &temp);
fgetws(array[i], 2560, stdin);
}
wprintf(L"\n\nStart array: [");
for (int i = 0; i < n; i++) {
wprintf(L" ");
wprintf(L"%ls", array[i]);
wprintf(L" ");
}
wprintf(L"]\n\n");
for (int i = 0; i < n; i++) {
int spaceIndex = 0;
for (int j = 0; j < wcslen(array[i]); j++) {
if (array[i][j] != ' ') {
spaceIndex++;
} else {
break;
}
}
wchar_t *new = malloc(sizeof(wchar_t) * spaceIndex + 1);
wcsncpy(new, array[i], spaceIndex);
new[n] = '\0';
numbers[i] = wcstol(new, (wchar_t **)NULL, 10) *
(pow(10.0, (double)transformSize(array[i][spaceIndex + 1])));
if (i == 0) {
min = numbers[i];
max = numbers[i];
}
if (numbers[i] >= max) {
max = numbers[i];
}
if (numbers[i] <= min) {
min = numbers[i];
}
free(new);
}
wprintf(L"Converted array: [");
for (int i = 0; i < n; i++) {
wprintf(L" %ld Ohm ", numbers[i]);
}
wprintf(L"]\n\n");
wprintf(L"Max element: %ld Ohm\n", max);
wprintf(L"Min element: %ld Ohm\n", min);
for (int i = 0; i < n; i++) {
free(array[i]);
}
free(array);
return 0;
}
Example of current program input/output:
Enter n: 3
Enter n-elements:
12 kOhm
3 kOhm
1 Ohm
// Must be 12 kOhm, 3 kOhm, 1 Om
Start array: [ 12 kOhm
kOhm
Ohm
]
// Must be 12000 Ohm, 3000 Ohm, 1 Ohm
Converted array: [ 12000 Ohm 0 Ohm 0 Ohm ]
Max element: 12000 Ohm
Min element: 0 Ohm
Mixing fgetsw and wscanf is a bad idea.
The problem is here:
...
for (int i = 0; i < n; i++) {
wchar_t temp;
array[i] = malloc(256 * sizeof(wchar_t));
wscanf(L"%c", &temp);
fgetws(array[i], 2560, stdin);
}
...
You are using wscanf(L"%c", &temp); to absorb the line feed that is left over from wscanf. You should do this only once after the wscanflike this:
...
wchar_t temp;
wscanf(L"%c", &temp);
for (int i = 0; i < n; i++) {
array[i] = malloc(256 * sizeof(wchar_t));
fgetws(array[i], 2560, stdin);
}
...
But the best would be not to mix wscanf and fgetsw in first place.
I suppose you use Visual Studio. If yes, learn how to use the debugger, it's very easy to use and very powerful. If no, learn how to use your debugger anyway.
But further in your program there may be other problems unrelated to your question, I didn't check.
I am having trouble doing my homework.
I am doing an RSA application which can encrypt and decrypt.
The problem is that after I Input things to encrypt the results are weird and I can't decrypt anything. This is because when I copied the results of encryption which are symbols, I got more weird stuffs.
I'm guessing it has something to do with my formula getting negative ASCIIs as results.
Below is what I tried, and, in order to understand what I meant by weird, just compile and try it out(I have some unused stuffs which I haven't removed yet):
Output:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define boolean int
#define true 1
#define false 0
//===================================================//
int p = 0;
int q = 0;
int n = 0;
int m = 0;
int divider = 2;
int tempdivider = 2;
int initial = 0;
int x = 0;
int y = 0;
char msg[100];
char alphabet[27];
//===================================================//
void cls();
void menu();
void init();
void reinit();
void inputencrypt();
//int encrypt(int num);
void encrypt();
char decrypt(char text[]);
int fpb(int num);
int d(int num);
int primecheck(int a);
boolean checkdigit(char text[]);
//===================================================//
int main() {
frontpage();
init();
menu();
getchar();
return 0;
}
//===================================================//
void cls() {
for (int i = 0;i < 25;i++) {
printf("\n");
}
}
//===================================================//
boolean checkdigit(char text[]) {
int len = strlen(text);
for (int i = 0;i < len;++i) {
if (text[i]<'0' || text[i]>'9') {
return false;
}
}
return true;
}
int primecheck(int a) {
if (a == 1) {
return false;
}
for (int i = 2;i < a;i++) {
if (a%i == 0) {
return false;
}
}
return true;
}
//===================================================//
void reinit() {
for (int i = 1;i < 27;i++) {
alphabet[i] = 'a' + i - 1;
}
p = 0;
q = 0;
n = 0;
m = 0;
divider = 2;
tempdivider = 2;
initial = 120;
x = 0;
y = 0;
}
void init() {
reinit();
do {
printf("p = ");
scanf("%d", &p);fflush(stdin);
if (!primecheck(p)) {
printf("must be prime number! \n");
}
} while (!primecheck(p));
do {
printf("q = ");
scanf("%d", &q);fflush(stdin);
if (!primecheck(q)) {
printf("must be prime number! \n");
}
} while (!primecheck(q));
n = p*q;
m = (p - 1)*(q - 1);
initial = m;
x = fpb(m);
y = d(m);
printf("n = %d\n", n);
printf("m = %d\n", m);
printf("e = %d\n", x);
printf("d = %d\n", y);
system("pause");
}
//===================================================//
void menu() {
char input[2];
int input1 = 0;
do {
do {
cls();
printf("main menu\n");
printf("================\n");
printf("1. encrypt\n");
printf("2. decrypt\n");
printf("3. exit\n");
printf(">> ");
scanf("%s", input);fflush(stdin);
if (checkdigit(input)) {
input1 = atoi(input);
}
} while (!checkdigit(input));
switch (input1) {
case 1:
int c;
char encrypted[100];
char word[100];
printf("input word to encrypt : ");
scanf(" %[^\n]", word);fflush(stdin);
for (int i = 0;i < strlen(word);i++) {
if (word[i] == ' ') {
encrypted[i] = ' ';
//i++;
}
else {
for (int j = 1;j < 27;j++) {
if (word[i] == alphabet[j]) {
c = 0;
c = pow(j, x);
c = c%n;
encrypted[i] = c;
break;
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", word[i]);
}
printf(" ]\n");
printf("\n\nEncrypted ASCII [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%d ", encrypted[i]);
}
printf(" ]\n");
printf("\n\nEncrypted [ ");
for (int i = 0;i < strlen(word);i++) {
//printf("%d", c);
printf("%c", encrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
case 2:
int temp[100];
char decrypted[100];
char wordx[100];
int h;
printf("input word to decrypt : ");
scanf(" %[^\n]", wordx);fflush(stdin);
for (int i = 0;i < strlen(wordx);i++) {
temp[i] = wordx[i];
//temp[i] -= 97;
//printf("%d ::: %c\n", temp[i], temp[i]);
}
for (int i = 0;i < strlen(wordx);i++) {
if (wordx[i] == ' ') {
decrypted[i] = ' ';
}
else {
h = 0;
h = pow(temp[i], y);
h = h%n;
decrypted[i] = h;
for (int j = 1;j < 27;j++) {
if (decrypted[i] == j) {
decrypted[i] = alphabet[j];
}
}
}
}
printf("\n\nWord ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", wordx[i]);
}
printf(" ]\n");
printf("\n\nDecrypted ASCII [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", c);
printf("%d ", decrypted[i]);
}
printf(" ]\n");
printf("\n\nDecrypted [ ");
for (int i = 0;i < strlen(wordx);i++) {
//printf("%d", decrypted[i]);
printf("%c", decrypted[i]);
}
printf(" ]");
printf("\n\n\n");
system("pause");
break;
}
} while (input1 != 3);
}
//===================================================//
int fpb(int num) {
if (!primecheck(num)) {
if (num%divider == 0) {
num = num / divider;
divider = 2;
}
else {
divider++;
}
fpb(num);
}
else if (primecheck(num)) {
if (!primecheck(num + divider)) {
tempdivider++;
divider = tempdivider;
num = initial;
fpb(num);
}
else {
return num + divider;
}
}
}
int d(int num) {
for (int i = 1;i < num;i++) {
if ((x*i) % num == 1) {
return i;
}
}
}
You have a general comprehension problem. Your console is only able to represent 96 characters correctly (known as printable 7bit-ASCII characters, 0x20 to 0x7F), but a byte can hold 255 different values. Your encryption algorithm does not care about this limited range, it will encrypt any value in the range [0..255] into another value in the range [0..255]. So your ASCII input characters will most likely be encrypted into values that cannot be represented by your console correctly. Copy&Past will not work correctly for non-printable characters (like 0x0B, which is a tab).
But now you will wonder: Why does that work for e.g. E-Mails? Simply: Because those characters are converted into an ASCII representation. Please google a bit for Base64 encoding.
As an alternative, you can always stream your encrypted characters into a file and later read back from that. This way you will bypass the limitations of your console.
Btw: Please have a look at the documentation of printf() and you will know, why you get those negative values.
The encrypt option has these three statements consecutively
c = 0;
c = pow(j, x);
c = c%n;
and the last of those will leave c in the range 0..(n-1).
Apart from that, there is no else clause and int c; can remain uninitialised.
So all in all it is inevitable that when you print c values as characters you will get "weird" results.
As for negative values, char encrypted[100]; is probably signed char so any integer value in the range 128..255 assigned to that, although undefined behaviour, may possibly show up as a negative number because the signed char is promoted back to int when passed as format %d to printf.
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;
}