Increase a variable number by 1 - c

I have code in which I have a large number of characters all declared as being 1 higher than the other.
e.g. m1, m2, m3...
is there any way to increase the number I'm searching for by 1 in a for loop?
I have a long string of letters that I need to check to see if any of them match to the individual, but I cannot use strings due to situational limitations.
a1 is the particular character I'm looking for, m1 is the first in a long string of characters I am having to store as individuals
My attempt that wouldn't run:
for (a1 != m["%d"], &check, check++)
Unfortunately due to the limits of my application I can only use stdio.h and stdlib.h in my solution. Any help would be greatly appreciated

Variable names are used by the compiler, but are not part of the generated executable and therefore not accessible at runtime. You can simulate something like that by an array initialized with the addresses of the respective variables:
#include <stdio.h>
int main() {
int a0=0,a1=10,a2=15;
int *a[3] = { &a0, &a1, &a2 };
for (int i=0; i<3; i++) {
int val = *(a[i]);
printf("a%d:%d\n",i,val);
}
}
Output:
a0:0
a1:10
a2:15

Related

Infinite array index without any pointer in C

I want to get a variable from user and set it for my array size. But in C I cannot use variable for array size. Also I cannot use pointers and * signs for my project because i'm learning C and my teacher said it's forbidden.
Can someone tell me a way to take array size from user?
At last, I want to do this two projects:
1- Take n from user and get int numbers from user then reverse print entries.
2- Take n from user and get float numbers from user and calculate average.
The lone way is using array with variable size.
<3
EDIT (ANSWER THIS):
Let me tell full of story.
First Question of my teacher is:
Get entries (int) from user until user entered '-1', then type entry numbers from last to first. ( Teacher asked me to solve this project with recursive functions and with NO any array )
Second Question is:
Get n entries (float) from user and calculate their average. ( For this I must use arrays and functions or simple codes with NO any pointer )
Modern C has variable size arrays, as follows:
void example(int size)
{
int myArray[size];
//...
}
The size shouldn't be too large because the aray is allocated on the stack. If it is too large, the stack will overflow. Also, this aray only exists in the function (here: funtion example) and you cannot return it to a caller.
I think your task is to come up with a solution that does not use arrays.
For task 2 that is pretty simple. Just accumulate the input and divide by the number of inputs before printing. Like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float result = 0;
float f;
int n = 0;
printf("How many numbers?\n");
if (scanf("%d", &n) != 1) exit(1);
for (int i=0; i < n; ++i)
{
if (scanf("%f", &f) != 1) exit(1);
result += f;
}
result /= n;
printf("average is %f\n", result);
return 0;
}
The first task is a bit more complicated but can be solved using recursion. Here is an algorithm in pseudo code.
void foo(int n) // where n is the number of inputs remaining
{
if (n == 0) return; // no input remaining so just return
int input = getInput; // get next user input
foo(n - 1); // call recursive
print input; // print the input received above
}
and call it like
foo(5); // To get 5 inputs and print them in reverse order
I'll leave for OP to turn this pseudo code into real code.
You can actually use variable sized arrays. They are allowed when compiling with -std=c99
Otherwise, you can over-allocate the array with an arbitrary size (like an upper bound of your actual size) then use it the actual n provided by the user.
I don't know if this helps you, if not please provide more info and possibly what you have already achieved.

"No Output" result in C?

I was doing a programming question and one of the sample output is 64197148392731290. My code for that question is correct as it is giving me the right answers for other test cases (output for those test cases are in single digit).
I understand that there will be too many iterations for the test case which has 64197148392731290 as output. So what should I do to get correct answer for that test case too.
Here is the code :
#include<stdio.h>
#include<string.h>
int main() {
int test_case;long long int i, j, count, n, k, k1;
scanf("%d", &test_case);
while(test_case--) {
scanf("%lld%lld", &n, &k);
char a[n];
count=0;
k1=k;
scanf("%s", a);
while(k1--) {
strcat(a,a);
}
for(i=0;i<(n*k);i++) {
if(a[i]=='a') {
for(j=(i+1);j<(n*k);j++) {
if(a[j]=='b') {
count++;
}
}
}
}
printf("%lld\n", count);
}
return 0;
}
Sample Input and Output :
Input:
3
4 2
abcb
7 1
aayzbaa
12 80123123
abzbabzbazab
Output:
6
2
64197148392731290
My task is to count the number of subsequences "ab" (not necessarily consecutive) in the new string. The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two integers N and K, denoting the length of the initial string S and the number of repetitions respectively.
The second line contains a string S. Its length is exactly N, and each of its characters is a lowercase English letter.
If you are trying to store input in "int" that wont work coz this number its out of range, change it to "long long int"
Well the previous answer was sure wrong. Thanks for the code.
Sorry don't have time for detailed study but preliminary analysis tells me that maybe the error is because you are trying to store a sting of length 2n in a[n]. It works for smaller values since when you declare
char a[n];
^
variable known at runtime
it actually allocates a large block so that any value of n within range is possible. For large values strcat(a,a) will probably fail.
Basically somewhere down the line the string becomes corrupt. Most probably that is because of strcat. I suggest remove strcat, do something else to a similar effect.

Code to change an array element changes a different variable

