Adding integers together in C but not mathematically [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How would one go about adding integers together like this.
Say you start with 1, then you add 2. So you have 12, next add 3, so you have 123. And so on.
I would just concatenate but I'm not allowed to use strings in this program.

Using some unusual math (based on the mechanisms of the decimal system) to make the desired variation of adding:
Code:
#include <stdio.h>
int main(void)
{
int i;
int number=0;
for (i=1; i<5; ++i)
{
number=number*10 + i;
printf("%d\n", number);
}
return 0;
}
Output:
1
12
123
1234

Like this?
#include <stdio.h>
int main() {
int a = 4, b = 5, c = 6, d = 7;
printf("a+b=%d\n",a*10+b);
printf("a+b+c=%d\n",(a*10+b)*10+c);
printf("a+b+c+d=%d\n",((a*10+b)*10+c)*10+d);
return 0;
}

This can be typical case to use realloc
char *mystr = NULL;
char *temp;
char c, ch;
short count = 0;
do {
printf("Enter character : ");
scanf(" %c", &c); // Better use sscanf or fgets, scanf is problematic
temp = (char*)realloc(mystr, (++count) * sizeof *mystr);
if (NULL != temp) {
mystr = temp;
mystr[count - 1] = c;
}
printf("Do you wish to continue: ");
scanf(" %c", &ch);
} while ('y' == ch);
// Since and since you don't have a null terminated string, do
for (int i = 0; i < count; i++)
printf("%c", mystr[i]);
printf("\n");
free(mystr); // Freeing the memory
getch();
Note : And you don't have strings in this program ;)

Related

Printing square using specified character and multiplying chars [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
Write a programme that prints a square pattern of side length M of any single character specified by the user using a single for loop and a single if else statement. You should define both M and the character constant C as preprocessor statements.
I actually did that but I wonder is there any easier way to solve this problem. Here's my code:
#include <stdio.h>
#include <string.h>
int
main()
{
int M, i = 1;
char C, G[1000];
printf("Input a value for side length:\n");
scanf("%d", &M);
printf("Input a character for pattern:\n");
scanf(" %c", &C);
for (; i <= M; i++) {
printf("%c", C);
if (i <= M) {
memset(G, C, (M - 1));
G[M - 1] = '\0';
puts(G);
}
}
return 0;
}
Something along these lines, perhaps:
int M1 = M + 1;
for (int i = 0; i < M*M1; ++i) {
if (i % M1 == M) putchar('\n');
else putchar(C);
}
You can do the memset outside of the loop once.
You can just do puts inside the loop:
#include <stdio.h>
#include <string.h>
int
main()
{
int M, i = 1;
char C, G[1000];
printf("Input a value for side length:\n");
scanf("%d", &M);
printf("Input a character for pattern:\n");
scanf(" %c", &C);
memset(G, C, M);
G[M] = '\0';
for (; i <= M; i++)
puts(G);
return 0;
}
For an input of 8 rows and a char of *, the output is:
Input a value for side length:
8
Input a character for pattern:
*
********
********
********
********
********
********
********
********
UPDATE:
After rereading the requirements, if C and M must be macros, the code should be:
#include <stdio.h>
#include <string.h>
#ifndef M
#error M not defined
#endif
#ifndef C
#error C not defined
#endif
int
main()
{
int i = 1;
char G[1000];
memset(G, C, M);
G[M] = '\0';
for (; i <= M; i++)
puts(G);
return 0;
}
And, the program should be compiled with:
cc -o program -DM=8 -DC="'*'" program.c

Keeping leading spaces in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm having this simple problem that I can't get over with.
int B;
char *a = (char*)malloc(1000*sizeof(char);
scanf("%[^\n]s", a);
printf("%c\n", a[0]);
B = strlen(a);
printf("%d\n", B);
If I put an entry like:
" abc "
a[0] = 'a' and B = 5 (the "abc" plus the last two spaces). I want to count the first three spaces, how do I do it?
You could simply read the entire line using fgets() instead of using scanf(), which generally skips whitespace unless you explicitly capture it.
int B;
char *a = malloc(1000 * sizeof*a); /* don't cast malloc */
if (fgets(a, 1000, stdin) == NULL) {
fputs("Could not read input\n", stdout);
}
else {
printf("%c\n", a[0]);
B = strlen(a);
printf("%d\n", B);
}
If you want to trim the leading space, you can try this:
void trim_left(char *p);
int main()
{
int B;
char *a = (char*)malloc(1000*sizeof(char));
scanf("%[^\n]s", a);
printf("%c\n", a[0]);
trim_left(a);
B = strlen(a);
printf("%d\n", B);
printf("a = %s\n", a);
return 0;
}
void trim_left(char *p) {
int i = 0;
while (p[i] && isspace(p[i])) {
i++;
}
memmove(p, p+i, strlen(p+i));
p[strlen(p+i)] = '\0';
}

Is there a way to print only the first word of a string with gets() in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am very new to programming and i wonder if there is a way to print out the first word of a string with gets() in C?
void printFirstWord(char string[])
{
int i;
for(i = 0; i < (string[i] != '\0'); i++)
{
if(isalpha(string[i]))
printf("%c", string[i]);
}
}
int main()
{
char string[MAX];
printf("Type in a scentence");
gets(string);
printFirstWord(string);
return 0;
}
This is the function that i have written and called in main right now. Is it because i have isalpha in the function?
In your implementation, you might add the following line in the loop:
if (string[i] == ' ')
break;
also, fix your loop parameters e.g. like this:
for (i = 0; i < strlen(string); i++)
Overall implementation in you way will be as below.
Consider choosing another design according to comments you got, e.g. not using gets.
void printFirstWord(char string[])
{
int i;
for (i = 0; i < strlen(string); i++)
{
if (isalpha(string[i]))
printf("%c", string[i]);
if (string[i] == ' ')
break;
}
}
int main()
{
#define MAX 100
char string[MAX];
printf("Type in a scentence\n");
gets_s(string, MAX);
printFirstWord(string);
getchar();
return 0;
}
I just found a way with isblank(); function, hope it helps to anybody :)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (){
int length, number, counter, position;
char name[50];
printf("Please type your complete name:\n");
gets(name);
//strlen();
//Returns the length of the given null-terminated byte string, that is, the number of characters in a character array
length=strlen(name);
//Counts each position until it finds a space
for(counter=0;counter<length;counter++)
{
if(isblank(name[counter]))
position=counter;
}
//Prints each character until the counter reaches the position number given by the counter variable
printf("\nThe first word you typed is: ");
for(number=0; number<=position; number++){
printf("%c", name[number]);
}
}

Reverse the order of an integer in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am currently learning C as part of a course and I have a task to reverse the order of a number without using any arithmetic (wording of the task).
I currently have this:
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
while (n != 0) {
reverse = reverse * 10;
reverse = reverse + n_10;
n = n / 10;
}
printf("Reverse of entered number is = %d\n", reverse);
return 0;
}
But this solution uses arithmetic. How can I alter this to complete the task?
From the exercise sheet, "though even at three
digits the naïve approach quickly grows unmanageable with arithmetic (try it!).
Your goal: Design 3-digit solution without using any arithmetic.(Hint: use scanf.)"
The wording of the question was confusing but to be clear the question is:
How do you reverse the order of a number, e.g. 123456789 to 987654321, without without using math. So the solution is to scanf to read the number and swap the numbers in a loop as the answer below.
You can just read it in as a string.
int main()
{
char str[80];
fgets(str, 80, stdin);
strrev(str);
printf("%s\n", str);
}
void strrev(char *str)
{
char *end, tmp;
end = str + strlen(str) - 1;
for (; end > str; --end, ++str) {
tmp = *end;
*end = *str;
*str = tmp;
}
}
I don't know if you consider pointer arithmetic to be "arithmetic"
Read as series of short strings that can hold 1 digit and then print in the reserve order.
char buf[10][2] = { 0 };
scanf("%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]",
&buf[0], &buf[1], &buf[2], &buf[3], &buf[4],
&buf[5], &buf[6], &buf[7], &buf[8], &buf[9]);
printf("%s%s%s%s%s%s%s%s%s%s",
buf[9], buf[8], buf[7], buf[6], buf[5],
buf[4], buf[3], buf[2], buf[1], buf[0]);
Obviously limited to max 10 digits.
A recusive approach, inpsired by #Nisse Engström. Works for any reasonable length input.
void pr(void) {
char digit[2];
if (scanf("%1[0-9]",digit)) {
pr();
printf("%s",digit);
}
}
int main(void) {
pr();
return 0;
}
Input
012345678901234567890123456789
Output
987654321098765432109876543210
Of course if (scanf("%1[0-9]",digit)) { should be if (scanf("%1[0-9]",digit) == 1) { to cope with EOF but that then may be "arithmetic".
Using scanf():
int
scanf (){
int
stdin =
getchar ();
return
stdin <0||
stdin ==
'\n'?
stdin :(
scanf (),
putchar (
stdin )),
'\n';}
int
main (){
putchar (
scanf ()
);}
Read integer, use sprintf() function to convert it into string and then use the library function strrev() to reverse the string.

Weird results in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'd like to ask you about my prog. The main purpose of this one is to fill the "result" array with data collect from "tab1" and "tab2" arrays. Could anybody check, why does results are so weird? Thank you.
#include <stdio.h>
#include <stdlib.h>
void laczenie(char tab1[],char tab2[])
{
int i;
char* result =(char*) malloc(100*sizeof(char));
for(i=0;i<30;i++)
{
if(tab1[i] != '\0') tab1[i]==result[i];
else if (tab2[i] !='\0')tab2[i]==result[i];
else printf(" ");
}
for(i=0;i<30;i++)printf("%c",result[i]);
free(result);
}
int main()
{
char x[10]={'n','a','p','i','s','1'};
char y[10]={'n','a','p','i','s','2'};
//char x[10] = {"napis1"};
//char y[10] = {"napis2"};
laczenie(x,y);
return 0;}
In addition to LihOs answer above this block looks wrong:
if(tab1[i] != '\0')
tab1[i]==result[i];
else if (tab2[i] !='\0')
tab2[i]==result[i];
else printf(" ");
Don't you mean to assign the value in tab1[i]or tab2[i] to result[i]like this?
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");
Also using magic numbers like in the loops: for(i=0;i<30;i++) is pretty bad practice, you should probably be using a constant for the size value (which you could then use in both the loops and in the array declarations. And why loop to 30 when the arrays is 10 elements only?
In your function you check for null-terminating character:
if(tab1[i] != '\0')
but where is null-terminating character here?
char x[10]={'n','a','p','i','s','1'};
Try:
char x[7]={'n','a','p','i','s','1','\0'};
Also note that tab1[i]==result[i]; compares tab[1] with result[i], if you want to assign the result[i] to tab1[i], use assignment operator =:
tab1[i]=result[i];
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");`
This is still wrong as by the time you assign tab2 to result i will be already at 6 so you will have to use two for loops i suppose for assign tab1 and tab 2

Resources