Tuesday 25 June 2013

Input The Marks Obtained In 5 Subjects

As the name suggests, this program accepts the values of the marks obtained by a student and displays the total percentage of marks obtained and the division the student is placed in.

I wrote the a while back based on a question in Let Us C (4th) edition. Anyway, this program is memorable to me because after writing this I saw that I could change the background colour of the entire screen.
This was before I could use the gotoxy function, so it uses a lot of cls to rewrite the entire screen.

We just set the text and background colour and then cls the screen. If we do this once, everything else appears in the colours you set.


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <windows.h>

#define TRUE 1
#define FALSE !TRUE

int sub1,sub2,sub3,sub4,sub5,state,tfl,tfl2,ranks;
float pcm,total;
char c,d;

void SetColorAndBackground(int ForgC, int BackC);
float calculation(void);
int division(void);
main()
{

    state=FALSE;

while(!state)
{
    SetColorAndBackground(7,9);
    system("cls");
    tfl=12,tfl2=12;
        printf("Enter the marks obtained by the student\n");
        printf("English\t\tScience\t\tMath\tSocial Sc.\tGFC\n");
        scanf("%i",&sub1);
        system("cls");

        printf("Enter the marks obtained by the student\n");
        printf("English\t\tScience\t\tMath\tSocial Sc.\tGFC\n");
        printf("%i\t\t",sub1);
        scanf("%i",&sub2);
        system("cls");

        printf("Enter the marks obtained by the student\n");
        printf("English\t\tScience\t\tMath\tSocial Sc.\tGFC\n");
        printf("%i\t\t%i\t\t",sub1,sub2);
        scanf("%i",&sub3);
        system("cls");

        printf("Enter the marks obtained by the student\n");
        printf("English\t\tScience\t\tMath\tSocial Sc.\tGFC\n");
        printf("%i\t\t%i\t\t%i\t",sub1,sub2,sub3);
        scanf("%i",&sub4);
        system("cls");

        printf("Enter the marks obtained by the student\n");
        printf("English\t\tScience\t\tMath\tSocial Sc.\tGFC\n");
        printf("%i\t\t%i\t\t%i\t%i\t\t",sub1,sub2,sub3,sub4);
        scanf("%i",&sub5);
        system("cls");

        printf("Please Look At The Marks\n");
        printf("English\t\tScience\t\tMath\tSocial Sc.\tGFC\n");
        printf("%i\t\t%i\t\t%i\t%i\t\t%i",sub1,sub2,sub3,sub4,sub5);
        printf("\n\n\n\t\tAre The marks correct?(Y/N):");


        while(tfl==12)
        {
            c=toupper(getch());
            if(c=='Y')
            {
                system("cls");
                printf("Percentage of marks obtained is %.2f\n",calculation());
                ranks=division();
                if(ranks==1)
                {
                    printf("First Division.\n");
                }
                else if(ranks==2)
                {
                    printf("Second Division.\n");
                }
                else if(ranks==3)
                {
                    printf("Third Division.\n");
                }
                else if (ranks==5)
                {
                    printf("The marks are out of range for a division.\n");
                }
                else
                {
                    printf("Failed.\n");
                }
                printf("\n\nCalculate another?(Y/N): ");
                while(tfl2==12)
                {
                    d=toupper(getch());
                    if(d=='Y')
                    {
                        system("cls");
                        tfl=10;
                        tfl2=10;
                        break;
                    }
                    if(d=='N')
                    {
                        SetColorAndBackground(7,0);
                        system("cls");
                        exit(0);
                    }

                }
            }
            if(c=='N')
            {
                system("cls");
                break;
            }

        }
}

}

float calculation(void)
{
    total=sub1+sub2+sub3+sub4+sub5;
    pcm=total/5;
    return(pcm);
}

int division(void)
{
    int div;
    div=calculation();
    if(div>59 && div<101)
    {
        return(1);
    }
    else if(div>49 && div<60)
    {
        return(2);
    }
    else if(div>39 && div<50)
    {
        return(3);
    }
    else if(div>100 || div<1)
    {
        return(5);
    }
    else
    {
        return(4);
    }
}

void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor=((BackC&0x0F)<<4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),wColor);
     return;
}

Monday 24 June 2013

Pyramid Spaces. Let Us C Chapter 3, exercise E-e


Let Us C is anything but short on exercises.
Ch-3 Exercise E-E
Write a program to produce the following output
A B C D E F G F E D C B A
A B C D E F     F E D C B A
A B C D E           E D C B A
A B C D                D C B A
A B C                      C B A
A B                            B A
A                                  A

