Vision and dreams are the blueprints of soul and achievements.
-Mohammed Ahmed F

Showing posts sorted by relevance for query c program. Sort by date Show all posts
Showing posts sorted by relevance for query c program. Sort by date Show all posts
Introduction to C++

Introduction to C++

What is C and why learn it?

C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories. C was originally designed for writing system software but today a variety of software programs are written in C.

C can be used on many different types of computers but is mostly used with the UNIX operating system.

It is a good idea to learn C because it has been around for a long time which means there is a lot of information available on it.

Quite a few other programming languages such as C++ and Java are also based on C which means you will be able to learn them more easily in the future.

Your first program:

The first thing you must do i download the Turbo C++ and now type the following lines of code and then I will explain it. Make sure that you type it exactly as I have or else you will have problems.

Also don't be scared if you think it is too complicated because it is all very easy once you understand it.

#include<stdio.h>

int main()
{
   printf("Hello World\n");
   return 0;
}


#include<stdio.h>

This includes a file called stdio.h which lets us use certain commands. stdio is short for Standard Input/Output which means it has commands for input like reading from the keyboard and output like printing things on the screen.

int main()

int is what is called the return value which will be explained in a while. main is the name of the point where the program starts and the brackets are there for a reason that you will learn in the future but they have to be there.

{}

The 2 curly brackets are used to group all the commands together so it is known that the commands belong to main. These curly brackets are used very often in C to group things together.

printf("Hello World\n");

This is the printf command and it prints text on the screen. The data that is to be printed is put inside brackets.

You will also notice that the words are inside inverted commas because they are what is called a string.

Each letter is called a character and a series of characters that is grouped together is called a string. Strings must always be put between inverted commas.

The \n is called an escape sequence and represents a newline character and is used because when you press ENTER it doesn't insert a new line character but instead takes you onto the next line in the text editor.

You have to put a semi-colon after every command to show that it is the end of the command.

Table of commonly used escape sequences:

\a- Audible signal

\b- Backspace
\t - Tab
\n - Newline
\v- Vertical tab
\f - New page / Clear screen
\r -Carriage return


return 0;

The int in int main() is short for integer which is another word for number. We need to use the return command to return the value 0 to the operating system to tell it that there were no errors while the program was running.

Notice that it is a command so it also has to have a semi-colon after it.

Save the text file as hello.c and now rum the program.

Indentation:

You will see that the printf and return commands have been indented or moved away from the left side. This is used to make the code more readable.

It seems like a stupid thing to do because it just wastes time but when you start writing longer, more complex programs, you will understand why indentation is needed.

Using comments:

Comments are a way of explaining what a program does. They are put after // or between /* */.

Comments are ignored by the compiler and are used by you and other people to understand your code.

You should always put a comment at the top of a program that tells you what the program does because one day if you come back and look at a program you might not be able to understand what it does but the comment will tell you.

You can also use comments in between your code to explain a piece of code that is very complex.

Here is an example of how to comment the Hello World program:

/* Author: Your name

   Date: yyyy/mm/dd
   Description:
   Writes the words "Hello World" on the screen */
#include<stdio.h>
int main()
{
   printf("Hello World\n"); //prints "Hello World"
   return 0;
}




INTRODUCTION TO C++:

Hello World Program:

Our first C++ program will print the message "Hello World" on the screen. Open a new project or console and start by typing the following line:

#include<iostream>

The above line includes the header file called iostream which will allow us to use the command to print words on the screen. Next you must type:

using namespace std;

This will let us use certain commands without having to type out their full name. Now we will type the main function.

int main()

{
}


The main function is where a program always starts. Every program must have a main function. The word int in front of main is to say what the return value is.

The curly brackets belong to the main function and show where it begins and where it ends. Now we will type the command that prints "Hello World" on the screen between the curly brackets.

cout << "Hello World\n";

The cout command is used to print things on the screen. The << means that the text must be output. The words that you want printed must be surrounded by quotes.

The \n means that the cursor must go the beginning of the next line. Lastly we must return 0 to the operating system to tell it that there were no errors while running the program.

return 0;

The full program should look like this:

#include<iostream>

using namespace std;
int main()
{
   cout << "Hello World\n";
   return 0;
}


Save the file as hello.cpp. You now need to compile the program. You need to open a command prompt and type the command name of your C++ compiler and the name of the C++ file you have just created.

Here is an example of how to do it with Turbo C++:

hello.cpp

If you are given error messages then you have made mistakes which means you should go through this post again and fix them.

If you don't get any errors then you should end up with an executable file which in my case is called hello.exe

Enter hello to run the program and you should see "Hello World" printed on the screen.

Congratulations! You have just made your first C++ program.

-Mohammed Ahmed F, Chief Administrative Officer.
Basics of C++

