Multiplying string - c

I want to make a lines of stars, each line containing more then the previous one. The point of my problem is that I don´t know how to multiply strings in C.
#include<stdio.h>
#include<conio.h>
main()
{
int max = 10
for (int i = 1; i <= max; ++i){
printf("*"*(2 * i - 1);
}
}

You can just repeat printing the desired number of strings.
#include<stdio.h>
#include<conio.h>
main()
{
int max = 10; // a semicolon is added to make it compile
for (int i = 1; i <= max; ++i){
for (int j = 0; j < (2 * i - 1); j++){ // repeat (2 * i - 1) times
printf("*");
}
printf("\n"); // separate lines
}
}
I respect the original code, so some points that are not good (meaningless including of non-standard conio.h and non-standard definition of main() (instead of int main(void))) remains.

The language semantics do not support what you are trying to do. In C a string is not a first class type in any case - it is simply an array of char, so all string handling is performed through functions; you cannot perform direct operations on them; and even if you could I doubt multiply would be one of them - it has a very limited use case easily implemented using simpler operations.
In this case you do not in fact need repeated string replication (or multiply as you refer to it) since you are outputting the string directly so have no need to store the string and the associated memory allocation issues that entails. Rather you simply need repeated string output.
#include <stdio.h>
void printRepeatString( const char* str, int n )
{
for( int i = 0; i < n; n++ )
{
printf( "%s", str ) ;
}
}
int main( void )
{
const int max = 10
for (int i = 1; i <= max; i++ )
{
printRepeatString( "*", (2 * i) - 1 ) ;
putchar( '\n' ) ;
}
return 0 ;
}

An alternative to "multiplying" a string of '*' is to create the longest one and then print a truncated portion of it.
Use "%.*s", n, s to print a character array s up to n characters.
#include<stdio.h>
#define MAX 10
int main(void) {
char s[2 * MAX] = {0};
memset(s, '*', 2 * MAX - 1);
for (int i = 1; i <= MAX; ++i) {
printf("%.*s\n", 2 * i - 1, s);
}
}
Output
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

Related

Remove Duplicates from Sorted Array Clean Code

Hello everyone,
I wrote an code which is remove duplicates from sorted array. I know that there are lots of people have a good know how about clean code in this platform. I want to write code especially clean code. So I wanna hear some suggestion this about. If yo critise my code I am glad.
#include <stdio.h>
int main()
{
int arr[]={1,2,2,2,3,4,4,4,5,6,7,7,7,8,8};
int arr_size = *(&arr + 1) - arr;
printf("length of array %d\n",arr_size);
int result[arr_size];
int last_item= result[0];
for (int i=0; i<arr_size;i++)
{
if(arr[i]!=last_item)
{
last_item= arr[i];
result[i]= last_item;
printf("result : %d\n", result[i]);
}
}
return 1;
}
For starters it is unclear why main returns 1 instead of 0.
Secondly you are not removing duplicate elements from an array. You are trying to copy unique elements from one array into another array.
Also it is unclear why the result array has arr_size elements as the source array.
This declaration
int last_item= result[0];
is invalid because the result array is not initialized. So it contains indeterminate values.
Also in the for loop you are using the invalid index i for the result array. So again some elements of the result array will have indeterminate values.
result[i]= last_item;
And within the for loop there should not be any call of printf. If you want to output the result array (it is already another task) then you need to use a separate loop or function.
And at last you should write a separate function that performs the task of copying unique or removing duplicate elements..
I would write a function that indeed removes duplicates from an array the following way as shown in the demonstration program below.
#include <stdio.h>
size_t remove_duplicates( int a[], size_t n )
{
size_t m = 0;
for (size_t i = 0; i < n; i++)
{
if ( i == 0 || a[i] != a[m-1])
{
if (i != m)
{
a[m] = a[i];
}
++m;
}
}
return m;
}
int main( void )
{
int arr[] = { 1,2,2,2,3,4,4,4,5,6,7,7,7,8,8 };
const size_t N = sizeof( arr ) / sizeof( *arr );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
size_t m = remove_duplicates( arr, N );
for (size_t i = 0; i < m; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
The program output is
1 2 2 2 3 4 4 4 5 6 7 7 7 8 8
1 2 3 4 5 6 7 8

Bubble sort takes a long time then segfaults

Given an integer n, write a C program to count the number of digits that are in the same position after forming an integer m with the digits in n but in ascending order of digits. For example, if the value of n is 351462987 then value of m will be 123456789 and digits 4 and 8 will be in the same position.
This is my code:
#include<stdio.h>
void bubble(int a[],int length)
{
for (int i=0;i<length;i++)
{
for (int j=0;j<length;j++)
{
if (a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
int check(int a[],int b[],int length)
{
int count=0;
for (int i=0;i<length;i++)
{
if (a[i]==b[i])
{
count=i;
break;
}
}
return count;
}
int length(int n)
{
int l;
while (n!=0)
{
n=n/10;
l++;
}
return l;
}
void main()
{
int n,arrn[100],temp[100];
scanf("%d",&n);
int l=length(n);
for (int i=0;i<l;i++)
{
arrn[l-i-1]=n%10;
temp[l-i-1]=arrn[l-i-1];
n=n/10;
}
bubble(temp,l);
int c=check(arrn,temp,l);
printf("%d",c);
}
I am able to compile the code but when I execute it it takes a long time only to show segmentation fault.
Easy answer, use a debugger.
Here are some problem with your code:
In length function, l is not initialized and as such can have an arbitrary initial value. In your case, you probably want to start at 0.
int l = 0;
Your check function probably don't do what you want. As written count is not a count but the index of a position where numbers match. As there is a break statement in the block, the loop will exit after the first match so the return value would be the position of the first match or 0 if no match was found.
Your bubble function goes one item too far when i is equal to length - 1 as you access item a[j + 1] in the inner loop which is out of bound. In that case, it is simpler to start at 1 instead of 0 and compare item at index i - 1 with item at index i.
Some extra notes:
It is recommended to add whitespace around operators and after a comma separating multiple declarations to improve readability. Here are some example of lines with improved readability.
int n, arrn[100], temp[100];
int count = 0;
for (int i = 0; i < length; i++)…
if (a[i] == b[i])…
arrn[l - i - 1] =n % 10;
temp[l - i - 1] = arrn[l - i - 1];
int check(int a[], int b[], int length)
Instead of writing multiple functions at once, you should write one function and ensure it works properly. By the way, the loop that split a number into digits could also be a function.
Try the function with small number (ex. 12 or 21)
Use better name for your variable. arrn and temp are not very clear. original and sorted might be better.
Your length function has a very obvious bug in it. What value does l start with? You don't initialise it so it could start with any value and cause undefined behaviour. You should set it to 0.
int length(int n)
{
int l = 0;
while (n!=0)
{
n=n/10;
l++;
}
return l;
}
Personally, I wouldn't be sorting or reading it into an int - to enable handling leading zeros in the digit string. For example:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXNUMLEN 200
int main(void)
{
int i, j, l, x=0;
char numin[MAXNUMLEN], numout[MAXNUMLEN];
int digits[10]={0};
printf("enter a string of digits: " );
fgets(numin, sizeof(numin), stdin);
printf("\nsaw : %s", numin );
// walk string once, counting num of each digit present
l=strlen(numin);
for(i=0; i<l; i++) {
if( isdigit(numin[i]) ) {
int d = numin[i] - '0'; // char digit to int digit
digits[d]++;
}
}
// for each digit present, write the number of instances of the digit to numout
for( i=0; i<10; i++ ) {
for(j=0; j<digits[i]; j++)
numout[x++] = '0'+i; // int digit back to char digit
}
numout[x]='\0'; // terminate string
printf("sorted: %s\n", numout );
}
Sample run:
watson:digsort john$ ./ds
enter a string of digits: 002342123492738234610
saw : 002342123492738234610
sorted: 000112222233334446789
watson:digsort john$

C program output not formatting properly(using \t)

I am just wondering and confused as too why my output is messed up. The code is below. I am a beginner so please excuse my lack of skill. Any help would be very much appreciated.
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= i; j++)
{
printf("*");
}
printf("\t");
for (int k = 1; k <= 11-i; k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Gives this output:
My desired output is this:
\t stops at the next reachable tab position, which by default are multiples of 8.
Therefore, if you print ***, it will skip to column 8, but if you print *********, you are already past 8, so it skips to column 16.
The precision and width fields can be use for formatting. Precision will print up to the specified number of characters and width will print at least the specified number of characters. Using an asterisk in either field allows an argument for a variable number of characters.
#include <stdio.h>
int main( void) {
char asterisk[] = "***********";
for (int i = 1; i <= 10; i++)
{
printf ( "%.*s", i, asterisk);//print up to i characters
printf ( "%*s", 15 - i, " ");//print at least 15 - i characters
printf ( "%.*s", 11 - i, asterisk);
printf("\n");
}
return 0;
}
... why my output is messed up (?)
Code uses a tab '\t' which only aligns to the next tab-stop - usual every 8 columns and the stars needed exceed 8.
With judicious use of the '-' flag, field width and precision, code can be simplified to print an array of characters.
#include <stdio.h>
#include <string.h>
int main(void) {
int n = 10;
char stars[n];
memset(stars, '*', n);
for (int i = 0; i < n; i++) {
// +------------- - flag: pad on right
// |+------------ field width: min characters to print, pad with spaces
// || +--------+- precision: max numbers of characters of the array to print
printf("%-*.*s %.*s\n", n, i + 1, stars, n - i, stars);
// | ^^^^^ ^^^^^ precision
// +--------------------- field width
}
}
Output
* **********
** *********
*** ********
**** *******
***** ******
****** *****
******* ****
******** ***
********* **
********** *
Note: stars is not a string as it lacks a null character. Use of a precision with "%s" allows printf() to use a simple character array. Characters from the array are written up to (but not including) a terminating null character.
A tab-stop is not a fixed-width space (e.g. the same as 4 spaces or 8 spaces), it means that the output device should move the caret (or print-head) to the next column position for tabular data. These column positions are at fixed regular intervals, that's why \t** and **\t have different printed widths:
String Output:
"\t**a" " **a" (7 wide)
"**\ta" "** a" (5 wide)
As others have mentioned, printing a tab character move the cursor to the next tab stop, not a certain number of spaces.
After printing the first set of asterisks, print spaces until you've printed enough characters to space out as far as you need.
for (int j = 1; j <= 10; j++)
{
if (j<i) {
printf("*");
} else {
printf(" ");
}
}
I would do like this:
const int rows = 10;
for (int i = 0; i < rows; i++) {
const int width = 10;
const int space = 5;
const int totalw = 2*width + space;
for (int j = 0; j < totalw; j++) {
char ch = j<=i || (j>=width+space && j<(totalw-i)) ? '*' : ' ';
printf("%c", ch);
}
printf("\n");
}
And just for completeness, even though mentioned in other answers. The '\t' character does not have a fixed width.

How do I print out 100 numbers in an array then add them using C

I'm trying to print out 100 numbers from an array using a loop and then add them all together. So far I have:
#include <stdio.h>
#include <stdlib.h>
int main(){
int* number = malloc(101 * sizeof(int));
int num = 0;
number[num] = 1;
while (number[num] <= 100){
printf(" %d\n ", number[num]);
num = num +1;
number[num] = number[num]+1;
}
return 0;
}
but this just prints 1 once.
number[num] = number[num]+1;
You only properly set number[0]. Now you are trying to take whats in number[1] and add to it, in the first iteration. You didn't set it to anything though, leaving it uninitialised. This is undefined behaviour. What you most likely wanted to do is
number[num] = number[num-1]+1;
To add one to the previous number before after printing it. Now it will print fine.
To add them up, simply do
for (int a = 0; a < 100; a++) {
number[100] += number[a]; // add number[a] to result
}
printf("%d\n",number[100]);
Also, don't forget to free your dynamically allocated array at the end.
Try this:
#include <stdio.h>
int main () {
int n[ 100 ]; /* n is an array of 100 integers */
int i,j;
int sum = 0;
/* initialization */
for ( i = 0; i < 100; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 100; j++ ) {
printf("Element[%d] = %d\n", j, n[j]);
sum += n[j];
}
printf("Sum of Elements = %d\n", sum);
return 0;
}
Remember that you should declare an array, then initialize it, print it out and after all print out the sum
You can just print out 1 to 100, then you could quickly use some maths to get the count of all numbers added together, for example, one of Gauss' algorithms, specifically http://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/
There’s a popular story that Gauss, mathematician extraordinaire, had a lazy teacher. The so-called educator wanted to keep the kids busy so he could take a nap; he asked the class to add the numbers 1 to 100.
Here's what I would do: -
int i = 0;
for (i = 1; i <= 100; i++) {
printf("%d", i);
}
// gauss technique 100(100 + 1) / 2
int count = (100 * 100 + 100 * 1) / 2;
printf("all numbers added: %d", count);

Find missing number between 1 to 100

This question has been asked here on SO before with below code
find3missing(int* array)
{
int newarray[100] = {0};
For i = 0 to 99
++newarray[array[i]] ;
For i = 0 to 99
If newarray[i] != 1
Cout << “the missing number is ” << i+1 << endl ;
}
But when I checked this code, it doesn't seem to work. Suppose I have an array of {1,2,6}. The output should be 3,4,5 but with the code above I get 1,4,5,6 instead. Below is my implementation of pseudo code with array size 6.
main()
{
int a[6]={1,2,6};
int tmp[6]={0},i;
for(i=0;i<6;i++)
{
++tmp[a[i]];
}
for(i=0;i<6;i++)
{
if(tmp[i]!=1)
{
printf("%d",i+1);
}
}
}
Is this the right code?
This ++newarray[array[i]] should be ++newarray[array[i] - 1]. This because you are interested in a sequence of 1-100 numbers, so no 0, but C arrays are 0 based. If you then look at the cout: the missing number is ” << i+1 here you "unshift" the number by adding 1.
There is another problem: you should pass the number of elements of the array, something like:
find3missing(int* array, int length) {
int newarray[100] = {0};
for (int i = 0; i < length; i++) {
++newarray[array[i] - 1] ;
}
C/C++ arrays are zero based, as A[i] is equivalent to *(A+i). So change ++newarray[array[i]] to ++newarray[array[i]-1]. Also use malloc, free and memset to use an array of dynamic size.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void find3missing(int* pArray, size_t size, int min, int max){
int* newarray;
int i;
unsigned int j;
int range = max - min;
if(range < 0)
return;
newarray = (int*) malloc(range*sizeof(int)); // allocate enough memory
memset(newarray,0,range*sizeof(int)); // set that block to zero
for(j = 0; j < size; ++j){
++newarray[pArray[j]-min];
}
for(i = 0; i < range; ++i){
if(!newarray[i])
printf("%d is missing!\n",min+i);
}
free(newarray);
}
int main(){
int test[] = {1,3,6};
find3missing(test,sizeof(test)/sizeof(int),1,6);
return 0;
}
Please note that this solution is very inefficient if your array is sorted. In this case have a look at Jimmy Gustafsson's answer.
This algoritm will be quite simple, since you're using a sorted array. Simply check if the current value +1 equals the nextvalue like below:
find3missing(){
int array[arraySize]; // the array with integers
for(i=0;i<arraySize;i++)
if(array[i]+1 != array[i+1]) // if value array[i]+1 is not equal the next index
// value, then it's a missing number
printf("A missing number: %i", i+1);
}

Resources