I tried writing this program but it was too hard for me. I cannot think in nested loops. I googled it and found a very short program that achieves the same purpose with a very short program HERE. If you decide to check out the link, scroll down to answer 1 which is the one I am talking about. Just remove the fourth line from that code clrscr(); which clears the screen in Turbo C.
But we are using Code::Blocks, gnu gcc default, so just remove it or replace it with system("cls") (in which case you have to #include <stdlib.h> into your code - but only if you use system("cls")); it executes the DOS 'cls' (clear screen) command.
Also the code in the link is missing #include <stdio.h> and #include <conio.h>. 
I tried figuring out the logic in the code, but got nowhere. So I wrote it from scratch as best as I could. It's much longer, but it does what it should. By the way, I was saving my code with the .cpp extension for quite a while. Now since I save them with a .c extension, it returns values (2 in case of this code) and C::B tells me
Process terminated with status 2 (0 minutes, 2 seconds)
So I am trying to get into the habit of saying return 0; at the end of my code.
Here is a sample output:


Here is the actual code:



#include <stdio.h>

main()
{
    int a,b,c,d,e,f,g,line=1,alp=65;

    for(a=0;a<7;a++)
    {
        printf("%c ",alp);
        alp=alp+1;
        for(b=0;b<1;b++)
        {
            if(line>6)
            {
                printf("  ");
                alp=alp+1;
            }
            else
            {
                printf("%c ",alp);
                alp=alp+1;
            }
            for(c=0;c<1;c++)
            {
                if(line>5)
                {
                    printf("  ");
                    alp=alp+1;
                }
                else
                {
                    printf("%c ",alp);
                    alp=alp+1;
                }
                for(d=0;d<1;d++)
                {
                    if(line>4)
                    {
                        printf("  ");
                        alp=alp+1;
                    }
                    else
                    {
                        printf("%c ",alp);
                        alp=alp+1;
                    }
                    for(e=0;e<1;e++)
                    {
                        if(line>3)
                        {
                            printf("  ");
                            alp=alp+1;
                        }
                        else
                        {
                            printf("%c ",alp);
                            alp=alp+1;
                        }
                        for(f=0;f<1;f++)
                        {
                            if(line>2)
                                {
                                    printf("  ");
                                    alp=alp+1;
                                }
                                else
                                {
                                    printf("%c ",alp);
                                    alp=alp+1;
                                }
                            for(g=0;g<1;g++)
                            {
                                if(line>1)
                                {
                                    printf("  ");
                                    alp=alp-1;
                                }
                                else
                                {
                                    printf("%c ",alp);
                                    alp=alp-1;
                                }
                            }
                            if(line>2)
                                {
                                    printf("  ");
                                    alp=alp-1;
                                }
                                else
                                {
                                    printf("%c ",alp);
                                    alp=alp-1;
                                }
                        }
                        if(line>3)
                        {
                            printf("  ");
                            alp=alp-1;
                        }
                        else
                        {
                            printf("%c ",alp);
                            alp=alp-1;
                        }
                    }
                    if(line>4)
                        {
                            printf("  ");
                            alp=alp-1;
                        }
                        else
                        {
                            printf("%c ",alp);
                            alp=alp-1;
                        }
                }
                if(line>5)
                        {
                            printf("  ");
                            alp=alp-1;
                        }
                        else
                        {
                            printf("%c ",alp);
                            alp=alp-1;
                        }
            }
            if(line>6)
                        {
                            printf("  ");
                            alp=alp-1;
                        }
                        else
                        {
                            printf("%c ",alp);
                            alp=alp-1;
                        }
        }
        printf("%c\n",alp);
        alp=65;
        line++;
    }
    return 0;
}


Wednesday 19 June 2013

Program That Reads And Prints The Source File

Save this file as Test.c
Compile it and it should output the source code itself. It does nothing clever, just reads test.c and prints it.


#include <stdio.h>

main()

{
    FILE *m;
    char c;

    m=fopen("test.c","r");


    while(1)

    {
        c=getc(m);
        if(c==EOF)
        {
            break;
        }
        printf("%c",c);
    }
    printf("\n");
    fclose(m);
    return 0;
}

The #include <stdio.h> does not show in my output because the screen does not fit it in. It scrolls up. Remove the 3 blank lines in the program code and it should show.

Sunday 16 June 2013

Write A Program That Converts A String...

Another exercise attempt. I almost have a headache after writing this. I'm going out for a drink. When I saw the question, the first thing that came to my mind was a switch case (I'm assuming the author does not want us to use the atoi ASCII to Integer function), so I wrote it using it switch case although there probably are other ways to do this, I can't be bothered now. To increase the number the user can input, I used unsigned integers. If you want the program to accept only smaller numbers:
1) Change unsigned to int if needed
    If you do this also replace %u with a %i in:
    printf("Here is your input as an (Unsigned) integer: %i",integer);
2) Change prompt the "upto 9 digits" part.
3) if(str_length<=9) replace 9 with desired limit.
4) Delete or comment out the code starting from case 9: to right before case:desired limit.

Let Us C, Chapter 9, Exercise D-d:
Write a program that converts a string like "124" to an integer 124.

#include <stdio.h>
#include <strings.h>

main()
{
    unsigned str_length,temp,integer=0;
    int i=0;
    char input[9];

    printf("Enter a string of numbers (upto 9 digits): ");
    scanf(" %s",input);

    str_length=strlen(input);
    if(str_length<=9)
    {
        switch(str_length)
        {
        case 9:     //if it is a 9 digit number
            /*Without the -48, temp will be assigned the ASCII value, 48 for 0, 49 for 1, 50 for 2 etc.
            so we subtract 48 to cut it down to the correct value*/
            temp=input[i]-48;
            integer=temp*100000000;
            i++;

        case 8:
            temp=input[i]-48;
            integer=temp*10000000+integer;
            i++;

        case 7:
            temp=input[i]-48;
            integer=temp*1000000+integer;
            i++;

        case 6:
            temp=input[i]-48;
            integer=temp*100000+integer;
            i++;

        case 5:
            temp=input[i]-48;
            integer=(temp*10000)+integer;
            i++;

        case 4:
            temp=input[i]-48;
            integer=(temp*1000)+integer;
            i++;

        case 3:
            temp=input[i]-48;
            integer=(temp*100)+integer;
            i++;

        case 2:
            temp=input[i]-48;
            integer=(temp*10)+integer;
            i++;

        case 1:
            temp=input[i]-48;
            integer=temp+integer;
            i++;
        }
        printf("Here is your input as an (Unsigned) integer: %u",integer);
    }

    else
    {
        printf("Invalid Input!");
    }

}

Saturday 15 June 2013

A Program That Extracts Part Of A Given String

I decided to do one of the exercises at the end of Chapter 9 of Let Us C.

D-c:
Write a program that extracts part of the given string from the specified position. For example, if the string is "Working with strings is fun", then if from position 4, 4 characters are to be extracted then the program should return string as "king". If the number of characters to be extracted is 0 then the program should extract entire string from the specified position.

I tried to do it with an array of pointers to strings as opposed to a normal array, although I don't think I needed to.
Sample execution:

Here is my attempt:

#include <stdio.h>
#include <strings.h>
#include <stdlib.h>

main()
{
    char *arr1,str[100],*temp;
    int start,ends,len,i;

    printf("Enter a length of string: \n");
    gets(str);
    len=strlen(str);
    temp=(char *)malloc(len+1);
    strcpy(temp,str);
    arr1=temp;

    printf("Where will the extraction begin from (Less than %i): \n",len);
    scanf("%i",&start);
    if(start<len && start>0)
    {
        start=start-1;

        printf("How many characters do you want to extract?(less than or equal to %i)?\n",len-start);
        scanf("%i",&ends);
        if(ends<=len && ends>0)
        {
            arr1[start+ends]='\0';
            arr1=arr1+start;

            printf("%s",arr1);
        }

        else if(ends==0)
        {
            i=start;
            while(arr1[i]!='\0')
            {
                printf("%c",arr1[i]);
                i++;
            }
        }

        else
        {
            printf("Invalid Input.");
        }
    }
    else
    {
        printf("Invalid Input!");
    }
}