Basics of C++

Today we will see the basics of C++:

When we consider a C++ program it can be defined as a collection of objects that communicate via invoking each others methods.

Let us now briefly look into what do class, object, methods and instant variables mean.

Object - Objects have states and behaviors.

Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.

Methods - A method is basically a behavior. A class can contain many methods.

It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables.

C++ Program Structure:

Let us look at a simple code that would print the words Hello World.

#include <iostream>

using namespace std;
// main() is where program execution begins.
int main()
{
   cout << "Hello World"; // prints Hello World
   return 0;
}


Let us look various parts of the above program:

The C++ language defines several headers, which contain information that is either necessary or useful to your program.

For this program, the header <iostream> is needed.

The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.

The next line // main() is where program execution begins. is a single-line comment available in C++.

Single-line comments begin with // and stop at the end of the line.

The line int main() is the main function where program execution begins.

The next line cout << "This is my first C++ program."; causes the message "This is my first C++ program" to be displayed on the screen.

The next line return 0; terminates main() function and causes it to return the value 0 to the calling process.

Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.

You can compile C/C++ programs using makefile.

Semicolons & Blocks in C++:

In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.

For example, following are three different statements:

x = y;

y = y+1;
add(x, y);


A block is a set of logically connected statements that are surrounded by opening and closing braces.

For example:
{

   cout << "Hello World"; // prints Hello World
   return 0;
}


C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where on a line you put a statement.

For example:

x = y;

y = y+1;
add(x, y);


is the same as

x = y; y = y+1; add(x, y);

C++ Identifiers:

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

C++ does not allow punctuation characters such as @, $, and % within identifiers.

C++ is a case sensitive programming language. Thus, "Manpower" and "manpower" are two different identifiers in C++.

Here are some examples of acceptable identifiers:

mohd

zara
abc
move_name
a_123
myname50
_temp
j
a23b9
retVal


Whitespace in C++:

A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it.

Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments.

Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins.

Therefore, in the statement,

int age;

There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the statement

fruit = apples + oranges;   // Get the total fruit

No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.
Introduction to Loops

Introduction to Loops

Loops


While Loop:

A while loop statement in C programming language repeatedly executes a target statement as long as a given condition is true.

Syntax:

while(condition)
{
statement(s);
}

Here statement(s) may be a single statement or a block of statements.

The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.

For Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

for (initialization; condition; increment  / decrement)
{
statement(s);
}

Here is the flow of control in a for loop:

The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

Next, the condition is evaluated.

If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables.

This statement can be left blank, as long as a semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition).

After the condition becomes false, the for loop terminates.

do...while Loop:

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming language checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

do
{
statement(s);
}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.

Nested Loops:

C programming language allows to use one loop inside another loop.

Following section shows few examples to illustrate the concept.

Syntax:

for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

The syntax for a nested while loop statement in C programming language is as follows:

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop statement in C programming language is as follows:

do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );

A final note on loop nesting is that you can put any type of loop inside of any other type of loop.

For example a for loop can be inside a while loop or vice versa.

Loop Control Statements:

Break Statement:

The break statement in C programming language has following two usage:

When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:

The syntax for a break statement in C is as follows:

break;

Continue Statement:

The continue statement in C programming language works somewhat like the break statement. 

Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the loop to execute.

For the while and do...while loops, continue statement causes the program control passes to the conditional tests.

Syntax:

The syntax for a continue statement in C is as follows:

continue;

Go TO Statement:

A goto statement in C programming language provides an unconditional jump from the goto to a labeled statement in the same function.

NOTE:

Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

Syntax:

The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.
10 Industry Demanding Programming Languages

10 Industry Demanding Programming Languages

Folks,

This should help you out in deciding what you need to pursue for your career. if you like this post, then kindly share among your friends.

The tech sector is booming. If you've used a smartphone or logged on to a computer at least once in the last few years, you've probably noticed this.

As a result, coding skills are in high demand, with programming jobs paying significantly more than the average position. Even beyond the tech world, an understanding of at least one programming language makes an impressive addition to any resumé.

The in-vogue languages vary by employment sector. Financial and enterprise systems need to perform complicated functions and remain highly organized, requiring languages like Java and C#. Media- and design-related webpages and software will require dynamic, versatile and functional languages with minimal code, such as Ruby, PHP, JavaScript and Objective-C.

With some help from Lynda.com, we've compiled a list of 10 of the most sought-after programming languages to get you up to speed.

1. Java: What it is: Java is a class-based, object-oriented programming language developed by Sun Microsystems in the 1990s. It's one of the most in-demand programming languages, a standard for enterprise software, web-based content, games and mobile apps, as well as the Android operating system. Java is designed to work across multiple software platforms, meaning a program written on Mac OS X, for example, could also run on Windows.

