Just writing some code to sort an array using bubble sort, but right at the start I couldn't even define an array and print it.
Code:
#include <stdio.h>
int main () {
int test[] = {9,9,9,9,9}; //define array
test[2] = 3;
bool checker = false; //is it sorted?
int i = 0;
for(int i = 0; i<=4; i++) //set random numbers for array
{
int g;
g = 4+i;
test[i] = g;
i++;
}
for (int i = 0; i <= 4; ++i ) //print array as normal
{
printf(", ", test[i]);
}
When executed it always outputs:
, , , ,
so the array is empty? or im printing it wrong? or something?
You are printing it wrong.
The line in which you are printing should read printf("%d, ", test[i]);
Also not that you have tagged the question as C++, but are using C related terms. Your #include <stdio.h> should be replaced by #include <iostream> and you should be using cout instead of printf for outputting data.
You have two problems in your code.
First, the initial 'for' loop uses 'i' as its counter variable, and your increment condition is 'i++'. That means 'i' automatically increments through each loop iteration; yet within the loop, you specify 'i++', meaning you will see the value of 'i' bumped twice with each pass. Eliminate the extraneous increment.
Second, you are printing the array incorrectly. You need to add a format qualifier such as '%d' to tell printf to use the first argument as a replacement for that specifier.
Lastly, you've indicated C++ for this code, but it really isn't. It's classic C.
Related
I am quite new to C so my apologies if this is a straight forward problem but I cannot seem to find my error. My code is as follows
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* makeString(char character,int count)
{
int i;
char* finalString=malloc(count+1);
for(i=1;i<=count;i++)
{
finalString[i]=character;
}
finalString[count]=0;
return finalString;
}
int main()
{
char* string=makeString('*',5);
printf("%s\n",string);
}
I am trying to get an output of the finalString which would be 'character', 'count' number of times. I am not getting any errors or warnings but It is not generating any output. When debugging it runs the loop successfully but does not ever store any character into finalString. Any help appreciated.
As with many programming languages, C uses 0-based indices for arrays. The first element of the character array at finalString is finalString[0], not finalString[1].
Your for loop should go from 0 to count - 1, instead of from 1 to count. The line:
for(i = 1; i <= count; i++)
should instead be:
for(i = 0; i < count; i++)
As your code is now, you have undefined behaviour, because you try to print finalString[0], which is uninitialized. In this case, it seems to be 0 ('\0').
I've ignored the fact that makeString is missing its closing }, since you say this compiles correctly, I assume that's a pasting error.
Arrays in C begin at 0, i.e. the 1st element is finalString[0].
Since you do not set it, it contains garbage, and most probably a NUL which ends the string immediately.
Your loop should look like
for(i=0;i<count;i++)
...
and so on.
I'm having issues on printing an array, that's what I'm doing:
#include <stdio.h>
#define DIM 5
int main () {
double data[DIM] = {128.5, 131.4, 133.2, 127.1, 130.9};
printf("%lf", data[DIM]);
return 0;
}
The answer is always 0.000000.
I've also tried to put the values separately, like this:
#include <stdio.h>
#define DIM 5
int main () {
double data[DIM];
data[0]=128.5;
data[1]=131.4;
data[2]=133.2;
data[3]=127.1;
data[4]=130.9;
printf("%lf", data[DIM]);
return 0;
}
And still the answer is always 0.000000.
Could someone please help. Thank you in advance!
As 4386427 and 500 - Internal Server Error pointed out, there are two issues at work here.
You are trying to print an out-of-bounds index. When you make an array of length 5, indexes go from 0 to 4.
More importantly, there is no specific "print array" function that I am aware of. Your best bet is to create a loop that prints each element of the array.
void printDoubleArray(double arr[], int length)
{
printf("[");
if (length > 0)
{
printf("%f", arr[0]);
}
for (int i = 1; i < length; i++)
{
printf(", %f", arr[i]);
}
printf("]\n");
}
In this call
printf("%lf", data[DIM]);
you are trying to output a non-existent element of the array with the index DIM while the valid range of indices for the array is [0, DIM). This record means that 0 is included in the range as a valid index and DIM is excluded from the range.
As a result the call of printf invokes undefined behavior.
Also you should use the conversion specifier f instead of lf. The length modifier l does not have an effect used with the conversion specifier f. So it is just redundant.
You can not output a whole array except character arrays (by means of the conversion specifier s).
To output the whole array you need to use a loop as for example
for ( size_t i = 0; i < DIM; i++ )
{
printf( "%.1f ", data[i] );
}
putchar( '\n' );
Here is a demonstrative program.
#include <stdio.h>
#define DIM 5
int main(void)
{
double data[DIM] = { 128.5, 131.4, 133.2, 127.1, 130.9 };
for ( size_t i = 0; i < DIM; i++ )
{
printf( "%.1f ", data[i] );
}
putchar( '\n' );
return 0;
}
The program output is
128.5 131.4 133.2 127.1 130.9
C, the language itself, does not have array bounds checking. You want the element one past the end? sure thing. You want the element a million past the end? sure you can ask for that too (who knows what will happen but you can ask for it)
If your compiler supports it, you can get more robust error reporting. Not C standard but helpful nonetheless.
GCC:
Compile with -fsanitize=address and at run-time the sanitizer will catch this overrun:
=======================
==220715==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffed8db4988 at pc 0x559ba54babcc bp 0x7ffed8db4920 sp 0x7ffed8db4910
READ of size 8 at 0x7ffed8db4988 thread T0
#0 0x559ba54babcb in main /tmp/overrun.c:9
clang:
In addition to the run-time sanitizer (-fsanitize=address), Clang can also point out your problem at compile time:
printf("%lf", data[DIM]);
^ ~~~
overrun.c:7:5: note: array 'data' declared here
double data[DIM] = {128.5, 131.4, 133.2, 127.1, 130.9};
^
1 warning generated.
I'm trying to create a complete C program to read ten alphabets and display them on the screen. I shall also have to find the number of a certain element and print it on the screen.
#include <stdio.h>
#include <conio.h>
void listAlpha( char ch)
{
printf(" %c", ch);
}
int readAlpha(){
char arr[10];
int count = 1, iterator = 0;
for(int iterator=0; iterator<10; iterator++){
printf("\nAlphabet %d:", count);
scanf(" %c", &arr[iterator]);
count++;
}
printf("-----------------------------------------");
printf("List of alphabets: ");
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
listAlpha(arr[x]);
}
printf("%c",arr);
return 0;
}
int findTotal(){
}
int main(){
readAlpha();
}
The code should be added in the findTotal() element. The output is expected as below.
Output:
List of alphabets : C C C A B C B A C C //I've worked out this part.
Total alphabet A: 2
Total alphabet B: 2
Total alphabet C: 6
Alphabet with highest hit is C
I use an array to count the number of the existence of each character,
I did this code but the display of number of each character is repeated in the loop
int main()
{
char arr[100];
printf("Give a text :");
gets(arr);
int k=strlen(arr);
for(int iterator=0; iterator<k; iterator++)
{
printf("[%c]",arr[iterator]);
}
int T[k];
for(int i=0;i<k;i++)
{
T[i]=arr[i];
}
int cpt1=0;
char d;
for(int i=0;i<k;i++)
{int cpt=0;
for(int j=0;j<k;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>cpt1)
{
cpt1=cpt;
d=T[i];
}
printf("\nTotal alphabet %c : %d \n",T[i],cpt);
}
printf("\nAlphabet with highest hit is : %c\n",d,cpt1);
}
There is no way to get the number of elements You write in an array.
Array in C is just a space in the memory.
C does not know what elements are actual data.
But there are common ways to solve this problem in C:
as mentioned above, create an array with one extra element and, fill the element after the last actual element with zero ('\0'). Zero means the end of the actual data. It is right if you do not wish to use '\0' among characters to be processed. It is similar to null-terminated strings in C.
add the variable to store the number of elements in an array. It is similar to Pascal-strings.
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 10
char array[ARRAY_SIZE + 1];
int array_len(char * inp_arr) {
int ret_val = 0;
while (inp_arr[ret_val] != '\0')
++ret_val;
return ret_val;
}
float array_with_level[ARRAY_SIZE];
int array_with_level_level;
int main() {
array[0] = '\0';
memcpy(array, "hello!\0", 7); // 7'th element is 0
printf("array with 0 at the end\n");
printf("%s, length is %d\n", array, array_len(array));
array_with_level_level = 0;
const int fill_level = 5;
int iter;
for (iter = 0; iter < fill_level; ++iter) {
array_with_level[iter] = iter*iter/2.0;
}
array_with_level_level = iter;
printf("array with length in the dedicated variable\n");
for (int i1 = 0; i1 < array_with_level_level; ++i1)
printf("%02d:%02.2f ", i1, array_with_level[i1]);
printf(", length is %d", array_with_level_level);
return 0;
}
<conio.h> is a non-standard header. I assume you're using Turbo C/C++ because it's part of your course. Turbo C/C++ is a terrible implementation (in 2020) and the only known reason to use it is because your lecturer made you!
However everything you actually use here is standard. I believe you can remove it.
printf("%c",arr); doesn't make sense. arr will be passed as a pointer (to the first character in the array) but %c expects a character value. I'm not sure what you want that line to do but it doesn't look useful - you've listed the array in the for-loop.
I suggest you remove it. If you do don't worry about a \0. You only need that if you want to treat arr as a string but in the code you're handling it quite validly as an array of 10 characters without calling any functions that expect a string. That's when it needs to contain a 0 terminator.
Also add return 0; to the end of main(). It means 'execution successful' and is required to be conformant.
With those 3 changes an input of ABCDEFGHIJ produces:
Alphabet 1:
Alphabet 2:
Alphabet 3:
Alphabet 4:
Alphabet 5:
Alphabet 6:
Alphabet 7:
Alphabet 8:
Alphabet 9:
Alphabet 10:-----------------------------------------List of alphabets: A B C D E F G H I J
It's not pretty but that's what you asked for and it at least shows you've successfully read in the letters. You may want to tidy it up...
Remove printf("\nAlphabet %d:", count); and insert printf("\nAlphabet %d: %c", count,arr[iterator]); after scanf(" %c", &arr[iterator]);.
Put a newline before and after the line of minus signs (printf("\n-----------------------------------------\n"); and it looks better to me.
But that's just cosmetics. It's up to you.
There's a number of ways to find the most frequent character. But at this level I recommend a simple nested loop.
Here's a function that finds the most common character (rather than the count of the most common character) and if there's a tie (two characters with the same count) it returns the one that appears first.
char findCommonest(const char* arr){
char commonest='#'; //Arbitrary Bad value!
int high_count=0;
for(int ch=0;ch<10;++ch){
const char counting=arr[ch];
int count=0;
for(int c=0;c<10;++c){
if(arr[c]==counting){
++count;
}
}
if(count>high_count){
high_count=count;
commonest=counting;
}
}
return commonest;
}
It's not very efficient and you might like to put some printfs in to see why!
But I think it's at your level of expertise to understand. Eventually.
Here's a version that unit-tests that function. Never write code without a unit test battery of some kind. It might look like chore but it'll help debug your code.
https://ideone.com/DVy7Cn
Footnote: I've made minimal changes to your code. There's comments with some good advice that you shouldn't hardcode the array size as 10 and certainly not litter the code with that value (e.g. #define ALPHABET_LIST_SIZE (10) at the top).
I have used const but that may be something you haven't yet met. If you don't understand it and don't want to learn it, remove it.
The terms of your course will forbid plagiarism. You may not cut and paste my code into yours. You are obliged to understand the ideas and implement it yourself. My code is very inefficient. You might want to do something about that!
The only run-time problem I see in your code is this statement:
printf("%c",arr);
Is wrong. At this point in your program, arr is an array of char, not a single char as expected by the format specifier %c. For this to work, the printf() needs to be expanded to:
printf("%c%c%c%c%c%c%c%c%c%c\n",
arr[0],arr[1],arr[2],arr[3],arr[4],
arr[5],arr[6],arr[7],arr[8],arr[9]);
Or: treat arr as a string rather than just a char array. Declare arr as `char arr[11] = {0};//extra space for null termination
printf("%s\n", arr);//to print the string
Regarding this part of your stated objective:
"I shall also have to find the number of a certain element and print it on the screen. I'm new to this. Please help me out."
The steps below are offered to modify the following work
int findTotal(){
}
Change prototype to:
int FindTotal(char *arr);
count each occurrence of unique element in array (How to reference)
Adapt above reference to use printf and formatting to match your stated output. (How to reference)
This is the first part of the program and I have a few questions on how parts of it work exactly. Keep in mind this is the first C program I have written. scanf("%d",&numberOfTimes); Why do I need the & and what does it do?
char input[][200]; Is this basically an array of strings or is it something completely different?
#include <stdio.h>
#include <string.h>
char outputs[100];
char input[][200];
int numberOfTimes;
void io(void){
scanf("%d", &numberOfTimes);
for(int i = 0; i < numberOfTimes; i++){
scanf("%s",input[i]);
}
}
This next part of the code is my attempt at actually solving the problem however I suspect that I screwed up the use of a function but I don't know which one or I used something improperly in order to get this result. (I provided example i/o of me code at the bottom).
void stringManipulation(char string[200]){
int strLength = strlen(string);
int number = strLength/2;
for(int i = 0; i <= number; i=i+2){
strcat(outputs,&string[i]);
}
}
int main(void) {
io();
for(int i = 0; i < numberOfTimes; i++) {
stringManipulation(input[i]);
printf("%s\n",outputs);
memset(&outputs[0], 0, sizeof(outputs));
}
return 0;
}
Did I use memset properly? Again I don't understand the use of the &.
Example input:
4
your
progress
is
noticeable
Expected output:
y
po
i
ntc
Output I am getting:
yourur
progressogressress
is
noticeableticeableceable
Thank you for your help.
The & before a variable means that you are referring to the address of the variable, and not the variable value itself. If you don't know about what the address of a variable is : http://www.cquestions.com/2010/02/address-of-variable-in-c.html
char input[][200] is an array of char array (a char array is vulgarized as a string but it ISN'T the TYPE).
Your problem is about your strcat use, you're adding characters that are between string[i] (included) and string[strLength], not only the string[i] character.
Your problem is in strcat:
Your code passes the address and hence you are getting the entire string from that character onward.
strcat(outputs,&string[i]);
Now, change the above code as below:
strcat(output,string[i]);
You'll get the desired output. The problem with your initial code was that you were passing the address and not individual character.
Also, change the for loop in such a way that "<"number and not "<="number.
Let me know if you have any more doubts.
I have this function that will make an array of chars (ie a string) into a right triangle. It works but then it keeps going even after the array has stopped. So the output always has many extra lines of blank space.
and if the word is long enough random symbols will appear at the end of that blank space. This is probably because the blank space exited the arrays size of 100.
I dont know whats causeing this. I tried to set conditions to the counter and the printf that makes a new line but that just breaks the code entirely. I thought it was definitely the printf for new lines doing it but it doesnt seem like it now after trying that.
Does anyone see whats wrong?
Below is the remote function from my code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define clear system("cls")
#define pause system("pause")
void triangulate(char stringArray[]){
int i,j,len = 0;
int counter=0;
len=strlen(stringArray);//a function library function that returns the length
printf("\n");
for(i=1;i<=len;++i){
for(j=1;j<=i;++j){
printf("%c",stringArray[counter]);
counter++;
}
printf("\n");
}
printf("len:%i counter:%i",len, counter);
pause;
}//end triangulate()
This is wrong:
for(i=1;i<=len;++i) {
for(j=1;j<=i;++j) {
printf("%c",stringArray[counter]);
counter++;
}
printf("\n");
}
You can't increment counter so many times. Because of the nested loops, counter will access out of bounds positions - you are incrementing it towards a final value that is O(n^2) with relation to the string's length.
Let's consider the following simple case:
stringArray = "abc";
and see what happens in the two loops:
i = 1; j = 1; counter = 0;
i = 2; j = 1; counter = 1;
i = 2; j = 2; counter = 2;
i = 3; j = 1; counter = 3; // Undefined behaviour since stringArray[counter]
// is out of bounds
and so on (however, once you hit undefined behaviour, all bets are off and your program is free to do whatever it wants).