Guess The Random Number Game

One of the first programs i wrote and liked.

The computer generates a random number using the system clock to seed itself. Then asks you to guess it.
You get six tries. Every time you enter a guess it tells you if the number was too high, too low or if it is correct.

This was based on a program for the same game in C For Dummies. The way I try to solve this is enter half of the number range I have. First 50 (middle of 1 to 100), if it is too low enter 75 (Middle between 50 and 100). If 50 is too high enter 25 (Middle between 1 and 50), etc.

Here's the program:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int number;
void time_seed(void);
int random(int range);
main()
{
time_seed();
number=random(100)+1;
system("cls");
printf("I'm thinking of a number between and including 1 to 100.\nCan you guess the number in 6 tries?\n");
int a;
for(a=0;a<6;a++)
{
char b[20];
int input;
printf("Enter guess number %i: ",a+1);
input=atoi(gets(b));

if(input<1)
{
printf("Between and including 1 and 100 please!\n");
}
else if(input>100)
{
printf("Between and including 1 and 100 please!\n");
}
if(input<number)
{
printf("Too low!\n");
}
else if(input>number)
{
printf("Too high!\n");
}
else if(input==number)
{
printf("That's Correct! Cookie for you!");
system("pause >nul");
exit(0);
}

}
printf("Sorry! The number was %i! Better luck next time.",number);
system("pause >nul");
}

int random(int range)
{
int y;
y=rand()%range;
return(y);
}

void time_seed(void)
{
srand((unsigned)time(NULL));
}

Friday 14 June 2013

Array Of Pointers To Strings

Well, I'm still studying pointers. At chapter 9 of Let Us C, there are a couple of programs that demonstrate switching 2 names in an array. Say the following names are entered/stored in an array:

Akshay Parag Raman Srinivas Gopal Rajesh

once the programs are run, the result should be this:

Akshay Parag Srinivas Raman Gopal Rajesh

The third and fourth names are interchanged.

The first program in the book demonstrates switching the names using a normal character array, the second demonstrates the same using an Array Of Pointers To Strings.

The book declares the name within the program but I wrote them using the scanf() function so that I could enter the names that I wanted, I did this for both the programs. As I read on the book mentions that we need to use a malloc() function to scanf() input from the keyboard when using an array of pointers to strings.

But I was already getting input in both the cases without the malloc() function, I don't even know what malloc() does. So I removed the .cpp extension from my file and saved it as .c, you know just in case it has something to do with C++ treating scanf() differently. Nope, still works. All I needed was an ampersand sign before the array name in the scanf() function.

I'm probably missing something, but why knock it when it works eh? =]

Here is the program:


#include <stdio.h>

main()
{
    char *name[6][10],*t;
    int i;

    puts("Enter 6 Names:");
    for(i=0;i<6;i++)
    {
        scanf("%s",&name[i]);
    }
    for(i=0;i<6;i++)
    {
        printf("%s ",&name[i]);
    }

        t=name[2][0];
        name[2][0]=name[3][0];
        name[3][0]=t;

    printf("\n");

    for(i=0;i<6;i++)
    {
        printf("%s ",&name[i]);
    }
}


Now on to learning malloc() for me.
_______________________________________________________________________
EDIT:
Okay, I was wrong. Just as I suspected. The whole point (pun-ha) of using pointers to arrays of strings is to save memory space. Since I already declared that there would be 6 strings each upto 10 characters long
char *name[6][10]
It is pointless (pun again-ha) to use pointers to arrays if I'm going to use the same amount of space no matter what length of strings I enter. Now if I do not declare the length of the strings, the statement only seems to allocate 4 bytes of memory for each string, so that's 3 characters and one null character. Allow me to demonstrate:

#include <stdio.h>

main()
{
    char *items[6];
    int i;

    puts("Enter the name of the items: ");
    for(i=0;i<6;i++)
    {
        scanf(" %s",&items[i]);
    }

    for(i=0;i<6;i++)
    {
        printf("%s ",&items[i]);
    }

    printf("\n");
    for(i=0;i<6;i++)
    {
        printf("%i ",&items[i]);
    }
}

Sample Input/Output:
This is what happens when you input acceptable characters:
Notice that the memory blocks are 4 spaces apart, so it takes in the 3 characters I input and stores the '\0' (NULL) character which tells the program that it is the end of the string in the last space. All good.
But when you input more characters than 3:
There is no space for the NULL character, so it just goes on to the next block, and the next until it encounters the NULL character for fig. That is why the output stops at fig. Except for the last Peach which sees no null value and we see that weird Clubs ASCII character at the end.

So technically, the computer does not know how many characters you will stick in there, so it gives you 4 bytes, at least thats what I think is happening.

So we need to use malloc() (Memory Allocate?) as soon as the user inputs the string to count the length and allocate the memory length for it.

LESSON: If the book says you can't do it, but you find that you can, find out why you can, because the book is right.


Thursday 13 June 2013

Write A Program To Reverse The Number

Another exercise in Let Us C (Chapter 1, Exercise I-h) asks this:

If a five digit number is input through the keyboard, write a program to reverse the number.

I saw this when I first went through the chapter, but skipped it since I didn't think I could do it (I am very bad at Math see?).

Anyway, I went back to it, and here's what I came up with. I wrote a program that does this reversal without using the modulus operator but I wanted to do it using modulus (%), so that it would also solve exercise I-g (If a five digit number is input through the keyboard, write a program to calculate the sum of its digits. (Hint: Use the modulus operator '%')).

The one that does not use modulus is HERE

What the modulus operator does is it returns the remainder when a number is divided by another.

Example: x=8%3 (x is equal to the REMAINDER of eight divided by 3), the remainder is two, so now x=2.