I'm quite puzzled by why my variable NumberOfArrays changes the second time through the for loop in my code. Can anyone help me out?
#include <stdio.h>
#include <cs50.h>
int main(int argc, string argv[])
{
//variable declarations
int NumberOfArrays = 0;
int arrayRack[0];
//Get number of arrays
printf("Key in the number of arrays you'd like to have\n");
NumberOfArrays = GetInt();
//Get number for each element in arrayRack[]
for(int i = 0; i < NumberOfArrays; i++)
{
printf("give me an int for the %i th array\n", i + 1);
arrayRack[i] = GetInt();
// *** on the second pass, my "NumberOfArrays" gets adjusted to my GetInt number here. Why?
}
//print out numbers stored in respective arrays
for(int j = 0; j < NumberOfArrays; j++)
{
printf("{%i}<-- number in %ith array\n", arrayRack[j], j + 1);
}
return 0;
}
Because you declared arrayRack as an empty array ([0]). Try int arrayRack[100]; or some other number, and make sure that NumberOfArrays is less than that number before you use it.
Explanation: (edit note that this may vary by compiler) your variables are most likely stored on the stack in nearby memory addresses. So arrayRack points somewhere close to NumberOfArrays in memory. C doesn't generally check if you've run off the end of an array, so accessing arrayRack[1] doesn't cause a compiler error in this situation. However, arrayRack[1] isn't part of your array, so accessing it actually accesses something else — in this situation, NumberOfArrays.
Edit gcc permits length-0 arrays but does not allocate space for them per this. However, length-0 arrays are prohibited by the C standard (e.g., see this, the answers to this, and this). Given the behaviour you've seen, it looks to me like the compiler is allocating one int's worth of space on the stack, pointing arrayRack to that space, and packing that space right next to NumberOfArrays. As a result, &(arrayRack[1]) == &NumberOfArrays. In any event, using variable-length arrays as suggested by #dasblinkenlight is a cleaner way to handle this situation.
In general, given int arrayRack[N];, you can only safely access arrayRack[0] through arrayRack[N-1].
You declared the array too early. Move the declaration to after the call of GetInt(), like this:
printf("Key in the number of arrays you'd like to have\n");
int NumberOfArrays = GetInt();
int arrayRack[NumberOfArrays];
Note: NumberOfArrays is not an ideal name for the variable, because it denotes the number of array elements, not the number of arrays; your code has only one array.

Is it possible to include loop counter in name of array when declaring it? (in C)

I have this loop which creates a certain number of array depending on a value input by the user. I want to include the counter of the array at the end of the array name such that it is: array1[], array2[], array3[] and so on, one for each iteration. Would this be possible? We have just started learning C now at university so I don't know much about it yet. I tried the following:
#include <stdio.h>
int main(void)
{
//Variables
int i, columns, column_size;
//Read input
printf("Input number of columns:\n");
scanf("%d", &columns)
//Loop to create arrays
for (i=1; i<=columns; i=i+step)
{
//Read column size
scanf("%d", &column_size);
//Create an array of given size for this column
int column+"i"+[column_size];
}
return 0;
}
I want to include the counter of the array at the end of the array name such that it is: array1[], array2[], array3[] and so on, one for each iteration
That is not possible. C is a compiled language, meaning that a program (the compiler) creates the program at one point in time and the program eats user-input at a different point in time.
Even the names of the "variables" might vanish after compilation, they are not needed to execute the program.
int a;
All this does is to tell the compiler that you, the programmer need 32bits of space to store something. If you want to store something there later on, you use the name "a":
a = 42;
The compiler calculates the offset to your current location in RAM and stores the "42" at that address. At runtime the used "names" are completely irrelevant, there is no lookup for the right place involved.
This is the difference to an "interpreted language" like Python.

Generating a 160bit string which is stored in an array

I'm trying to generate a random 160bit string which is supposed to be stored in a character array named str[20]. It's obvious that the array holds 20 characters. How can I change the 160bits into 20 characters/numbers? I'm trying to do this in C.. Any help is greatly appreciated as I've ran out of ideas and then helpdesk at my uni won't help me..
This looks like homwork, so I'll only give you the basics:
Your variable will look like:
char str[20];
Note that this array will hold bytes of data, not necessarily "characters" (letter, numbers and punctuation marks as we typically understand the word character").
Unless the assignement is about writing your own random generator, you may want to use C's runtime pseudo-random generator (in stdlib.h), and use two of its functions: srand() and rand(). srand() is used to "seed" the generator (either seed with same value to get repeatability, useful during debug, or with a variable number (typically related to the system time) to get truly random numbers. rand() is used to produce integral random values.
Because rand() produces a value between 0 and RAND_MAX (which is a "big" number), you may need to use modulo to get the right amount. for example
str[0] = char(rand() % 256); // or something like that.
rand() however will not produce a 20 bytes integer, so you'll need to get several rand values and fit them appropriately in the array. The most straight forward may be to call rand 20 times and store 1 byte each time, but it is also ok to store several bytes at once, using pointers into parts of str.
160 bits is 20 bytes, so can fit in 20 string characters.
If N is a number containing all your bits in a row, you can write a loop like this:
int i;
for (i=0; i<20; i++) {
str[i] = (char)(N & 0xFF);
N >>= 8;
}
Edit: C indeed has no datatype that can hold all your bits in a row. So you need to split up the loop in several subloops for each variable that contains a part of your bits.
If, on the other hand, you are generating one bit at a time on the fly, the code could look like this (assuming your random function is called "random()" and returns an int that is either 0 or 1)
int i, j, b;
for (i=0; i<20; i++)
{
b = 0;
for (j=0; j<8; j++)
{
b |= (random() & 1);
b <<= 1;
}
str[i] = (char)b;
}
a random printable string. If you don't care if it's printable or not, remove the call to min((int)' '). Note I use a null-terminator to make it a proper c-string, if you don't want this, simply remove the part that makes the last character null (and the part taht prints it -- that'll be looking for a null terminator.)
#include <stdlib.h>
int main()
{
char* str[20];
int i;
for (i = 0; i < 19; i++)
{
char[i] = min((int)' ', rand() % CHAR_MAX);
}
char[19] = '\0';
puts(str);
}

Resources