Where to Study?: Udemy, Lynda, Oracle, LearnJavaOnline

2. C Language: What it is: A general-purpose, imperative programming language developed in the early '70s, C is the oldest and most widely used language, providing the building blocks for other popular languages, such as C#, Java, JavaScript and Python. C is mostly used for implementing operating systems and embedded applications. Because it provides the foundation for many other languages, it is advisable to learn C (and C++) before moving on to others.


3. C++: What it is: C++ is an intermediate-level language with object-oriented programming features, originally designed to enhance the C language. C++ powers major software like Firefox, Winamp and Adobe programs. It's used to develop systems software, application software, high-performance server and client applications and video games.

Where to Study?: Udemy, Lynda, CPlusPlus, LearnCpp, C++ Programming.

4. C#: What it is: Pronounced "C-sharp," C# is a multi-paradigm language developed by Microsoft as part of its .NET initiative. Combining principles from C and C++, C# is a general-purpose language used to develop software for Microsoft and Windows platforms.


5. Objective-C: What it is: Objective-C is a general-purpose, object-oriented programming language used by the Apple operating system. It powers Apple's OS X and iOS, as well as its APIs, and can be used to create iPhone apps, which has generated a huge demand for this once-outmoded programming language.
6. PHP: What it is: PHP (Hypertext Processor) is a free, server-side scripting language designed for dynamic websites and app development. It can be directly embedded into an HTML source document rather than an external file, which has made it a popular programming language for web developers. PHP powers more than 200 million websites, including Wordpress, Digg and Facebook.
7. Python: What it is: Python is a high-level, server-side scripting language for websites and mobile apps. It's considered a fairly easy language for beginners due to its readability and compact syntax, meaning developers can use fewer lines of code to express a concept than they would in other languages. It powers the web apps for Instagram, Pinterest and Rdio through its associated web framework, Django, and is used by Google, Yahoo! and NASA.

Where to Study?: Udemy, Codecademy, Lynda, LearnPython, Python.

8. Ruby: What it is: A dynamic, object-oriented scripting language for developing websites and mobile apps, Ruby was designed to be simple and easy to write. It powers the Ruby on Rails (or Rails) framework, which is used on Scribd, GitHub, Groupon and Shopify. Like Python, Ruby is considered a fairly user-friendly language for beginners.

Where to Study?: Codecademy, Code School, TryRuby, RubyMonk.

9. JavaScript: What it is: JavaScript is a client and server-side scripting language developed by Netscape that derives much of its syntax from C. It can be used across multiple web browsers and is considered essential for developing interactive or animated web functions. It is also used in game development and writing desktop applications. JavaScript interpreters are embedded in Google's Chrome extensions, Apple's Safari extensions, Adobe Acrobat and Reader, and Adobe's Creative Suite.

Where to Study?:  Codecademy, Lynda, Code School, Treehouse, Learn-JS.

10. SQL: What it is: Structured Query Language (SQL) is a special-purpose language for managing data in relational database management systems. It is most commonly used for its "Query" function, which searches informational databases. SQL was standardized by the American National Standards Institute (ANSI) and the International Organization for Standardization (ISO) in the 1980s.

Where to Study?: Lynda, SQLCourse, TutorialsPoint, SQLZoo.


-Chief Administrative Officer.
Program to print Diamond pattern

Program to print Diamond pattern

#include <stdio.h>
int main()
{
  int n, c, k, space = 1;

  printf("Enter number of rows\n");
  scanf("%d", &n);

  space = n - 1;
  for (k = 1; k <= n; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");

    space--;
    for (c = 1; c <= 2*k-1; c++)
      printf("*");

    printf("\n");
  }

  space = 1;
  for (k = 1; k <= n - 1; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");

    space++;
    for (c = 1 ; c <= 2*(n-k)-1; c++)
      printf("*");

    printf("\n");
  }

  return 0;
}
5 common problems a new programmer faces?

5 common problems a new programmer faces?

Folks,

The 5 Most Common Problems New Programmers Face--And How You Can Solve Them
Getting set up

Learning to program is hard enough, but it's easy to get tripped up before you even begin. First you need to chose a programming language (I recommend C++), then You need a compiler and a programming tutorial that covers the language you chose and that works with the compiler that you set up. This is all very complicated, and all before you even start to get to the fun parts. 

If you're still struggling with getting the initial setup, then check out our page on setting up a compiler and development environment (Code::Blocks and MINGW) which walks you through setting up a compiler with a lot of screenshots, and gets you up to the point of having an actual running program.

Thinking Like a Programmer

Have you seen the State Farm commercials where the car wash company returns the cars to customers with the soap suds still on the car? The company washes the car, but it didn't rinse it. 