or: x=5%2 (x is equal to the REMAINDER of five divided by two), the remainder is one, so now x=1

The logic I used is this:

A five digit number is in the 10,000th unit. So if we divide the 5 digit number by 10,000 (the smallest 5 digit number), we get all but the 10,000th unit as a remainder. As an example let us say the input is 12345 or 23456.

Example: 1)      12345/10000 (Remainder) = 2345
               2)      23456/10000 (Remainder) =3456

And we subtract it from the original input giving us the 10,000th unit of the first digit:

Example: 1)     12345-2345=10,000
               2)     23456-3456=20,000

Divide the 10,000th unit by 10,000 and we get the first digit:

Example: 1)     10000/10000=1 First digit of first input
               2)     20000/10000=2 First digit of second input.

We just continue doing this eliminating the 10000th, 1000th, 100th and 10th units. Eventually we know all the digits.

The program first displays the reverse number as a string of single variables:
 printf("Reverse of %i = %i%i%i%i%i\n",input,fifth,fourth,third,second,first);

Then as a single variable
printf("Reverse number again= %i",rev);
Try entering 10000 as the input and look at the output to see the difference between them; then choose which one is best, I prefer to leave them both in.


Here is the program:

#include <stdio.h>

main()
{
    int input,rev,temp,remain_digits,first,second,third,fourth,fifth;

    printf("Enter a five digit number:");
    scanf(" %i",&input);
    if(input>9999 && input<=99999) //Make sure it is a 5 digit number
    {
        temp=input;
        remain_digits=temp%10000;
        printf("remaining %i\n",remain_digits);
        first=(temp-remain_digits)/10000;
        printf("first %i\n",first); //first digit

        temp=remain_digits;
        remain_digits=temp%1000;
        printf("remaining %i\n",remain_digits);
        second=(temp-remain_digits)/1000;
        printf("second %i\n",second); //second digit

        temp=remain_digits;
        remain_digits=temp%100;
        printf("remaining %i\n",remain_digits);
        third=(temp-remain_digits)/100;
        printf("third %i\n",third);

        temp=remain_digits;
        remain_digits=temp%10;
        printf("remaining %i\n",remain_digits);
        fourth=(temp-remain_digits)/10;
        printf("fourth %i\n",fourth);

        fifth=remain_digits;

        printf("fifth %i\n",fifth);

        printf("Reverse of %i = %i%i%i%i%i\n",input,fifth,fourth,third,second,first);

        /*If you want the reverse number as a single variable*/
        rev=(fifth*10000)+(fourth*1000)+(third*100)+(second*10)+first;
        printf("Reverse number again= %i",rev);

    }

    else
    {
        printf("Only a 5 digit number please.");
    }

}



IF you get negative or strange values as an output change the line:
int input,rev,temp,remain_digits,first,second,third,fourth,fifth;

To:

unsigned input,rev,temp,remain_digits,first,second,third,fourth,fifth;
and change every occurrence of %i to %u (Pressing Ctrl+R will bring up Search And Replace in Code::Blocks).


Older systems have a limited range for an int, I think its from -32768 to Positive 32767. Mine is at around 2 billion, go figure.

We can also use this to solve the exercise I-g:
If a five digit number is input through the keyboard, write a program to calculate the sum of its digits. (Hint: Use the modulus operator '%')
In this case, once we have all the digits, we can simply say:

printf("Sum of the digits= %i",first+second+third+fourth+fifth);

and that will output the sum of the digits.

Tuesday 11 June 2013

Program to put quotation marks on an input string

Repetition is the key to familiarity. I am still writing programs that deal with passing address of strings and manipulating them.

Here is a program that adds quotes to a string input by the user. We can simply do this by:

printf("\"%s\""arr1);

This program is a more complicated way of doing it, written as an exercise, and besides now the string in memory holds the input with quotes in them. Makes me feel like I'm putting the "s into the computer memory with tweezers or something. Heh!

#include <stdio.h>

void passed(char *x,char *y);   //PASS THE VALUE AT ADDRESS X AND Y

main()
{
    char arr1[500],arr2[500];   //both arrays have 500 blocks each set for them.

    printf("Enter a string: "); //ask for and get user string into arr1
    gets(arr1);

    passed(arr1,arr2);              //send THE ADDRESS OF THE FIRST MEMORY BLOCKS to passed
    
    printf("Here is the original string:\n%s\n",arr1);

    printf("Here is the copied string:\n%s",arr2);  //arr1 is unchanged and still contains the original input
                                                    //arr2 has quotation marks on the original string
}

void passed(char *x,char *y)
{
    *y='"'; //assign a quotation mark to the FIRST MEMORY BLOCK
    y++;    //go on to the next block
    while(*x!='\0')     //while the memoryblock does not contain \0 (NULL- which means the end of the string)
    {
        *y=*x;          //the value at *x is copied to *y.
        x++;            //next memory block
        y++;            //next memory block
    }
    *y='"';     //the entire string has been copied from arr1 (passed as a pointer *x) into arr2
                //put a " at the ending
    y++;        //next memory block
    *y='\0';    //the \0 (NULL) character is assigned here to let the program recognize the end of the string.
}

Pointers, Strings & Arrays. Count the characters of a user entered string

Day before, I went down and bought the 12th edition of 'Let US C' (2012), It's a big step up from the 4th edition.
The Graphics chapter , thankfully, has been updated to Windows graphics from DOS Graphics in the 4th edition.
I'm really having a difficult time understanding strings and arrays. Okay, I do understand Arrays, they are pretty easy, but referring to them with pointers, especially in the 'String' arrays....it's a pain.
I'm not moving on to the other chapters until I have grasped the concepts- at least to the point that I can manipulate variables across functions as easily as I manipulate variables within one function by direct reference.
Say we have a char 'name[20]' that holds 'John Smith'. I want to be able to send that to another function by using a pointer, and manipulate it to change it to say: Jane Smith. I'll stick to this chapter and write small programs that do these things until it becomes second nature to me.

Here is a program that uses a function to count the length of a string the user has entered. I try writing this without looking at the book and sites, but eventually end up having to take a peek to get rid of the errors.

