I would like to select an array with a variable in order to copy its values into another array.
I'm struggling with this line : xyz[i] = arr1[i];
I want to replace arr1 with the variable name
Something like I use in Bash : xyz[i] = ${name}[i];
Does anyone have any clues or solutions ?
Here's a simplified version of my code
#include <stdio.h>
int main() {
int arr1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int arr2[8] = {8, 7, 6, 5, 4, 3, 2, 1};
int xyz [8], i, num=8;
int loop;
char name[4];
printf("Array's name ? ");
scanf("%s", &name);
// Array's name ? arr1
for (i = 0; i < num; i++) {
xyz[i] = arr1[i];
}
for(loop = 0; loop < 8; loop++) {
printf("%d ", xyz[loop]);
}
// 1 2 3 4 5 6 7 8
return 0;
}
C doesn't provide this capability (after the source code has been compiled, variable names no longer exist as such). You'll need to use a pointer to do something like this, and you'll need to add logic to assign the right value to that pointer. For a couple of names, a simple if/else statement is good enough:
int *p = NULL; // p will point to the first element of arr1 or arr2 depending on the value of name
if ( strcmp( name, "arr1" ) == 0 )
p = arr1;
else if ( strcmp( name, "arr2" ) == 0 )
p = arr2;
else
fprintf( stderr, "%s is not a valid name\n", name );
if ( !p )
{
// handle bad entry
}
else
{
for ( i = 0; i < num; i++ )
xyz[i] = p[i];
}
In the general case (where you have more than just a few options), you'll want to build some kind of a map that associates a name with an address:
struct {
char *name;
int *arr;
} name_arr_map[] = {
{"arr1", arr1},
{"arr2", arr2},
...
};
int *p = NULL;
// get name
for ( i = 0; i < N; i++ ) // N entries in our map
{
if ( strcmp( name_arr_map[i].name, name ) == 0 )
{
p = name_arr_map[i].arr;
break;
}
}
if ( !p )
{
// handle bad entry
}
else
{
for ( i = 0; i < num; i++ )
xyz[i] = p[i];
}
For a few entries (a couple of dozen or so) a simple linear search like this is good enough. If you have more than that, you may want to use a more sophisticated structure like a hash table or a tree.
However, for this specific case...
When you find yourself creating multiple variables of the same type with the names thing1, thing2, etc., that's a real strong hint you want an array - in this case, a 2D array:
int arrs[2][8] = { { 1, 2, 3, 4, 5, 6, 7, 8 },
{ 8, 7, 6, 5, 4, 3, 2, 1 } };
In this case you don't need a name, just an index:
int idx = 0;
...
printf( "Which array do you want to use, 0 or 1? " );
scanf( "%d", &idx );
if ( idx < 0 || idx > 1 )
{
// handle bad entry
}
else
{
for ( i = 0; i < 8; i++ )
xyz[i] = arrs[idx][i];
}
C does not have the ability to do this. You can either manually do it with if/else statements or find some sort of hashmap implementation in c like this one in order to map from names to arrays. Note that C++ has a pre-installed hashmap implementation that you don't have to download.
Related
I have not been able to find examples that initialize two-dimension array at run-time.
This is code in perl; can anyone "translate" this code into C?
my #grid; # grid = 2D array
my $gr=0; # rows in grid
my $gc=0; # cols in grid
my #ct;
if( $ARGV[0] eq '5x5' ) {
$gr=5; $gc=5; # grid is all zeroes
#ct=(2,2,2,2,0);
}
if( $ARGV[0] eq '9x9' ) {
$gr=9; $gc=9; # grid is all zeroes
#ct=(2,3,4,2,3,5,3,5,3);
}
if( $ARGV[0] eq '6x10' ) {
$gr=6; $gc=10;
#grid = (
[0,8,0,0,0,9,3,5,6,7],
[6,0,0,5,0,7,0,0,1,0],
[5,0,2,0,4,1,0,0,0,0],
[0,0,0,0,2,0,0,0,0,1],
[0,0,0,1,0,0,0,0,0,0],
[1,5,0,4,2,6,8,0,0,0],
);
#ct=(14,41,15,29,26,33,32,27,32,21);
}
“Initialization” is just giving initial values to an object. To do this at run-time, you can do any of the following, among other possibilities:
Initialize in the definition, as shown in the question:
int myPoints[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
Initialize with individual assignments:
myPoints[0][0] = 1;
myPoints[0][1] = 2;
myPoints[0][2] = 3;
myPoints[1][0] = 4;
myPoints[1][1] = 5;
myPoints[1][2] = 6;
myPoints[2][0] = 7;
myPoints[2][1] = 8;
myPoints[2][2] = 9;
Initialize with code that computes values:
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
myPoints[i][j] = 3*i + j + 1;
Copy from a compound literal:
memcpy(myPoints, (const int [3][3]) { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} }, sizeof myPoints);
In the first case (initializing with the definition), if myPoints is a static object, the compiler is likely to store the values in the object file, to be loaded as part of program loading. If myPoints is an automatic object, it is likely to generate instructions to store values for the array. Technically, the C standard permits the compiler to do either of these for any of the examples above. Which is used is a matter of optimization and compiler implementation. So the distinction of initializing at “run-time” is largely irrelevant unless performance issues are important.
I am trying to sort numbers using the bubble sorting method. However, sometimes the output returns some incorrect answers.
Appreciate someone can help how to fix this issue. the C code and incorrect output as below
typedef struct
{
char pname[2];
int ptotime;
} data;
int main()
{
int totalwait = 0;
data name[] = {{'A', .ptotime = 4},
{'B', .ptotime = 6},
{'C', .ptotime = 3},
{'D', .ptotime = 7},
{'E', .ptotime = 2}};
printf("Process Name\t Process Time \n");
for (int j = 0; j < 5; j++)
{
printf("\t%s\t\t\t\t%d\n", name[j].pname, name[j].ptotime);
}
//Shortest job first (SJF) scheduling
printf("\nShortest job first (SJF) scheduling \n");
int swapped, temp;
while (1)
{
swapped = 0;
for (int x = 0; x < 5; x++)
{
if (name[x].ptotime >= name[x + 1].ptotime)
{
temp = name[x].ptotime;
name[x].ptotime = name[x + 1].ptotime;
name[x + 1].ptotime = temp;
swapped = 1;
char temp2[2];
strcpy(temp2, name[x].pname);
strcpy(name[x].pname, name[x + 1].pname);
stpcpy(name[x + 1].pname, temp2);
}
}
if (swapped == 0)
{
break;
}
}
printf("Process Name\t Process Time \n");
for (int j = 0; j < 5; j++)
{
printf("\t%s\t\t\t\t%d\n", name[j].pname, name[j].ptotime);
}
return 0;
}
Output
Process Name Process Time
A 4
B 6
C 3
D 7
E 2
Shortest job first (SJF) scheduling
Process Name Process Time
0
E 2
C 3
A 4
B 6
Expected output
Process Name Process Time
A 4
B 6
C 3
D 7
E 2
Shortest job first (SJF) scheduling
Process Name Process Time
E 2
C 3
A 4
B 6
D 7
For starters do not use magic numbers as 5. Use named constants.
The array name is initialized incorrectly. You are using character literals to initialize the data member pname of a character array type without enclosing character literals in braces.
data name[] = {{'A', .ptotime = 4},
^^^
//...
in this loop
for (int x = 0; x < 5; x++)
{
if (name[x].ptotime >= name[x + 1].ptotime)
^^^^^
//...
there is an access beyond the array. So the program has undefined behavior.
Use local variables as for example the variable swap in the shortest scope where they are used.
To swap elements of the array name there is no need to swap each data member of each element of the array. You can swap whole objects.
Here is a demonstrative program.
#include <stdio.h>
typedef struct
{
char pname[2];
int ptotime;
} data;
int main( void )
{
data name[] =
{
{ "A", .ptotime = 4 },
{ "B", .ptotime = 6 },
{ "C", .ptotime = 3 },
{ "D", .ptotime = 7 },
{ "E", .ptotime = 2 }
};
const size_t N = sizeof( name ) / sizeof( *name );
printf("Process Name\t Process Time \n");
for ( size_t i = 0; i < N; i++ )
{
printf( "\t%s\t\t\t\t%d\n", name[i].pname, name[i].ptotime );
}
putchar( '\n' );
//Shortest job first (SJF) scheduling
printf("\nShortest job first (SJF) scheduling \n");
for ( int swapped = 1; swapped; )
{
swapped = 0;
for ( int i = 1; i < N; i++ )
{
if ( name[i].ptotime < name[i-1].ptotime )
{
data tmp = name[i];
name[i] = name[i-1];
name[i-1] = tmp;
swapped = 1;
}
}
}
printf("Process Name\t Process Time \n");
for ( size_t i = 0; i < N; i++ )
{
printf( "\t%s\t\t\t\t%d\n", name[i].pname, name[i].ptotime );
}
return 0;
}
Its output is
Process Name Process Time
A 4
B 6
C 3
D 7
E 2
Shortest job first (SJF) scheduling
Process Name Process Time
E 2
C 3
A 4
B 6
D 7
Change:
for(int x = 0; x < 5; x++) {
into:
for(int x = 0; x < 4; x++) {
When x=4, the code compares name[4] with name[5], but name[5] is out of bounds (the only valid elements are name[0] ... name[4]).
There is a problem here:
for (int x = 0; x < 5; x++) {
if (name[x].ptotime >= name[x + 1].ptotime) {
the maximal value x can take is 4. But then name[x + 1] will access one element beyond the end of your array which has only 5 elements. Accessing an array out of bounds yields in undefined behaviour and all bets are off.
There may be more problems though.
In your swap cycle, this code snippet:
for(int x = 0; x < 5; x++)
In the last iteration you copy the values of name[4+1] to name[4] witch is to say you copy the values of the 6th element of your 5 element array, this is access out of bounds witch is undefined behavior.
Use
for(int x = 0; x < 4; x++)
This way the last cycle will be copying name[3+1] to name[3], 5th element to 4th element, witch is the expected behaviour.
Corrected code
I have an unsorted array, what is the best method to remove all the duplicates of an element if present?
e.g:
a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]
so after that operation the array should look like
a[1,5,2,6,8,9,10,3,4,11]
Check every element against every other element
The naive solution is to check every element against every other element. This is wasteful and yields an O(n2) solution, even if you only go "forward".
Sort then remove duplicates
A better solution is sort the array and then check each element to the one next to it to find duplicates. Choose an efficient sort and this is O(n log n).
The disadvantage with the sort-based solution is order is not maintained. An extra step can take care of this however. Put all entries (in the unique sorted array) into a hashtable, which has O(1) access. Then iterate over the original array. For each element, check if it is in the hash table. If it is, add it to the result and delete it from the hash table. You will end up with a resultant array that has the order of the original with each element being in the same position as its first occurrence.
Linear sorts of integers
If you're dealing with integers of some fixed range you can do even better by using a radix sort. If you assume the numbers are all in the range of 0 to 1,000,000 for example, you can allocate a bit vector of some 1,000,001. For each element in the original array, you set the corresponding bit based on its value (eg a value of 13 results in setting the 14th bit). Then traverse the original array, check if it is in the bit vector. If it is, add it to the result array and clear that bit from the bit vector. This is O(n) and trades space for time.
Hash table solution
Which leads us to the best solution of all: the sort is actually a distraction, though useful. Create a hashtable with O(1) access. Traverse the original list. If it is not in the hashtable already, add it to the result array and add it to the hash table. If it is in the hash table, ignore it.
This is by far the best solution. So why the rest? Because problems like this are about adapting knowledge you have (or should have) to problems and refining them based on the assumptions you make into a solution. Evolving a solution and understanding the thinking behind it is far more useful than regurgitating a solution.
Also, hash tables are not always available. Take an embedded system or something where space is VERY limited. You can implement an quick sort in a handful of opcodes, far fewer than any hash table could be.
This can be done in amortized O(n) using a hashtable-based set.
Psuedo-code:
s := new HashSet
c := 0
for each el in a
Add el to s.
If el was not already in s, move (copy) el c positions left.
If it was in s, increment c.
If you don't need to keep the original object you can loop it and create a new array of unique values. In C# use a List to get access to the required functionality. It's not the most attractive or intelligent solution, but it works.
int[] numbers = new int[] {1,2,3,4,5,1,2,2,2,3,4,5,5,5,5,4,3,2,3,4,5};
List<int> unique = new List<int>();
foreach (int i in numbers)
if (!unique.Contains(i))
unique.Add(i);
unique.Sort();
numbers = unique.ToArray();
Treat numbers as keys. for each elem in array:
if hash(elem) == 1 //duplicate
ignore it
next
else
hash(elem) = 1
add this to resulting array
end
If you know about the data like the range of numbers and if it is finite, then you can initialize that big array with ZERO's.array flag[N] //N is the max number in the array
for each elem in input array:
if flag[elem - 1] == 0
flag[elem - 1] = 1
add it to resulatant array
else
discard it //duplicate
end
indexOutput = 1;
outputArray[0] = arrayInt[0];
int j;
for (int i = 1; i < arrayInt.length; i++) {
j = 0;
while ((outputArray[j] != arrayInt[i]) && j < indexOutput) {
j++;
}
if(j == indexOutput){
outputArray[indexOutput] = arrayInt[i];
indexOutput++;
}
}
Use a Set implementation.
HashSet,TreeSet or LinkedHashSet if its Java.
This is a code segment i created in C++, Try out it
#include <iostream>
using namespace std;
int main()
{
cout << " Delete the duplicate" << endl;
int numberOfLoop = 10;
int loopCount =0;
int indexOfLargeNumber = 0;
int largeValue = 0;
int indexOutput = 1;
//Array to hold the numbers
int arrayInt[10] = {};
int outputArray [10] = {};
// Loop for reading the numbers from the user input
while(loopCount < numberOfLoop){
cout << "Please enter one Integer number" << endl;
cin >> arrayInt[loopCount];
loopCount = loopCount + 1;
}
outputArray[0] = arrayInt[0];
int j;
for (int i = 1; i < numberOfLoop; i++) {
j = 0;
while ((outputArray[j] != arrayInt[i]) && j < indexOutput) {
j++;
}
if(j == indexOutput){
outputArray[indexOutput] = arrayInt[i];
indexOutput++;
}
}
cout << "Printing the Non duplicate array"<< endl;
//Reset the loop count
loopCount =0;
while(loopCount < numberOfLoop){
if(outputArray[loopCount] != 0){
cout << outputArray[loopCount] << endl;
}
loopCount = loopCount + 1;
}
return 0;
}
My solution(O(N)) does not use additional memory, but array must been sorted(my class using insertion sort algorithm, but it doesn't matter.):
public class MyArray
{
//data arr
private int[] _arr;
//field length of my arr
private int _leght;
//counter of duplicate
private int countOfDup = 0;
//property length of my arr
public int Length
{
get
{
return _leght;
}
}
//constructor
public MyArray(int n)
{
_arr = new int[n];
_leght = 0;
}
// put element into array
public void Insert(int value)
{
_arr[_leght] = value;
_leght++;
}
//Display array
public void Display()
{
for (int i = 0; i < _leght; i++) Console.Out.Write(_arr[i] + " ");
}
//Insertion sort for sorting array
public void InsertSort()
{
int t, j;
for (int i = 1; i < _leght; i++)
{
t = _arr[i];
for (j = i; j > 0; )
{
if (_arr[j - 1] >= t)
{
_arr[j] = _arr[j - 1];
j--;
}
else break;
}
_arr[j] = t;
}
}
private void _markDuplicate()
{
//mark duplicate Int32.MinValue
for (int i = 0; i < _leght - 1; i++)
{
if (_arr[i] == _arr[i + 1])
{
countOfDup++;
_arr[i] = Int32.MinValue;
}
}
}
//remove duplicates O(N) ~ O(2N) ~ O(N + N)
public void RemoveDups()
{
_markDuplicate();
if (countOfDup == 0) return; //no duplicate
int temp = 0;
for (int i = 0; i < _leght; i++)
{
// if duplicate remember and continue
if (_arr[i] == Int32.MinValue) continue;
else //else need move
{
if (temp != i) _arr[temp] = _arr[i];
temp++;
}
}
_leght -= countOfDup;
}
}
And Main
static void Main(string[] args)
{
Random r = new Random(DateTime.Now.Millisecond);
int i = 11;
MyArray a = new MyArray(i);
for (int j = 0; j < i; j++)
{
a.Insert(r.Next(i - 1));
}
a.Display();
Console.Out.WriteLine();
a.InsertSort();
a.Display();
Console.Out.WriteLine();
a.RemoveDups();
a.Display();
Console.ReadKey();
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class testing {
public static void main(String[] args) {
EligibleOffer efg = new EligibleOffer();
efg.setCode("1234");
efg.setName("hey");
EligibleOffer efg1 = new EligibleOffer();
efg1.setCode("1234");
efg1.setName("hey1");
EligibleOffer efg2 = new EligibleOffer();
efg2.setCode("1235");
efg2.setName("hey");
EligibleOffer efg3 = new EligibleOffer();
efg3.setCode("1235");
efg3.setName("hey");
EligibleOffer[] eligibleOffer = { efg, efg1,efg2 ,efg3};
removeDupliacte(eligibleOffer);
}
public static EligibleOffer[] removeDupliacte(EligibleOffer[] array) {
List list = Arrays.asList(array);
List list1 = new ArrayList();
int len = list.size();
for (int i = 0; i <= len-1; i++) {
boolean isDupliacte = false;
EligibleOffer eOfr = (EligibleOffer) list.get(i);
String value = eOfr.getCode().concat(eOfr.getName());
if (list1.isEmpty()) {
list1.add(list.get(i));
continue;
}
int len1 = list1.size();
for (int j = 0; j <= len1-1; j++) {
EligibleOffer eOfr1 = (EligibleOffer) list1.get(j);
String value1 = eOfr1.getCode().concat(eOfr1.getName());
if (value.equals(value1)) {
isDupliacte = true;
break;
}
System.out.println(value+"\t"+value1);
}
if (!isDupliacte) {
list1.add(eOfr);
}
}
System.out.println(list1);
EligibleOffer[] eligibleOffer = new EligibleOffer[list1.size()];
list1.toArray(eligibleOffer);
return eligibleOffer;
}
}
Time O(n) space O(n)
#include <iostream>
#include<limits.h>
using namespace std;
void fun(int arr[],int size){
int count=0;
int has[100]={0};
for(int i=0;i<size;i++){
if(!has[arr[i]]){
arr[count++]=arr[i];
has[arr[i]]=1;
}
}
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
int main()
{
//cout << "Hello World!" << endl;
int arr[]={4, 8, 4, 1, 1, 2, 9};
int size=sizeof(arr)/sizeof(arr[0]);
fun(arr,size);
return 0;
}
public class RemoveDuplicateArray {
public static void main(String[] args) {
int arr[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 9 };
int size = arr.length;
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (arr[i] == arr[j]) {
while (j < (size) - 1) {
arr[j] = arr[j + 1];
j++;
}
size--;
}
}
}
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
}
}
output - 1 2 3 4 5 6 7 9
You can use the "in" and "not in" syntax in python which makes it pretty straight forward.
The complexity is higher than the hashing approach though since a "not in" is equivalent to a linear traversal to find out whether that entry exists or not.
li = map(int, raw_input().split(","))
a = []
for i in li:
if i not in a:
a.append(i)
print a
I am doing it in Python.
array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5,10,10,8,7,7,9,10]
array1.sort() # sorting is must
print(array1)
current = NONE
count = 0
# overwriting the numbers at the frontal part of the array
for item in array1:
if item != current:
array1[count] = item
count +=1
current=item
print(array1)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10, 10]
print(array1[:count])#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The most Efficient method is :
array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5,10,10,8,7,7,9,10]
array1.sort()
print(array1)
print([*dict.fromkeys(array1)])#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#OR#
aa = list(dict.fromkeys(array1))
print( aa)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
use an dictionary array and add each items as key
if an item was duplicated , dictionary avoid to add it!
it's the best solution
int[] numbers = new int[] {1,2,3,4,5,1,2,2,2,3,4,5,5,5,5,4,3,2,3,4,5};
IDictionary<int, string> newArray = new Dictionary<int, string>();
for (int i = 0; i < numbers.count() ; i++)
{
newArray .Add(numbers[i] , "");
}
C bothers me with its handling of strings. I have a pseudocode like this in my mind:
char *data[20];
char *tmp; int i,j;
for(i=0;i<20;i++) {
tmp = data[i];
for(j=1;j<20;j++)
{
if(strcmp(tmp,data[j]))
//then except the uniqueness, store them in elsewhere
}
}
But when i coded this the results were bad.(I handled all the memory stuff,little things etc.) The problem is in the second loop obviously :D. But i cannot think any solution. How do i find unique strings in an array.
Example input : abc def abe abc def deg entered
unique ones : abc def abe deg should be found.
You could use qsort to force the duplicates next to each other. Once sorted, you only need to compare adjacent entries to find duplicates. The result is O(N log N) rather than (I think) O(N^2).
Here is the 15 minute lunchtime version with no error checking:
typedef struct {
int origpos;
char *value;
} SORT;
int qcmp(const void *x, const void *y) {
int res = strcmp( ((SORT*)x)->value, ((SORT*)y)->value );
if ( res != 0 )
return res;
else
// they are equal - use original position as tie breaker
return ( ((SORT*)x)->origpos - ((SORT*)y)->origpos );
}
int main( int argc, char* argv[] )
{
SORT *sorted;
char **orig;
int i;
int num = argc - 1;
orig = malloc( sizeof( char* ) * ( num ));
sorted = malloc( sizeof( SORT ) * ( num ));
for ( i = 0; i < num; i++ ) {
orig[i] = argv[i + 1];
sorted[i].value = argv[i + 1];
sorted[i].origpos = i;
}
qsort( sorted, num, sizeof( SORT ), qcmp );
// remove the dups (sorting left relative position same for dups)
for ( i = 0; i < num - 1; i++ ) {
if ( !strcmp( sorted[i].value, sorted[i+1].value ))
// clear the duplicate entry however you see fit
orig[sorted[i+1].origpos] = NULL; // or free it if dynamic mem
}
// print them without dups in original order
for ( i = 0; i < num; i++ )
if ( orig[i] )
printf( "%s ", orig[i] );
free( orig );
free( sorted );
}
char *data[20];
int i, j, n, unique[20];
n = 0;
for (i = 0; i < 20; ++i)
{
for (j = 0; j < n; ++j)
{
if (!strcmp(data[i], data[unique[j]]))
break;
}
if (j == n)
unique[n++] = i;
}
The indexes of the first occurrence of each unique string should be in unique[0..n-1] if I did that right.
Why are you starting second loop from 1?
You should start it from
i+1. i.e.
for(j=i+1;j<20;j++)
Like if the list is
abc
def
abc
abc
lop
then
when i==4
tmp="lop"
but then the second loop starts which is from 1 to 19. This means it will get a value of 4 too at one stage, and then
data[4], which is "lop", will be same as tmp. So although "lop" is unique but it will be flagged as repeated.
Hope it was helpful.
Think a bit more about your problem -- what you really want to do is look at the PREVIOUS strings to see if you've already seen it. So, for each string n, compare it to strings 0 through n-1.
print element 0 (it is unique)
for i = 1 to n
unique = 1
for j = 0 to i-1 (compare this element to the ones preceding it)
if element[i] == element[j]
unique = 0
break from loop
if unique, print element i
Might it be that your test is if (strcmp (this, that)) which will succeed if the two are different? !strcmp is probably what you want there.
In the method I've tried this:
int 1, 2, 4, 5, 6, 7;
char 3;
char display[10];
scanf("%d%d%c%d%d%d%d", &1, &2, &3, &4, &5, &6, &7);
display = {1, 2, 3, 4, 5, 6, 7};
But I get errors everywhere and it doesn't work.
Presumably in that order?
Walk the string a char at a time and use isdigit() isalpha() to check each one.
Or just do:
char test[] = "12B3456";
if ( (strlen(test)>6) &&
isdigit(test[0]) &&
isdigit(test[1]) &&
isalpha(test[2]) &&
isdigit(test[3]) &&
isdigit(test[4]) &&
isdigit(test[5]) &&
isdigit(test[6]) )
{
// valid
}
First of all, in C, variable names can't start with a number, or be a number for that matter. So the declaration of int 1,2,3,4,5,6,7 will not compile, as well as char 3;
Here's a sample of how you could do it assuming the input is a null terminated string:
int matches(char *input){
int i;
/* This array contains 1 in places where a digit is expected */
char expected_digits[] = {1,1,0,1,1,1,1};
for(i = 0 ; input[i] != 0 && i < 7; i++){
if(expected_digits[i] == 1){
if(!isdigit(input[i])){
return 0;
}
}
else{
if(!isalpha(input[i]))
{
return 0;
}
}
}
if(i == 7) {
/* We reached the end of the input string and all its places matched */
return 1;
}
else{
return 0;
}
}
Not the best piece of code, but should do the trick. And it should compile with a C compiler.