This is a perfect metaphor for computer programs. Computers, like that car wash company, are very very literal. They do exactly, and only, what you tell them to do; they do not understand implicit intentions. The level of detail required can be daunting at first because it requires thinking through every single step of the process, making sure that no steps are missing. 

This can make programming seem to be a tough slog at first, but don't despair. Not everything must be specified--only what is not something the computer can already do. The header files and libraries that come with your compiler (for example, the iostream header file that allows you to interact with the user) provide a lot of pre-existing functionality. You can use websites like http://www.cppreference.com or our own function reference to find information on these pre-existing libraries of functionality. By using these, you can focus on precisely specifying only what is unique about your program. And even once you do that, you will begin to see patterns that can be turned into functions that wrap up a bunch of steps into a single function that you can call from everywhere. Suddenly complex problems will begin to look simple. It's the difference between:


Walk forward ten feet
Move your hand to the wall
Move your hand to the right until you hit an obstacle
...
Press upward on indentation and Walk to door Find light switch Turn on light.

The magic thing about programming is that you can box up a complex behaviour into a simple subroutine (often, into a function) that you can reuse. Sometimes it's hard to get the subroutine done up just right at first, but once you've got it, you no longer need to worry about it. 

You can go here to read more about how to think about programming, written for beginners.


Compiler Error Messages


This may seem like a small thing, but because most beginners aren't familiar with the strictness of the format of the program (the syntax), beginners tend to run into lots of complaints generated by the compiler. Compiler errors are notoriously cryptic and verbose, and by no means were written with newbies in mind. 

That said, there are a few basic principles you can use to navigate the thicket of messages. First, often times a single error causes the compiler to get so confused that it generates dozens of messages--always start with the first error message. Second, the line number is a lie. Well, maybe not a lie, but you can't trust it completely. The compiler complains when it first realizes there is a problem, not at the point where the problem actually occurred. However, the line number does indicate the last possible line where the error could have occurred--the real error may be earlier, but it will never be later. 

Finally, have hope! You'll eventually get really really good at figuring out what the compiler actually means. There will be a few error messages that today seem completely cryptic, even once you know what the real problem was, that in a few months time you will know like an old (if confused) friend. I've actually written more about this in the past; if you want more detailed help, check out my article on deciphering compiler and linker errors. (Interested in learning how to deal with these errors and other programming problems in a more guided way? Consider taking a course in computer science with our sponsor, Creighton online.)


Debugging


Debugging is a critical skill, but most people aren't born with a mastery of it. Debugging is hard for a few reasons; first, it's frustrating. You just wrote a bunch of code, and it doesn't work even though you're pretty sure it should. Damn! Second, it can be tedious; debugging often requires a lot of effort to narrow in on the problem, and until you have some practice, it can be hard to efficiently narrow it down. One type of problem, segmentation faults, are a particularly good example of this--many programmers try to narrow in on the problem by adding in print statements to show how far the program gets before crashing, even though the debugger can tell them exactly where the problem occurred. Which actually leads to the last problem--debuggers are yet another confused, difficult to set up tool, just like the compiler. If all you want is your program to work, the last thing you want to do is go set up ANOTHER tool just to find out why. 

To learn more about debugging techniques, check out this article on debugging strategies.


Designing a Program


When you're just starting to program, design is a real challenge. Knowing how to think about programming is one piece, but the other piece is knowing how to put programs together in a way that makes it easy to modify them later. Ideas like "commenting your code", "encapsulation and data hiding" and "inheritance" don't really mean anything when you haven't felt the pain of not having them. The problem is that program design is all about making things easier for your future self--sort of like eating your vegetables. Bad designs make your program inflexible to future changes, or impossible to understand after you've written. Frequently, bad design exposes too many details of how something is implemented, so that every part of the program has to know all the details of each other section of the program.

One great example is writing a checkers game. You need some way to represent the board--so you pick one. A fixed-sized global array: int checkers_board[8][8]. Your accesses to the board all go directly through the array: checkers_board[x][y] = ....; Is there anything wrong with this approach? You betcha. Notice that I wrote your accesses to the board all go directly through the array. The board is the conceptual entity--the thing you care about. The array happens to be, at this particular moment, how you implement the board. Again, two things: the thing you represent, and the way you represent it. By making all accesses to the board use the array directly, you entangle the two concepts. What happens when you decide to change the way you represent the board? You have an awful lot of code to change. But what's the solution? 

If you create a function that performs the types of basic operations you perform on the checkers board (perhaps a get_piece_on_square() method and a set_piece_to_square() method), every access to the board can go through this interface. If you change the implementation, the interface is the same. And that's what people mean when they talk about "encapsulation" and "data hiding". Many aspects of program design, such as inheritance, are there to allow you to hide the details of an implementation (the array) of a particular interface or concept (the board).