Suppose the user enters "My String", it is stored in an array M|Y|<space>|S|T|R|I|N|G|\0|. The \0 is called a NULL character that lets the program know that we have reached the end of the string.

So, every character the user has entered has three characteristics:

User String            Address (Will be in sequence)   Name of the Location
User may enter       I am beginning from 1000          We declared arr1
'My String'              for illustration

M                            1000                                            arr1[0]
y                             1001                                            arr1[1]
<space>                   1002                                            arr1[2]
S                             1003                                            arr1[3]
t                              1004                                             arr1[4]
r                              1005                                             arr1[5]
i                              1006                                             arr1[6]
n                             1007                                             arr1[7]
g                             1008                                             arr1[8]
\0 (NULL)                1009                                              arr1[9]

What the program does is it sends the address of the first character (1000) of the user entered string (M in this case) to the function passed():
                               int length=passed(arr1);

and it goes through each character until it encounters the '\0'.
While(the value at the address stored in x is not \0, increment the address at x)
                               while(*x!='\0') 
                               {
                                     x++;
Every character it goes through, the int variable 'y' which has been declared as a zero is also incremented by 1. y is counting the number of characters we are going through:
                                 y++;
                                 }
 Finally 'y' (number of characters we went through before we reached \0) is sent back to main:
                                 return(y);

 which stores it in 'length' and is displayed with printf.
                                 int length=passed(arr1);

                                 printf("Length of:\n%s= %i",arr1,length);

Characters in a string can be counted by using the standard library string function strlen() (string length), but this program tries to emulate what strlen() does, and if I figure this out, I feel I will have a better understanding about pointers and related arrays and variables.

Here is the program:

#include <stdio.h>

int passed(char *x);

main()
{
    char arr1[500];
    printf("Enter a string to count it's length:\n");
    gets(arr1);
    int length=passed(arr1);

    printf("Length of:\n%s= %i",arr1,length);
}

int passed(char *x)
{
    int y=0;
    while(*x!='\0')
    {
        x++;
        y++;
    }
    return(y);
}
__________________________________________________________________________

Here is a sample output:

Enter a string to count it's length:
My String             //User enters this
Length of:
My String= 9



Thursday 6 June 2013

myconstdwin.h

So the new header file contains the following header files windows.h, conio.h, stdio.h, so if you include myconstdwin.h, you dont need to include them again.

Its just an improvement on the previous file. It adds a new ability to move the DOS window.
I have it saved as myconstdwin.h to remind me that the three header files are already included.
If you are not sure what to do with this code:
Copy and paste this code into notepad, save the file as myconstdwin.h on the desktop (not as myconstdwin.txt).
Cut and paste the file into the INCLUDE folder (the default path for the include folder in Code::Blocks is
C:\Program Files\CodeBlocks\MinGW\include) or (C:\Program Files\CodeBlocks\MinGW\x86_64-w64-mingw32\include). Now any program in Code::Blocks that has 
#include <myconstdwin.h> in it will compile and run.

NOTE: Any program that uses the movewin function might require you to  rewrite it again. That means a program that uses movewin will require you to include the following lines in the program:

void movewin(int x, int y)
{
    HWND hWnd=GetConsoleWindowNT();
    MoveWindow(hWnd,x,y,800,400,TRUE);
}

EDIT: To see what this file allows us to do Click Me

Now on to the header file:

#include <windows.h>
#include <conio.h>
#include <stdio.h>  //For move and resize window

COORD coord = {0, 0};

/*Start of move and resize window*/
/*Move Window*/
HWND WINAPI GetConsoleWindowNT(void)
{
    // declare function pointer type

    typedef HWND WINAPI (*GetConsoleWindowT)(void);

    // declare one such function pointer

    GetConsoleWindowT GetConsoleWindow;

    // get a handle on kernel32.dll

    HMODULE hK32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));

    // assign procedure address to function pointer

    GetConsoleWindow = (GetConsoleWindowT)GetProcAddress(hK32Lib,TEXT("GetConsoleWindow"));

    // check if the function pointer is valid

    // since the function is undocumented

    if ( GetConsoleWindow == NULL ) {
         return NULL;
    }

    // call the undocumented function

    return GetConsoleWindow();
}

void movewin(int x, int y) //Move the DOS Window x=Decrease-Left Increase-Right, y=Decrease-Up Increase-Down
{
    HWND hWnd=GetConsoleWindowNT();
    MoveWindow(hWnd,x,y,800,400,TRUE); //x,y moves screen. 800,400 takes the screen max size cannot make it
                                       //larger using this we have to use the 'mode x,y' DOS command
}
/*End of move and resize window*/


void gotoxy(int x,int y)
{
coord.X=x;coord.Y=y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}


void SetColorAndBackground(int ForgC,int BackC)
{
     WORD wColor=((BackC&0x0F)<<4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),wColor);
     return;
}


Somewhat addicted. Changes to the previous program.

I've been fiddling around with the previous program (The one that draws the lines). I'll try to write a complete program out of it that will do some semi-useful stuff.

It is turning into a big program and I know for certain that this program is in no way the best way to write it, ah but what the hell, I'm still a newb.

The screen size is set at line 39 (system("mode 158,77");). It fits my square screen. I don't think it should be changed, because that would mess the program up badly. :(     But I tried it on my Laptop and all it needs is a little scrolling on my part as I use it.

Only the graph menu option for WEEK works for now, and it still needs work. I have left in the comments I made to myself regarding the bugs I need to fix & other stuff I need to remember.

It's killing me that there probably are easy fixes for these but I don't know them. Well, live and learn.

I have added another function to <myconstdwin.h> and renamed it. I'll post it after I have posted this program. The new function will allow for moving the DOS window around the screen, besides that it also allows limited resizing of the window. [EDIT: Here It Is]

These ASCII drawings may look lame and amateurish, but they give me the satisfaction of seeing them being drawn on the screen. It's something I wanted to do when I was a teen, let me satisfy that urge.

Working on this, I have also learnt to detect the Function keys and others usually undetectable with the 'getc' family of functions.

When will I learn how to save data to disk? =[

As always: Copy paste into Code::Blocks and hit F9.

#include <myconstdwin.h> //contains the color, gotoxy and move window functions includes windows, conio.h & stdio.h
#include <time.h>
#include <ctype.h>

#define TRUE 1
#define FALSE !TRUE

void movewin(int x, int y); //Move the DOS Window
void tab(void);
void backspace(void);
void entr(void);
void drawbox(void);
void menuoptionsmain(void);
void menuoptionsgraph(char mop1[25],char mop2[25],char mop3[25]);
void fillbox2(void);
void TimeNDate(void);
void helpmain(void);
int get_key();

void graph(void);
void drawmesh(void);
void weekgraph(void);
void yeargraph(void);

void erase_box1(void);
void erase_box3(int b); //The int that is passed is used as gotoxy(x,passed Int), so that it doesnt have to backspace
                        //the blank lines. It was much slower if it backspaces the whole box.
void erase_box4(void);

int state;

/*horizontal characters 157 without lines*/
/*gotoxy(horizontal,vertical)*/
/*SPACE FROM THE TOP OF THE BOTTOM BOX TO ITS BOTTOM IS 63*/

main()
{
    movewin(1,1);                      //Move Dos Window to top left
    system("mode 158,77");             //We use this to resize the window
    drawbox();                         //Draw the lines
    menuoptionsmain();                 //Print menu options
    fillbox2();
    state=TRUE;
    while(state)
    {
        int key;
        gotoxy(1,12);
        key=get_key();
        if(key==27) //Esc Key
        {
            state=FALSE;
        }
        else if(key==315)   //F1 Key
        {
            helpmain();
        }

        else if(key==321)   //F7
        {
            graph();
            menuoptionsmain();                 //Print menu options
        }
    }
}

void drawbox(void)
{
    system("cls");
    /*This part of the code draws the lines*/
    int x;
    SetColorAndBackground(8,0);

    for(x=0;x<75;x++)   //Middle verticle line
    {
        gotoxy(80,x);
        printf("%c",186);
    }

    for(x=1;x<157;x++)      //outside middle horizontal line
    {
        gotoxy(x,11);
        printf("%c",205); //196
    }

    for(x=1;x<80;x++)   //First half of Outside top line
    {
        gotoxy(x,0);
        printf("%c",205); //196
    }


    gotoxy(80,0);
    printf("%c",203);   //Middle joint of outside top.

    for(x=81;x<157;x++)   //Second half of Outside top line
    {
        gotoxy(x,0);
        printf("%c",205); //196
    }

    gotoxy(157,0);  //Top outside right joint
    printf("%c",187);

    for(x=1;x<75;x++)
    {
        gotoxy(0,x);
        printf("%c",186); //186,
    }

    gotoxy(0,75); //Outside left verticle bottom Joint
    printf("%c",200);

    for(x=1;x<80;x++)   //First half of Horizontal bottom
    {
        gotoxy(x,75);
        printf("%c",205);
    }

    for(x=1;x<75;x++)   //Left outside verticle line
    {
        gotoxy(157,x);
        printf("%c",186);
    }

    gotoxy(80,11);
    printf("%c",206);   //Middle line middle joint.

    gotoxy(0,0);
    printf("%c",201);   //Home joint

    gotoxy(0,11);       //left verticle line middle joint
    printf("%c",204);

    gotoxy(157,11);     //right verticle line middle joint
    printf("%c",185);

    gotoxy(80,75);      //Bottom horizontal line, middle joint.
    printf("%c",202);

    for(x=81;x<157;x++)   //Second half of Horizontal bottom
    {
        gotoxy(x,75);
        printf("%c",205); //196
    }

    gotoxy(157,75);     //Bottom horizontal right joint.
    printf("%c",188);

    /*The Outside lines are done. Now to draw the inside boxes*/

    gotoxy(1,1);    //Inside Top left joint. Left Box
    printf("%c",201);

    for(x=2;x<79;x++)   //First half Inside top Horizontal line. Left Box
    {
        gotoxy(x,1);
        printf("%c",205);
    }

    gotoxy(79,1);
    printf("%c",187);   //Inside top right joint. Left Box

    gotoxy(81,1);    //Inside Top left joint. Second box
    printf("%c",201);

    for(x=82;x<156;x++)   //Inside top Horizontal line. Right Box
    {
        gotoxy(x,1);
        printf("%c",205);
    }

    gotoxy(156,1);      //Inside Top right joint (2nd box)
    printf("%c",187);

    for(x=2;x<10;x++)   //first box left vertical inside
    {
        gotoxy(1,x);
        printf("%c",186);
    }

    gotoxy(1,10);       //first box, bottom left joint
    printf("%c",200);

    for(x=2;x<79;x++)       //first box bottom hori inside
    {
        gotoxy(x,10);
        printf("%c",205);
    }

    gotoxy(79,10);        //First box, bottom right joint.
    printf("%c",188);

    for(x=2;x<10;x++)   //first box right vertical inside
    {
        gotoxy(79,x);
        printf("%c",186);
    }

    for(x=2;x<10;x++)   //Second box left vertical inside
    {
        gotoxy(81,x);
        printf("%c",186);
    }

    gotoxy(81,10);      //Second inside box. Left bottom joint
    printf("%c",200);

    for(x=2;x<10;x++)   //Second box Right vertical inside
    {
        gotoxy(156,x);
        printf("%c",186);
    }

    for(x=82;x<156;x++)       //Second box bottom hori inside
    {
        gotoxy(x,10);
        printf("%c",205);
    }

    gotoxy(156,10);         //Second box, bottom right joint. (inside)
    printf("%c",188);
}

void menuoptionsmain(void)  //Display Menu Options
{
    erase_box1();
    gotoxy(2,2);
    printf("Esc\t-\tExit Program");
    gotoxy(2,3);
    printf("F1\t-\tHelp");
    gotoxy(2,4);
    printf("F2\t-\tOpen Records");
    gotoxy(2,5);
    printf("F3\t-\tSearch");
    gotoxy(2,6);
    printf("F4\t-\tSave");
    gotoxy(2,7);
    printf("F5\t-\tUsers");
    gotoxy(2,8);
    printf("F6\t-\tBackup");
    gotoxy(2,9);
    printf("F7\t-\tBar Graph");
}

/*Complete This Function*/
void menuoptionsgraph(char mop1[25],char mop2[25],char mop3[25])
{
    erase_box1();
    gotoxy(2,2);
    printf("%s",mop1);
    gotoxy(2,3);
    printf("%s",mop2);
    gotoxy(2,4);
    printf("%s",mop3);
}

void fillbox2(void)
{
    int w=0,x,y=2,z;
    while (w<8)
    {
        for(x=0;x<74;x++)
        {
            gotoxy(x+82,y);
            printf("%c",178);
        }
        w++;
        y++;
    }
    SetColorAndBackground(8,0);
    gotoxy(110,3);              //This Displays the logo
    printf(" %c  %c%c%c %c   %c",220,220,220,220,220,220);
    gotoxy(110,4);
    printf("%c %c  %c  %c%c %c%c",219,219,219,219,219,219,219);
    gotoxy(110,5);
    printf("%c%c%c  %c  %c %c %c",219,220,219,219,219,219,219);
    gotoxy(110,6);
    printf("%c %c %c%c%c %c   %c",219,219,220,219,220,219,219);
    //gotoxy(83,3);
    //printf("Accounts & Inventory"); 
    //gotoxy(88,4);
    //printf("Management.");
    //gotoxy(104,4);
    //printf(" Shop Name ");
    SetColorAndBackground(8,0);
    gotoxy(85,8);
    TimeNDate();
    gotoxy(109,8);
    /*Backspace out the time & replace with ASCII 178 because it is static. We only want the date.*/
    printf("\b\b\b\b\b\b \b\b \b\b \b\b \b\b \b\b \b\b \b\b \b\b \b%c%c%c%c%c%c%c%c%c",178,178,178,178,178,178,178,178,178);
}

void TimeNDate(void) //Displays time & date when needed.
{
time_t t;
time(&t);
printf("%s",ctime(&t));
}

void helpmain(void)     //Main menu help.
{
    int key;
    gotoxy(1,12);
    printf("Shop Name. "); 
    printf("Accounts & Inventory Management (AIM).");
    gotoxy(1,14);
    printf("Press one of the keys in the menu for");
    gotoxy(1,15);
    printf("a discription.");
    key=get_key();
    erase_box3(15);
    if(key==315)
    {
        gotoxy(1,12);
        printf("This displays help for any area of the");
        gotoxy(1,13);
        printf("program you may be in. It will attempt");
        gotoxy(1,14);
        printf("to explain what you can do on the");
        gotoxy(1,15);
        printf("current screen.");
        gotoxy(1,22);
        printf("Press any key....");
        getch();
        erase_box3(22);
    }
}

int get_key()   //reads key and returns an appropriate value including function keys.
{
    int c = getch();
    switch (c)
    {
      case 0:   return getch()+256;
      case 224: return getch()+512;
    }
    return c;
}

void graph(void)    //Draws graph.
{
    char c;

    menuoptionsgraph("B\t-\tBack","W\t-\tGraph For A Week","Y\t-\tGraph For A Year");
    gotoxy(1,12);
    printf("AIM only provides the ability to create bar graphs for a Week (by day) or Year");
    gotoxy(1,13);
    printf("(By Month).");
    gotoxy(1,14);
    printf("The graphs display an approximate & should not be considered completely");
    gotoxy(1,15);
    printf("accurate.");
    gotoxy(1,17);
    printf("Would you like a Week or Year chart?(W/Y/Back):");
    for(;;)
    {
       c=toupper(getch());
       if(c=='Y')
       {
           erase_box3(17);
            yeargraph();
            break;
       }

       else if(c=='W')
       {
           erase_box3(17);
           weekgraph();
           break;
       }

       else if(c=='B')
       {
           erase_box3(17);
           break;
       }
    }

}

void weekgraph(void)
{
    int a[7],h[7],i,j,k=0;
    int x,y;
    float temp,b[7];
    char day[7] [10]={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

    /*Using 'day1' to properly indent the sales the second time it is used when the graph is displayed
     since I cannot seem to reassign the values to 'char day' once i've declared it*/
    char day1[7] [10]={"Monday\t","Tuesday","Wednesday","Thursday","Friday\t","Saturday","Sunday\t"};



    /*Need to figure out 1. If user presses enter key without entering a value*/
    menuoptionsgraph("Enter Values"," "," ");
    for(x=0;x<7;x++)
    {
        gotoxy(1,12+x);
        printf("Sale %s (0 for closed): ",day[x]);
        scanf(" %i",&a[x]);
        h[x]=a[x];
    }
    erase_box3(26);

    /*Display Sales by day*/
    for(x=0;x<7;x++)
    {
        gotoxy(1,12+x);
        printf("%s\t-%6i",day1[x],h[x]);
    }
    getch();

    /*Sort the input in ascending order & store it in a[x]*/
    gotoxy(1,12);
    for (i=0;i<7;i++)
        for(j=i+1;j<7;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[j];
                a[j]=a[i];
                a[i]=temp;
            }
        }

        /*a[x] now contains the numbers in ascending order.
          h[x] has the input in the original order.*/

          /*Divide the largest number (contained in a[6]) by 100
            store the result (1% of largest number), store it in a float variable (temp)
            and divide all the input by temp. Assign the multiple to b[x].
            2% will add one character of growth for the bar
            1 to 100 is assigned by percentages.*/

    temp=(float)a[6]/100;  //Divide largest number by 100, store in temp.

    for(x=0;x<7;x++)    //Divide all the input by 1% of the largest number & store in b[x] array
    {
        b[x]=(float)h[x]/temp;
        //b[x]=(int)b[x];
    }


    /*Start drawing the graph*/

    drawmesh(); //Draws a mesh where the graph will be drawn. with percentages printed to left

    gotoxy(87,74);
    printf("Monday    Tuesday  Wednesday  Thursday   Friday   Saturday  Sunday"); //Bottom of Graph

    gotoxy(82,73); //Line for dividing the day names and the bars begins here
    for(x=0;x<74;x++)
    {
        printf("%c",196);  //Displays the bottom line for the graph.
    }
/*


*/
    SetColorAndBackground(12,0); //red
    y=72;
    for(x=0;x<b[0];x+=2)        //Monday Draws the bar (2 lines and 2 spaces) of ASCII 219 in red)
    {
        for(temp=0;temp<1000000;temp++); //Provide a slight pause between drawing
        gotoxy(89,y);                      //First character
        printf("%c",219);
        gotoxy(90,y);                   //Second character
        printf("%c",219);
        y--;                            //decrement y (verticle space)
    }

    SetColorAndBackground(15,0);    //Bright White for the input value
    gotoxy(88,21);                  //Display the amount entered on top of the bar
    printf("%4i",h[0]);

    /*repeat the above 6 more times*/

    SetColorAndBackground(12,0);
    y=72;
    for(x=0;x<b[1];x+=2)        //Tuesday
    {
        for(temp=0;temp<1000000;temp++);
        gotoxy(100,y);
        printf("%c",219);
        gotoxy(101,y);
        printf("%c",219);
        y--;
    }

    SetColorAndBackground(15,0);
    gotoxy(99,21);
    printf("%4i",h[1]);

    SetColorAndBackground(12,0);
    y=72;
    for(x=0;x<b[2];x+=2)        //Wednesday
    {
        for(temp=0;temp<1000000;temp++);
        gotoxy(111,y);
        printf("%c",219);
        gotoxy(112,y);
        printf("%c",219);
        y--;
    }

    SetColorAndBackground(15,0);
    gotoxy(110,21);
    printf("%4i",h[2]);

    SetColorAndBackground(12,0);
    y=72;
    for(x=0;x<b[3];x+=2)        //Thursday
    {
        for(temp=0;temp<1000000;temp++);
        gotoxy(121,y);
        printf("%c",219);
        gotoxy(122,y);
        printf("%c",219);
        y--;
    }

    SetColorAndBackground(15,0);
    gotoxy(120,21);
    printf("%4i",h[3]);

    SetColorAndBackground(12,0);
    y=72;
    for(x=0;x<b[4];x+=2)        //Friday
    {
        for(temp=0;temp<1000000;temp++);
        gotoxy(131,y);
        printf("%c",219);
        gotoxy(132,y);
        printf("%c",219);
        y--;
    }

    SetColorAndBackground(15,0);
    gotoxy(130,21);
    printf("%4i",h[4]);

    SetColorAndBackground(12,0);
    y=72;
    for(x=0;x<b[5];x+=2)        //Saturday
    {
        for(temp=0;temp<1000000;temp++);
        gotoxy(141,y);
        printf("%c",219);
        gotoxy(142,y);
        printf("%c",219);
        y--;
    }

    SetColorAndBackground(15,0);
    gotoxy(140,21);
    printf("%4i",h[5]);

    SetColorAndBackground(12,0);
    y=72;
    for(x=0;x<b[6];x+=2)        //Sunday
    {
        for(temp=0;temp<1000000;temp++);
        gotoxy(151,y);
        printf("%c",219);
        gotoxy(152,y);
        printf("%c",219);
        y--;
    }

    SetColorAndBackground(15,0);
    gotoxy(150,21);
    printf("%4i",h[6]);
    SetColorAndBackground(8,0); //back to grey

    /*Find & display total earned in the week*/
    k=0;
    for(x=0;x<7;x++)
    {
        k=k+h[x];
    }
    gotoxy(1,19);
    printf("______________________");
    gotoxy(11,20);
    printf("Total-%6i",k);
    gotoxy(23,20); //Move cursor to last digit after total.
    menuoptionsgraph("Any Key\t-\tMain Menu","F1\t\t-\tHelp","F4\t\t-\tSave");
    getch();
    erase_box3(26);
    erase_box4();
    gotoxy(1,12);
}

void yeargraph(void)
{
    gotoxy(1,12);
    printf("Yeargraph Code here.");
    getch();
    erase_box3(12);
}

void erase_box1(void)
{
    int x,y=9;
    while(y>1)
    {
        for(x=3;x<80;x++)
        {
            gotoxy(x,y);
            printf("\b \b");
        }
        y--;
    }
}

void erase_box3(int b)
{
    int x,y=b,z=b;
    while(y>11)
    {
        gotoxy(79,y);
        for(x=1;x<79;x++)
        {
            printf("\b \b");
        }
        y--;
    }
}

void erase_box4(void)
{
    int x,y=74,z=0;
    while(y>11)
    {
        gotoxy(156,y);
        for(x=0;x<75;x++)
        {
            printf("\b \b");
        }
        y--;
    }
}

/*Move Window*/
void movewin(int x, int y)
{
    HWND hWnd=GetConsoleWindowNT();
    MoveWindow(hWnd,x,y,800,400,TRUE); //x,y moves screen. 800,400 takes the screen max size cannot make it
                                       //larger using this we have to use the 'system x,y' DOS command
}

/*Draws the mesh behind the graph*/
void drawmesh(void)
{
    int w,x,y,z=22;

    /*This part puts the percentage to the left of the mesh*/
    y=72;
    for(x=0;x<102;x+=10)
    {
        gotoxy(81,y);
        printf("%3i%%",x);
        y-=5;
    }


    gotoxy(86,z);
    printf("%c",218);
    for(w=0;w<16;w++)
    {
        for(x=0;x<3;x++)
        {
            printf("%c",196);

        }
        printf("%c",194);
    }
    for(x=0;x<3;x++)
        {
            printf("%c",196);

        }
    printf("%c",191);


    for(y=0;y<25;y++)
    {
        z++;
    gotoxy(86,z);
    printf("%c",179);

    for(w=0;w<16;w++)
    {
        for(x=0;x<3;x++)
        {
            printf("%c",255);

        }
        printf("%c",179);
    }
    for(x=0;x<3;x++)
        {
            printf("%c",255);

        }
    printf("%c",179);


        z++;
    gotoxy(86,z);
    printf("%c",195);

    for(w=0;w<16;w++)
    {
        for(x=0;x<3;x++)
        {
            printf("%c",196);

        }
        printf("%c",197);
    }
    for(x=0;x<3;x++)
        {
            printf("%c",196);

        }
    printf("%c",180);
    }
}