This commit is contained in:
bigheadbh 2021-03-03 12:10:04 -03:00 committed by Felipe
parent f19601aedf
commit 5554ab7587
259 changed files with 195481 additions and 195481 deletions

8
.gitignore vendored
View File

@ -1,4 +1,4 @@
*.exe *.exe
*.class *.class
*.o *.o

View File

@ -1,16 +1,16 @@
# AEDII # AEDII
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II
## Ajuda ## Ajuda
[Readme.md com os principais comandos.](ajuda/) [Readme.md com os principais comandos.](ajuda/)
## fonte ## fonte
## labs ## labs
Ativdades dos laboratórios. Ativdades dos laboratórios.
## tps ## tps

View File

@ -1,91 +1,91 @@
## ALGUNS ARQUIVOS INTERESSANTES ## ALGUNS ARQUIVOS INTERESSANTES
* ~/.bash_history - Lista de comandos executados * ~/.bash_history - Lista de comandos executados
* ~/.vimrc - Configuracoes do VIM * ~/.vimrc - Configuracoes do VIM
* ~/.profile - Configuracoes do seu Usuario * ~/.profile - Configuracoes do seu Usuario
## PRINCIPAIS COMANDOS NO VIM ## PRINCIPAIS COMANDOS NO VIM
* i - Abre o modo de insercao * i - Abre o modo de insercao
* ESC - Fecha o modo de insercao * ESC - Fecha o modo de insercao
* :w - Salvar * :w - Salvar
* :q - Sair * :q - Sair
* :q! - Forcar saida * :q! - Forcar saida
* :wq! - Salvar e forcar a saida * :wq! - Salvar e forcar a saida
* ? PALAVRA - Procurar as ocorrencias de PALAVRA * ? PALAVRA - Procurar as ocorrencias de PALAVRA
* :%s/STRING_OLD/STRING_NEW/gc - Substrituir a STRING_OLD pela STRING_NEW * :%s/STRING_OLD/STRING_NEW/gc - Substrituir a STRING_OLD pela STRING_NEW
* yy - Copiar linha * yy - Copiar linha
* NUMEROyy - Copiar NUMERO linhas * NUMEROyy - Copiar NUMERO linhas
* dd - Excluir linha * dd - Excluir linha
* NUMEROdd - Excluir NUMERO linhas * NUMEROdd - Excluir NUMERO linhas
* dw - Excluir palavra * dw - Excluir palavra
* NUMEROdw - Excluir NUMERO palavras * NUMEROdw - Excluir NUMERO palavras
* p - Colar * p - Colar
* :sp ARQUIVO - Abre o arquivo ARQUIVO * :sp ARQUIVO - Abre o arquivo ARQUIVO
* ww - Alternar entre os arquivos abertos * ww - Alternar entre os arquivos abertos
* CTRL+V - Abre o modo de visualizacao * CTRL+V - Abre o modo de visualizacao
## ALGUNS COMANDOS PARA O MODO SHELL DO LINUX ## ALGUNS COMANDOS PARA O MODO SHELL DO LINUX
* man * man
* exit * exit
* cd * cd
* ls * ls
* ls -l -t -h * ls -l -t -h
* rm * rm
* cp * cp
* mkdir * mkdir
* clear * clear
* grep * grep
* grep "PALAVRA" ARQUIVO * grep "PALAVRA" ARQUIVO
* diff * diff
* diff ARQUIVO1 ARQUIVO2 * diff ARQUIVO1 ARQUIVO2
* ssh * ssh
* sftp * sftp
* wget * wget
* chmod * chmod
* javac * javac
* java * java
* tar -zcvf arquivo.tar.gz pasta * tar -zcvf arquivo.tar.gz pasta
* tar -zxvf arquivo.tar.gz * tar -zxvf arquivo.tar.gz
## COMPILAR E EXECUTAR PROGRAMA JAVA EM LINHA DE COMANDO ## COMPILAR E EXECUTAR PROGRAMA JAVA EM LINHA DE COMANDO
1) Compilar: 1) Compilar:
> javac Programa.java > javac Programa.java
2) Executar: 2) Executar:
> java Programa > java Programa
3) Executar alterando entrada padrao: 3) Executar alterando entrada padrao:
> java Programa < entrada.in > java Programa < entrada.in
4) Executar alterando saida padrao: 4) Executar alterando saida padrao:
> java Programa > saida.in > java Programa > saida.in
5) Executar alterando entrada/saida padrao: 5) Executar alterando entrada/saida padrao:
> java Programa < entrada.in > saida.in > java Programa < entrada.in > saida.in
## COMPILAR E EXECUTAR PROGRAMA C++ EM LINHA DE COMANDO ## COMPILAR E EXECUTAR PROGRAMA C++ EM LINHA DE COMANDO
1) Compilar: 1) Compilar:
> g++ fonte.cc -o objeto > g++ fonte.cc -o objeto
2) Executar: 2) Executar:
> ./objeto > ./objeto
3) Executar alterando entrada padrao: 3) Executar alterando entrada padrao:
> ./objeto < entrada.in > ./objeto < entrada.in
4) Executar alterando saida padrao: 4) Executar alterando saida padrao:
> ./objeto > saida.in > ./objeto > saida.in
5) Executar alterando entrada/saida padrao: 5) Executar alterando entrada/saida padrao:
> ./objeto < entrada.in > saida.in > ./objeto < entrada.in > saida.in
## GDB ## GDB
1) Chamar o gdb 1) Chamar o gdb
> gdb objeto > gdb objeto
2) Executar no gdb 2) Executar no gdb
> run > run
3) Acessar a pilha de chamadas 3) Acessar a pilha de chamadas
> bt > bt

View File

@ -1,206 +1,206 @@
import java.io.*; import java.io.*;
import java.util.Formatter; import java.util.Formatter;
import java.util.Scanner; import java.util.Scanner;
import java.io.File; import java.io.File;
import java.nio.charset.*; import java.nio.charset.*;
public class Arq public class Arq
{ {
private static String nomeArquivo = ""; private static String nomeArquivo = "";
private static String charsetArquivo = "ISO-8859-1"; private static String charsetArquivo = "ISO-8859-1";
private static boolean write = false, read = false; private static boolean write = false, read = false;
private static Formatter saida = null; private static Formatter saida = null;
private static Scanner entrada = null; private static Scanner entrada = null;
public static boolean openWrite(String nomeArq, String charset) { public static boolean openWrite(String nomeArq, String charset) {
boolean resp = false; boolean resp = false;
close(); close();
try{ try{
saida = new Formatter(nomeArq, charset); saida = new Formatter(nomeArq, charset);
nomeArquivo = nomeArq; nomeArquivo = nomeArq;
resp = write = true; resp = write = true;
} catch (Exception e) {} } catch (Exception e) {}
return resp; return resp;
} }
public static boolean openWrite(String nomeArq) { public static boolean openWrite(String nomeArq) {
return openWrite(nomeArq, charsetArquivo); return openWrite(nomeArq, charsetArquivo);
} }
public static boolean openWriteClose(String nomeArq, String charset, String conteudo) { public static boolean openWriteClose(String nomeArq, String charset, String conteudo) {
boolean resp = openWrite(nomeArq, charset); boolean resp = openWrite(nomeArq, charset);
if(resp == true){ if(resp == true){
println(conteudo); println(conteudo);
close(); close();
} }
return resp; return resp;
} }
public static boolean openWriteClose(String nomeArq, String conteudo) { public static boolean openWriteClose(String nomeArq, String conteudo) {
return openWriteClose(nomeArq, charsetArquivo, conteudo); return openWriteClose(nomeArq, charsetArquivo, conteudo);
} }
public static boolean openRead(String nomeArq) { public static boolean openRead(String nomeArq) {
return openRead(nomeArq, charsetArquivo); return openRead(nomeArq, charsetArquivo);
} }
public static boolean openRead(String nomeArq, String charset) { public static boolean openRead(String nomeArq, String charset) {
boolean resp = false; boolean resp = false;
close(); close();
try{ try{
entrada = new Scanner(new File(nomeArq), charset); entrada = new Scanner(new File(nomeArq), charset);
nomeArquivo = nomeArq; nomeArquivo = nomeArq;
resp = read = true; resp = read = true;
} catch (Exception e) {} } catch (Exception e) {}
return resp; return resp;
} }
public static String openReadClose(String nomeArq){ public static String openReadClose(String nomeArq){
openRead(nomeArq); openRead(nomeArq);
String resp = readAll(); String resp = readAll();
close(); close();
return resp; return resp;
} }
public static void close() { public static void close() {
if(write == true){ if(write == true){
saida.close(); saida.close();
} }
if(read == true){ if(read == true){
entrada.close(); entrada.close();
} }
write = read = false; write = read = false;
nomeArquivo = ""; nomeArquivo = "";
charsetArquivo = "ISO-8859-1"; charsetArquivo = "ISO-8859-1";
} }
public static long length(){ public static long length(){
long resp = -1; long resp = -1;
if(read != write){ if(read != write){
File file = new File(nomeArquivo); File file = new File(nomeArquivo);
resp = file.length(); resp = file.length();
} }
return resp; return resp;
} }
public static void print(int x){ public static void print(int x){
if(write == true){ if(write == true){
saida.format( "%d", x); saida.format( "%d", x);
} }
} }
public static void print(double x){ public static void print(double x){
if(write == true){ if(write == true){
saida.format( "%f", x); saida.format( "%f", x);
} }
} }
public static void print(String x){ public static void print(String x){
if(write == true){ if(write == true){
saida.format( "%s", x); saida.format( "%s", x);
} }
} }
public static void print(boolean x){ public static void print(boolean x){
if(write == true){ if(write == true){
saida.format( "%s", ((x) ? "true" : "false")); saida.format( "%s", ((x) ? "true" : "false"));
} }
} }
public static void print(char x){ public static void print(char x){
if(write == true){ if(write == true){
saida.format( "%c", x); saida.format( "%c", x);
} }
} }
public static void println(int x){ public static void println(int x){
if(write == true){ if(write == true){
saida.format( "%d\n", x); saida.format( "%d\n", x);
} }
} }
public static void println(double x){ public static void println(double x){
if(write == true){ if(write == true){
saida.format( "%f\n", x); saida.format( "%f\n", x);
} }
} }
public static void println(String x){ public static void println(String x){
if(write == true){ if(write == true){
saida.format( "%s\n", x); saida.format( "%s\n", x);
} }
} }
public static void println(boolean x){ public static void println(boolean x){
if(write == true){ if(write == true){
saida.format( "%s\n", ((x) ? "true" : "false")); saida.format( "%s\n", ((x) ? "true" : "false"));
} }
} }
public static void println(char x){ public static void println(char x){
if(write == true){ if(write == true){
saida.format( "%c\n", x); saida.format( "%c\n", x);
} }
} }
public static int readInt(){ public static int readInt(){
int resp = -1; int resp = -1;
try{ try{
resp = entrada.nextInt(); resp = entrada.nextInt();
} catch (Exception e) {} } catch (Exception e) {}
return resp; return resp;
} }
public static char readChar(){ public static char readChar(){
char resp = ' '; char resp = ' ';
try{ try{
resp = (char)entrada.nextByte(); resp = (char)entrada.nextByte();
} catch (Exception e) {} } catch (Exception e) {}
return resp; return resp;
} }
public static double readDouble(){ public static double readDouble(){
double resp = -1; double resp = -1;
try{ try{
resp = Double.parseDouble(readString().replace(",",".")); resp = Double.parseDouble(readString().replace(",","."));
} catch (Exception e) {} } catch (Exception e) {}
return resp; return resp;
} }
public static String readString(){ public static String readString(){
String resp = ""; String resp = "";
try{ try{
resp = entrada.next(); resp = entrada.next();
} catch (Exception e) { System.out.println(e.getMessage()); } } catch (Exception e) { System.out.println(e.getMessage()); }
return resp; return resp;
} }
public static boolean readBoolean(){ public static boolean readBoolean(){
boolean resp = false; boolean resp = false;
try{ try{
resp = (entrada.next().equals("true")) ? true : false; resp = (entrada.next().equals("true")) ? true : false;
} catch (Exception e) {} } catch (Exception e) {}
return resp; return resp;
} }
public static String readLine(){ public static String readLine(){
String resp = ""; String resp = "";
try{ try{
resp = entrada.nextLine(); resp = entrada.nextLine();
} catch (Exception e) { System.out.println(e.getMessage()); } } catch (Exception e) { System.out.println(e.getMessage()); }
return resp; return resp;
} }
public static boolean hasNext(){ public static boolean hasNext(){
return entrada.hasNext(); return entrada.hasNext();
} }
public static String readAll(){ public static String readAll(){
String resp = ""; String resp = "";
while(hasNext()){ while(hasNext()){
resp += (readLine() + "\n"); resp += (readLine() + "\n");
} }
return resp; return resp;
} }
} }

View File

@ -1,40 +1,40 @@
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
class ExemploURL { class ExemploURL {
public static String getHtml(String endereco){ public static String getHtml(String endereco){
URL url; URL url;
InputStream is = null; InputStream is = null;
BufferedReader br; BufferedReader br;
String resp = "", line; String resp = "", line;
try { try {
url = new URL(endereco); url = new URL(endereco);
is = url.openStream(); // throws an IOException is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is)); br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
resp += line + "\n"; resp += line + "\n";
} }
} catch (MalformedURLException mue) { } catch (MalformedURLException mue) {
mue.printStackTrace(); mue.printStackTrace();
} catch (IOException ioe) { } catch (IOException ioe) {
ioe.printStackTrace(); ioe.printStackTrace();
} }
try { try {
is.close(); is.close();
} catch (IOException ioe) { } catch (IOException ioe) {
// nothing to see here // nothing to see here
} }
return resp; return resp;
} }
public static void main(String[] args) { public static void main(String[] args) {
String endereco, html; String endereco, html;
endereco = "http://maratona.crc.pucminas.br/series/Friends.html"; endereco = "http://maratona.crc.pucminas.br/series/Friends.html";
html = getHtml(endereco); html = getHtml(endereco);
System.out.print(html); System.out.print(html);
} }
} }

View File

@ -1,252 +1,252 @@
import java.io.*; import java.io.*;
import java.nio.charset.*; import java.nio.charset.*;
class MyIO { class MyIO {
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1"))); private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")));
private static String charset = "ISO-8859-1"; private static String charset = "ISO-8859-1";
public static void setCharset(String charset_){ public static void setCharset(String charset_){
charset = charset_; charset = charset_;
in = new BufferedReader(new InputStreamReader(System.in, Charset.forName(charset))); in = new BufferedReader(new InputStreamReader(System.in, Charset.forName(charset)));
} }
public static void print(){ public static void print(){
} }
public static void print(int x){ public static void print(int x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(x); out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void print(float x){ public static void print(float x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(x); out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void print(double x){ public static void print(double x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(x); out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void print(String x){ public static void print(String x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(x); out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void print(boolean x){ public static void print(boolean x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(x); out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void print(char x){ public static void print(char x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(x); out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void println(){ public static void println(){
} }
public static void println(int x){ public static void println(int x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.println(x); out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void println(float x){ public static void println(float x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.println(x); out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void println(double x){ public static void println(double x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.println(x); out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void println(String x){ public static void println(String x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.println(x); out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void println(boolean x){ public static void println(boolean x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.println(x); out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void println(char x){ public static void println(char x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.println(x); out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static void printf(String formato, double x){ public static void printf(String formato, double x){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.printf(formato, x);// "%.2f" out.printf(formato, x);// "%.2f"
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
} }
public static double readDouble(){ public static double readDouble(){
double d = -1; double d = -1;
try{ try{
d = Double.parseDouble(readString().trim().replace(",",".")); d = Double.parseDouble(readString().trim().replace(",","."));
}catch(Exception e){} }catch(Exception e){}
return d; return d;
} }
public static double readDouble(String str){ public static double readDouble(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readDouble(); return readDouble();
} }
public static float readFloat(){ public static float readFloat(){
return (float) readDouble(); return (float) readDouble();
} }
public static float readFloat(String str){ public static float readFloat(String str){
return (float) readDouble(str); return (float) readDouble(str);
} }
public static int readInt(){ public static int readInt(){
int i = -1; int i = -1;
try{ try{
i = Integer.parseInt(readString().trim()); i = Integer.parseInt(readString().trim());
}catch(Exception e){} }catch(Exception e){}
return i; return i;
} }
public static int readInt(String str){ public static int readInt(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readInt(); return readInt();
} }
public static String readString(){ public static String readString(){
String s = ""; String s = "";
char tmp; char tmp;
try{ try{
do{ do{
tmp = (char)in.read(); tmp = (char)in.read();
if(tmp != '\n' && tmp != ' ' && tmp != 13){ if(tmp != '\n' && tmp != ' ' && tmp != 13){
s += tmp; s += tmp;
} }
}while(tmp != '\n' && tmp != ' '); }while(tmp != '\n' && tmp != ' ');
}catch(IOException ioe){ }catch(IOException ioe){
System.out.println("lerPalavra: " + ioe.getMessage()); System.out.println("lerPalavra: " + ioe.getMessage());
} }
return s; return s;
} }
public static String readString(String str){ public static String readString(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readString(); return readString();
} }
public static String readLine(){ public static String readLine(){
String s = ""; String s = "";
char tmp; char tmp;
try{ try{
do{ do{
tmp = (char)in.read(); tmp = (char)in.read();
if(tmp != '\n' && tmp != 13){ if(tmp != '\n' && tmp != 13){
s += tmp; s += tmp;
} }
}while(tmp != '\n'); }while(tmp != '\n');
}catch(IOException ioe){ }catch(IOException ioe){
System.out.println("lerPalavra: " + ioe.getMessage()); System.out.println("lerPalavra: " + ioe.getMessage());
} }
return s; return s;
} }
public static String readLine(String str){ public static String readLine(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readLine(); return readLine();
} }
public static char readChar(){ public static char readChar(){
char resp = ' '; char resp = ' ';
try{ try{
resp = (char)in.read(); resp = (char)in.read();
}catch(Exception e){} }catch(Exception e){}
return resp; return resp;
} }
public static char readChar(String str){ public static char readChar(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readChar(); return readChar();
} }
public static boolean readBoolean(){ public static boolean readBoolean(){
boolean resp = false; boolean resp = false;
String str = ""; String str = "";
try{ try{
str = readString(); str = readString();
}catch(Exception e){} }catch(Exception e){}
if(str.equals("true") || str.equals("TRUE") || str.equals("t") || str.equals("1") || if(str.equals("true") || str.equals("TRUE") || str.equals("t") || str.equals("1") ||
str.equals("verdadeiro") || str.equals("VERDADEIRO") || str.equals("V")){ str.equals("verdadeiro") || str.equals("VERDADEIRO") || str.equals("V")){
resp = true; resp = true;
} }
return resp; return resp;
} }
public static boolean readBoolean(String str){ public static boolean readBoolean(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readBoolean(); return readBoolean();
} }
public static void pause(){ public static void pause(){
try{ try{
in.read(); in.read();
}catch(Exception e){} }catch(Exception e){}
} }
public static void pause(String str){ public static void pause(String str){
try { try {
PrintStream out = new PrintStream(System.out, true, charset); PrintStream out = new PrintStream(System.out, true, charset);
out.print(str); out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); } }catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
pause(); pause();
} }
} }

View File

@ -1,18 +1,18 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r"); FILE *p = fopen ("teste.txt", "r");
// testa se o arquivo foi aberto com sucesso // testa se o arquivo foi aberto com sucesso
if (p != NULL) { if (p != NULL) {
printf ("Arquivo foi aberto com sucesso.\n\n"); printf ("Arquivo foi aberto com sucesso.\n\n");
fclose(p); fclose(p);
} else { } else {
printf ("Nao foi possivel abrir o arquivo.\n\n"); printf ("Nao foi possivel abrir o arquivo.\n\n");
} }
return 0; return 0;
} }

View File

@ -1,19 +1,19 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r"); FILE *p = fopen ("teste.txt", "r");
// testa se o arquivo foi aberto com sucesso // testa se o arquivo foi aberto com sucesso
if (p != NULL) { if (p != NULL) {
printf ("Arquivo foi aberto com sucesso.\n\n"); printf ("Arquivo foi aberto com sucesso.\n\n");
fclose(p); fclose(p);
} else { } else {
printf ("Nao foi possivel abrir o arquivo.\n\n"); printf ("Nao foi possivel abrir o arquivo.\n\n");
} }
return 0; return 0;
} }

View File

@ -1,21 +1,21 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen (argv[1], "r"); FILE *p = fopen (argv[1], "r");
int ch; int ch;
if (p != NULL) { if (p != NULL) {
do { do {
ch = fgetc(p); ch = fgetc(p);
if(ch != EOF){ if(ch != EOF){
printf( "%i %c\n", ch, (char)ch); printf( "%i %c\n", ch, (char)ch);
//printf( "%c", (char)ch); //printf( "%c", (char)ch);
} }
} while (ch != EOF); } while (ch != EOF);
fclose(p); fclose(p);
} }
return 0; return 0;
} }

View File

@ -1,23 +1,23 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r"); FILE *p = fopen ("teste.txt", "r");
char str[100+1]; char str[100+1];
char* resp; char* resp;
int i = 0; int i = 0;
if (p != NULL) { if (p != NULL) {
do { do {
resp = fgets(str, 100, p); resp = fgets(str, 100, p);
if(resp != NULL){ if(resp != NULL){
printf("(%d) %s", i, str); printf("(%d) %s", i, str);
i++; i++;
} }
} while (resp != NULL); } while (resp != NULL);
fclose(p); fclose(p);
} }
return 0; return 0;
} }

View File

@ -1,12 +1,12 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "w"); FILE *p = fopen ("teste.txt", "w");
fputc('M', p); fputc('M', p);
fclose(p); fclose(p);
return 0; return 0;
} }

View File

@ -1,11 +1,11 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "w"); FILE *p = fopen ("teste.txt", "w");
fputs("Algoritmos e Estruturas de Dados II", p); fputs("Algoritmos e Estruturas de Dados II", p);
fclose(p); fclose(p);
return 0; return 0;
} }

View File

@ -1,19 +1,19 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *in = fopen ("teste.txt", "r"), FILE *in = fopen ("teste.txt", "r"),
*out = fopen ("copia.txt", "w"); *out = fopen ("copia.txt", "w");
while ( !feof(in) ) { while ( !feof(in) ) {
char ch = getc(in); char ch = getc(in);
if ( !feof(in)) { if ( !feof(in)) {
putc(ch, out); putc(ch, out);
} }
} }
fclose(in); fclose(in);
fclose(out); fclose(out);
return 0; return 0;
} }

View File

@ -1,24 +1,24 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p; FILE *p;
double d = 12.23; double d = 12.23;
int i = 101; int i = 101;
long l = 123023L; long l = 123023L;
if ((p = fopen("teste.txt", "wb")) == NULL) { if ((p = fopen("teste.txt", "wb")) == NULL) {
printf ("arquivo nao pode ser aberto\n"); printf ("arquivo nao pode ser aberto\n");
exit(1); exit(1);
} }
fwrite(&d, sizeof(double), 1, p); fwrite(&d, sizeof(double), 1, p);
fwrite(&i, sizeof(int), 1, p); fwrite(&i, sizeof(int), 1, p);
fwrite(&l, sizeof(long), 1, p); fwrite(&l, sizeof(long), 1, p);
fclose(p); fclose(p);
return 0; return 0;
} }

View File

@ -1,25 +1,25 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p; FILE *p;
double d; double d;
int i; int i;
long l; long l;
if ((p = fopen("teste.txt", "rb")) == NULL) { if ((p = fopen("teste.txt", "rb")) == NULL) {
printf ("arquivo nao pode ser aberto\n"); printf ("arquivo nao pode ser aberto\n");
exit(1); exit(1);
} }
fread(&d, sizeof(double), 1, p); fread(&d, sizeof(double), 1, p);
fread (&i, sizeof(int), 1, p); fread (&i, sizeof(int), 1, p);
fread (&l, sizeof(long), 1, p); fread (&l, sizeof(long), 1, p);
printf("%f %d %ld", d, i, l); printf("%f %d %ld", d, i, l);
fclose(p); fclose(p);
return 0; return 0;
} }

View File

@ -1,35 +1,35 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
typedef struct cliente { typedef struct cliente {
char nome[100]; char nome[100];
int codigo; int codigo;
} cliente; } cliente;
void escrever(char*); void escrever(char*);
void ler(char*); void ler(char*);
void main(int argc, char** argv){ void main(int argc, char** argv){
escrever("teste.txt"); escrever("teste.txt");
ler("teste.txt"); ler("teste.txt");
} }
void escrever(char* nomeArq){ void escrever(char* nomeArq){
cliente c1, c2; cliente c1, c2;
strcat(c1.nome, "Ze da Silva"); c1.codigo = 1; strcat(c1.nome, "Ze da Silva"); c1.codigo = 1;
strcat(c2.nome, "Lele da Cuca"); c2.codigo = 11; strcat(c2.nome, "Lele da Cuca"); c2.codigo = 11;
FILE *p = fopen(nomeArq, "ab"); FILE *p = fopen(nomeArq, "ab");
fwrite(&c1, sizeof(cliente), 1, p); fwrite(&c1, sizeof(cliente), 1, p);
fwrite(&c2, sizeof(cliente), 1, p); fwrite(&c2, sizeof(cliente), 1, p);
fclose(p); fclose(p);
} }
void ler(char* nomeArq){ void ler(char* nomeArq){
cliente c1, c2; cliente c1, c2;
FILE *p = fopen(nomeArq, "rb"); FILE *p = fopen(nomeArq, "rb");
fread(&c1, sizeof(cliente), 1, p); fread(&c1, sizeof(cliente), 1, p);
fread(&c2, sizeof(cliente), 1, p); fread(&c2, sizeof(cliente), 1, p);
fclose(p); fclose(p);
printf("%s -- %d\n", c1.nome, c1.codigo); printf("%s -- %d\n", c1.nome, c1.codigo);
printf("%s -- %d\n", c2.nome, c2.codigo); printf("%s -- %d\n", c2.nome, c2.codigo);
} }

View File

@ -1,23 +1,23 @@
#include <stdio.h> #include <stdio.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen("teste.txt", "wb+"); FILE *p = fopen("teste.txt", "wb+");
double d = 12.23; int i = 101; long l = 123023L; double d = 12.23; int i = 101; long l = 123023L;
fwrite(&d, sizeof(double), 1, p); fwrite(&d, sizeof(double), 1, p);
fwrite(&i, sizeof(int), 1, p); fwrite(&i, sizeof(int), 1, p);
fwrite(&l, sizeof(long), 1, p); fwrite(&l, sizeof(long), 1, p);
rewind(p); rewind(p);
fread(&d, sizeof(double), 1, p); fread(&d, sizeof(double), 1, p);
fread (&i, sizeof(int), 1, p); fread (&i, sizeof(int), 1, p);
fread (&l, sizeof(long), 1, p); fread (&l, sizeof(long), 1, p);
printf("%f %d %ld", d, i, l); printf("%f %d %ld", d, i, l);
fclose(p); fclose(p);
return 0; return 0;
} }

View File

@ -1,22 +1,22 @@
#include <stdio.h> #include <stdio.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
FILE *p = fopen("teste.txt", "wb+"); FILE *p = fopen("teste.txt", "wb+");
int registro, valor, i; int registro, valor, i;
for (i = valor = 0; i < 10; i++, valor = i * 10) fwrite(&valor, sizeof(int), 1, p); for (i = valor = 0; i < 10; i++, valor = i * 10) fwrite(&valor, sizeof(int), 1, p);
int numRegistro = ftell(p) / sizeof (int); int numRegistro = ftell(p) / sizeof (int);
do { do {
printf ("\nEscolha um numero entre zero e %i: ", numRegistro-1); printf ("\nEscolha um numero entre zero e %i: ", numRegistro-1);
scanf("%d", &registro); scanf("%d", &registro);
} while (registro < 0 || registro >= numRegistro); } while (registro < 0 || registro >= numRegistro);
fseek(p, registro * sizeof(int), SEEK_SET); fseek(p, registro * sizeof(int), SEEK_SET);
fread(&valor, sizeof(int), 1, p); fread(&valor, sizeof(int), 1, p);
fclose(p); fclose(p);
printf ("\nValor: %d\n\n", valor); printf ("\nValor: %d\n\n", valor);
return 0; return 0;
} }

View File

@ -1,117 +1,117 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
//============================================================================= //=============================================================================
void gravar_arquivo_texto(){ void gravar_arquivo_texto(){
// ABRIR O ARQUIVO // ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.txt", "w"); FILE *arq = fopen("arquivo.txt", "w");
if(arq == NULL){ if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n"); printf("Erro ao tentar abrir o arquivo!\n");
return; return;
} }
// ESCREVER NO ARQUIVO // ESCREVER NO ARQUIVO
fprintf(arq, "%s\t", "Algoritmos"); fprintf(arq, "%s\t", "Algoritmos");
fprintf(arq, "%d\t", 1); fprintf(arq, "%d\t", 1);
fprintf(arq, "%f\t", 5.3); fprintf(arq, "%f\t", 5.3);
fprintf(arq, "%c\t", 'X'); fprintf(arq, "%c\t", 'X');
// FECHA O ARQUIVO // FECHA O ARQUIVO
fclose(arq); fclose(arq);
} }
//============================================================================= //=============================================================================
void ler_texto_texto(){ void ler_texto_texto(){
char texto[12], caracter; char texto[12], caracter;
int inteiro; int inteiro;
float real; float real;
// ABRIR O ARQUIVO // ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.txt", "r"); FILE *arq = fopen("arquivo.txt", "r");
if(arq == NULL){ if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n"); printf("Erro ao tentar abrir o arquivo!\n");
return; return;
} }
// LE O ARQUIVO // LE O ARQUIVO
fscanf(arq, "%99[^\t]\t", &texto); // LER STRING fscanf(arq, "%99[^\t]\t", &texto); // LER STRING
fscanf(arq, "%d\t", &inteiro); fscanf(arq, "%d\t", &inteiro);
fscanf(arq, "%f\t", &real); fscanf(arq, "%f\t", &real);
fscanf(arq, "%c\t", &caracter); fscanf(arq, "%c\t", &caracter);
// FECHA O ARQUIVO // FECHA O ARQUIVO
fclose(arq); fclose(arq);
printf("texto: %s\n", texto); printf("texto: %s\n", texto);
printf("inteiro: %d\n", inteiro); printf("inteiro: %d\n", inteiro);
printf("real: %f\n", real); printf("real: %f\n", real);
printf("caracter: %c\n", caracter); printf("caracter: %c\n", caracter);
} }
//============================================================================= //=============================================================================
void gravar_arquivo_binario(){ void gravar_arquivo_binario(){
char texto[12] = "Algoritmos", caracter = 'X'; char texto[12] = "Algoritmos", caracter = 'X';
int inteiro = 1; int inteiro = 1;
float real = 5.3; float real = 5.3;
// ABRIR O ARQUIVO // ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.bin", "wb"); FILE *arq = fopen("arquivo.bin", "wb");
if(arq == NULL){ if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n"); printf("Erro ao tentar abrir o arquivo!\n");
return; return;
} }
// ESCREVER NO ARQUIVO // ESCREVER NO ARQUIVO
fwrite(&texto, sizeof(char), 12, arq); fwrite(&texto, sizeof(char), 12, arq);
fwrite(&inteiro, sizeof(int), 1, arq); fwrite(&inteiro, sizeof(int), 1, arq);
fwrite(&real, sizeof(float), 1, arq); fwrite(&real, sizeof(float), 1, arq);
fwrite(&caracter,sizeof(char), 1, arq); fwrite(&caracter,sizeof(char), 1, arq);
// FECHA O ARQUIVO // FECHA O ARQUIVO
fclose(arq); fclose(arq);
} }
//============================================================================= //=============================================================================
void ler_texto_binario(){ void ler_texto_binario(){
char texto[12], caracter; char texto[12], caracter;
int inteiro; int inteiro;
float real; float real;
// ABRIR O ARQUIVO // ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.bin", "rb"); FILE *arq = fopen("arquivo.bin", "rb");
if(arq == NULL){ if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n"); printf("Erro ao tentar abrir o arquivo!\n");
return; return;
} }
// LE O ARQUIVO // LE O ARQUIVO
fread(&texto, sizeof(char), 12, arq); fread(&texto, sizeof(char), 12, arq);
fread(&inteiro, sizeof(int), 1, arq); fread(&inteiro, sizeof(int), 1, arq);
fread(&real, sizeof(float), 1, arq); fread(&real, sizeof(float), 1, arq);
fread(&caracter,sizeof(char), 1, arq); fread(&caracter,sizeof(char), 1, arq);
// FECHA O ARQUIVO // FECHA O ARQUIVO
fclose(arq); fclose(arq);
printf("texto: %s\n", texto); printf("texto: %s\n", texto);
printf("inteiro: %d\n", inteiro); printf("inteiro: %d\n", inteiro);
printf("real: %f\n", real); printf("real: %f\n", real);
printf("caracter: %c\n", caracter); printf("caracter: %c\n", caracter);
} }
//============================================================================= //=============================================================================
int main(){ int main(){
gravar_arquivo_texto(); gravar_arquivo_texto();
ler_texto_texto(); ler_texto_texto();
gravar_arquivo_binario(); gravar_arquivo_binario();
ler_texto_binario(); ler_texto_binario();
return 1; return 1;
} }

View File

@ -1,14 +1,14 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
//============================================================================= //=============================================================================
// EXEMPLO DE UTILIZAÇÃO DOS ARGUMENTOS PASSADOS PARA O MAIN // EXEMPLO DE UTILIZAÇÃO DOS ARGUMENTOS PASSADOS PARA O MAIN
int main(int argc, char *argv[]){ int main(int argc, char *argv[]){
int i; int i;
for (i = 0; i < argc; i++) for (i = 0; i < argc; i++)
printf("%d Parametro: %s\n", i, argv[i]); printf("%d Parametro: %s\n", i, argv[i]);
return 0; return 0;
} }
//============================================================================= //=============================================================================

View File

@ -1,22 +1,22 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(int argc, char *argv[]){ int main(int argc, char *argv[]){
char c; char c;
char s[100]; char s[100];
int i; int i;
double d; double d;
printf("\nEntre com um caractere: "); printf("\nEntre com um caractere: ");
scanf("%c", &c); scanf("%c", &c);
printf("\nEntre com uma palavra: "); printf("\nEntre com uma palavra: ");
scanf("%s", s); scanf("%s", s);
printf("\nEntre com um inteiro e um real: "); printf("\nEntre com um inteiro e um real: ");
scanf("%i%lf", &i, &d); scanf("%i%lf", &i, &d);
printf("\ninteiro(%d) real(%f) char(%c) s(%s)", i, d, c, s); printf("\ninteiro(%d) real(%f) char(%c) s(%s)", i, d, c, s);
return 0; return 0;
} }

View File

@ -1,6 +1,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
void helloWorld(void){ void helloWorld(void){
printf("Hello World!\n"); printf("Hello World!\n");
} }

View File

@ -1,6 +1,6 @@
#ifndef _H_TESTE #ifndef _H_TESTE
#define _H_TESTE #define _H_TESTE
void helloWorld(void); void helloWorld(void);
#endif #endif

View File

@ -1,8 +1,8 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "helloworld.h" #include "helloworld.h"
int main(){ int main(){
helloWorld(); helloWorld();
return (0); return (0);
} }

View File

@ -1,15 +1,15 @@
# My first makefile # My first makefile
all: printy all: printy
printy: main.o helloworld.o printy: main.o helloworld.o
gcc -o printy main.o helloworld.o gcc -o printy main.o helloworld.o
main.o: main.c helloworld.h main.o: main.c helloworld.h
gcc -o main.o main.c -c -W -Wall -ansi -pedantic gcc -o main.o main.c -c -W -Wall -ansi -pedantic
helloworld.o: helloworld.c helloworld.h helloworld.o: helloworld.c helloworld.h
gcc -o helloworld.o helloworld.c -c -W -Wall -ansi -pedantic gcc -o helloworld.o helloworld.c -c -W -Wall -ansi -pedantic
clean: clean:
rm -rf *.o *~ printy rm -rf *.o *~ printy

View File

@ -1,6 +1,6 @@
#include <stdio.h> #include <stdio.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
printf ("Ola pessoal!!!\n\n"); printf ("Ola pessoal!!!\n\n");
return 0; return 0;
} }

View File

@ -1,13 +1,13 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
int x = 10; int x = 10;
int * y = & x; int * y = & x;
printf("\n%i", x); printf("\n%i", x);
printf("\n%p", &x); printf("\n%p", &x);
printf("\n%p", y); printf("\n%p", y);
printf("\n%p", &y); printf("\n%p", &y);
printf("\n%i", *y); printf("\n%i", *y);
printf("\n"); printf("\n");
} }

View File

@ -1,19 +1,19 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
int x1 = 11, int x1 = 11,
x2 = 22, x2 = 22,
x3 = 33; x3 = 33;
int *p; int *p;
p = &x1; //p <- o endereço de x1 p = &x1; //p <- o endereço de x1
x2 = *p; //x2 <- o cont. do addr apont. por p x2 = *p; //x2 <- o cont. do addr apont. por p
*p = x3; //o cont. do addr apont. por p <- x3 *p = x3; //o cont. do addr apont. por p <- x3
p = &x3; //p <- o endereço de x3 p = &x3; //p <- o endereço de x3
*p = 0; //o cont. do addr apont. por p <- x3 *p = 0; //o cont. do addr apont. por p <- x3
printf("\ncont:%d %d %d %d", x1, x2, x3, *p); printf("\ncont:%d %d %d %d", x1, x2, x3, *p);
printf("\naddr:%p %p %p %p", &x1, &x2, &x3, p); printf("\naddr:%p %p %p %p", &x1, &x2, &x3, p);
printf("\n"); printf("\n");
} }

View File

@ -1,27 +1,27 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
int *x1; int *x1;
int x2; int x2;
int *x3; int *x3;
x1 = (int*) malloc (sizeof(int)); x1 = (int*) malloc (sizeof(int));
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3); printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
*x1 = 20; *x1 = 20;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3); printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x2 = *x1; x2 = *x1;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3); printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
*x3 = x2 * *x1; *x3 = x2 * *x1;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3); printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x3 = &x2; x3 = &x2;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3); printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x2 = 15; x2 = 15;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3); printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
printf("\n"); printf("\n");
} }

View File

@ -1,13 +1,13 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
double M [3][3]; double M [3][3];
double *p = M[0]; double *p = M[0];
for (int i = 0; i < pow(3, 2); i++, p++){ for (int i = 0; i < pow(3, 2); i++, p++){
*p=0.0; *p=0.0;
} }
} }

View File

@ -1,26 +1,26 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#define MAXTAM 10 #define MAXTAM 10
typedef struct Cliente { typedef struct Cliente {
int codigo; int codigo;
char nome[MAXTAM]; char nome[MAXTAM];
} Cliente; } Cliente;
int main (int argc, char** argv){ int main (int argc, char** argv){
char* p1 = (char*) malloc (sizeof(char)); char* p1 = (char*) malloc (sizeof(char));
int* p2 = (int*) malloc (sizeof(int)); int* p2 = (int*) malloc (sizeof(int));
float* p3 = (float*) malloc (sizeof(float)); float* p3 = (float*) malloc (sizeof(float));
Cliente* p4 = (Cliente*) malloc (sizeof(Cliente)); Cliente* p4 = (Cliente*) malloc (sizeof(Cliente));
int* p5 = (int*) malloc (MAXTAM * sizeof (int)); int* p5 = (int*) malloc (MAXTAM * sizeof (int));
Cliente* p6 =(Cliente*) malloc (MAXTAM * sizeof (Cliente)); Cliente* p6 =(Cliente*) malloc (MAXTAM * sizeof (Cliente));
free(p1); free(p1);
free(p2); free(p2);
free(p3); free(p3);
free(p4); free(p4);
free(p5); free(p5);
free(p6); free(p6);
} }

View File

@ -1,26 +1,26 @@
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#define MAXTAM 10 #define MAXTAM 10
typedef struct Cliente { typedef struct Cliente {
int codigo; int codigo;
char nome[MAXTAM]; char nome[MAXTAM];
} Cliente; } Cliente;
int main (int argc, char** argv){ int main (int argc, char** argv){
char* p1 = new char; char* p1 = new char;
int* p2 = new int; int* p2 = new int;
float* p3 = new float; float* p3 = new float;
Cliente* p4 = new Cliente; Cliente* p4 = new Cliente;
int* p5 = new int [MAXTAM]; int* p5 = new int [MAXTAM];
Cliente* p6 = new Cliente[MAXTAM]; Cliente* p6 = new Cliente[MAXTAM];
delete p1; delete p1;
delete p2; delete p2;
delete p3; delete p3;
delete p4; delete p4;
delete [] p5; delete [] p5;
delete [] p6; delete [] p6;
} }

View File

@ -1,24 +1,24 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define MAXTAM 100 #define MAXTAM 100
typedef struct Cliente { typedef struct Cliente {
int codigo; int codigo;
char nome[MAXTAM]; char nome[MAXTAM];
} Cliente; } Cliente;
int main (int argc, char** argv){ int main (int argc, char** argv){
Cliente registro; Cliente registro;
Cliente* ponteiro = (Cliente*) malloc (sizeof(Cliente)); Cliente* ponteiro = (Cliente*) malloc (sizeof(Cliente));
registro.codigo = 1; registro.codigo = 1;
strcpy(registro.nome, "AA"); strcpy(registro.nome, "AA");
printf("\nFuncionario (%i): %s", registro.codigo, registro.nome); printf("\nFuncionario (%i): %s", registro.codigo, registro.nome);
ponteiro->codigo = 2; ponteiro->codigo = 2;
strcpy(ponteiro->nome, "BB"); strcpy(ponteiro->nome, "BB");
printf("\nFuncionario (%i): %s", ponteiro->codigo, ponteiro->nome); printf("\nFuncionario (%i): %s", ponteiro->codigo, ponteiro->nome);
printf("\n"); printf("\n");
} }

View File

@ -1,30 +1,30 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
double a; double a;
double *p, *q; double *p, *q;
a = 3.14; a = 3.14;
printf("%f\n", a); printf("%f\n", a);
p = &a; p = &a;
*p = 2.718; *p = 2.718;
printf("%f\n", a); printf("%f\n", a);
a = 5; a = 5;
printf("%f\n", *p); printf("%f\n", *p);
p = NULL; p = NULL;
p = (double*) malloc(sizeof(double)); p = (double*) malloc(sizeof(double));
*p = 20; *p = 20;
q = p; q = p;
printf("%f\n", *p); printf("%f\n", *p);
printf("%f\n", a); printf("%f\n", a);
free(p); free(p);
printf("%f\n", *q); printf("%f\n", *q);
printf("\n"); printf("\n");
return 0; return 0;
} }

View File

@ -1,19 +1,19 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
int a[10], *b; int a[10], *b;
b = a; b = a;
b[5] = 100; b[5] = 100;
printf("\n%d -- %d", a[5], b[5]); printf("\n%d -- %d", a[5], b[5]);
b = (int*) malloc(10*sizeof(int)); b = (int*) malloc(10*sizeof(int));
b[7] = 100; b[7] = 100;
printf("\n%d -- %d", a[7], b[7]); printf("\n%d -- %d", a[7], b[7]);
printf("\n"); printf("\n");
//O comando a = b gera um erro de compilação //O comando a = b gera um erro de compilação
return 0; return 0;
} }

View File

@ -1,40 +1,40 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main (int argc, char** argv){ int main (int argc, char** argv){
int *x1; int *x1;
int x2; int x2;
int *x3; int *x3;
x1 = (int*) malloc(sizeof(int)); x1 = (int*) malloc(sizeof(int));
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
*x1 = 20; *x1 = 20;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = *x1; x2 = *x1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
*x3 = x2 * *x1; *x3 = x2 * *x1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x3 = &x2; x3 = &x2;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 15; x2 = 15;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 & 3; x2 = 13 & 3;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 | 3; x2 = 13 | 3;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 >> 1; x2 = 13 >> 1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 << 1; x2 = 13 << 1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3); printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
return 0; return 0;
} }

View File

@ -1,21 +1,21 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#define MAXTAM 10 #define MAXTAM 10
typedef struct Cliente { typedef struct Cliente {
int codigo; int codigo;
char nome[MAXTAM]; char nome[MAXTAM];
} Cliente; } Cliente;
int main (int argc, char** argv){ int main (int argc, char** argv){
Cliente c; Cliente c;
c.codigo = 5; c.codigo = 5;
Cliente *p = NULL; Cliente *p = NULL;
p = (Cliente*) malloc (sizeof(Cliente)); p = (Cliente*) malloc (sizeof(Cliente));
p->codigo = 6; p->codigo = 6;
Cliente *p2 = &c; Cliente *p2 = &c;
p2->codigo = 7; p2->codigo = 7;
return 0; return 0;
} }

View File

@ -1,20 +1,20 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
typedef struct Celula { typedef struct Celula {
int elemento; int elemento;
struct Celula *prox; struct Celula *prox;
} Celula; } Celula;
Celula *novaCelula(int elemento) { Celula *novaCelula(int elemento) {
Celula *nova = (Celula*) malloc(sizeof(Celula)); Celula *nova = (Celula*) malloc(sizeof(Celula));
nova->elemento = elemento; nova->elemento = elemento;
nova->prox = NULL; nova->prox = NULL;
return nova; return nova;
} }
int main (int argc, char** argv){ int main (int argc, char** argv){
Celula *tmp = novaCelula(3); Celula *tmp = novaCelula(3);
return 0; return 0;
} }

View File

@ -1,20 +1,20 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
typedef struct Elemento { typedef struct Elemento {
int valor; int valor;
} Elemento; } Elemento;
int main (int argc, char** argv){ int main (int argc, char** argv){
Elemento e1; Elemento e1;
Elemento* e2 = (Elemento*) malloc (3 * sizeof (Elemento)); Elemento* e2 = (Elemento*) malloc (3 * sizeof (Elemento));
Elemento e3[3]; Elemento e3[3];
Elemento** e4 = (Elemento**) malloc(3 * sizeof(Elemento*)); Elemento** e4 = (Elemento**) malloc(3 * sizeof(Elemento*));
e4[0] = (Elemento*) malloc(sizeof(Elemento*)); e4[0] = (Elemento*) malloc(sizeof(Elemento*));
e4[2] = (Elemento*) malloc(sizeof(Elemento*)); e4[2] = (Elemento*) malloc(sizeof(Elemento*));
e4[0]->valor = 7; e4[0]->valor = 7;
printf("\n%i -- %i\n", e4[0]->valor, e4[2]->valor); printf("\n%i -- %i\n", e4[0]->valor, e4[2]->valor);
return 0; return 0;
} }

View File

@ -1,26 +1,26 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
void terceiro(){ void terceiro(){
printf("3o - inicio e fim\n"); printf("3o - inicio e fim\n");
} }
void segundo(){ void segundo(){
printf("2o - inicio\n"); printf("2o - inicio\n");
terceiro(); terceiro();
printf("2o - fim\n"); printf("2o - fim\n");
} }
void primeiro(){ void primeiro(){
printf("1o - inicio\n"); printf("1o - inicio\n");
segundo(); segundo();
printf("1o - fim\n"); printf("1o - fim\n");
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
printf("main - inicio\n"); printf("main - inicio\n");
primeiro(); primeiro();
printf("main - fim\n"); printf("main - fim\n");
return 0; return 0;
} }

View File

@ -1,45 +1,45 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define bool int #define bool int
#define true 1 #define true 1
#define false 0 #define false 0
bool isUpper(char x){ bool isUpper(char x){
return (x >= 'A' && x <= 'Z'); return (x >= 'A' && x <= 'Z');
} }
int contMaiusculo(char* s){ int contMaiusculo(char* s){
int cont = 0; int cont = 0;
for(int i = 0; i < strlen(s); i++){ for(int i = 0; i < strlen(s); i++){
if(isUpper(s[i]) == true){ if(isUpper(s[i]) == true){
cont++; cont++;
} }
} }
return cont; return cont;
} }
int contMaiusculoRec(char* s, int i){ int contMaiusculoRec(char* s, int i){
int cont = 0; int cont = 0;
if(i < strlen(s)){ if(i < strlen(s)){
if(isUpper(s[i]) == true){ if(isUpper(s[i]) == true){
cont++; cont++;
} }
cont += contMaiusculoRec(s, i + 1); cont += contMaiusculoRec(s, i + 1);
} }
return cont; return cont;
} }
int contMaiusculoRecursivo(char* s){ int contMaiusculoRecursivo(char* s){
return contMaiusculoRec(s, 0); return contMaiusculoRec(s, 0);
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
printf("\nAlGoritmos e Estrutudas de Dados: %i", contMaiusculo("AlGoritmos e Estruturas de Dados")); printf("\nAlGoritmos e Estrutudas de Dados: %i", contMaiusculo("AlGoritmos e Estruturas de Dados"));
printf("\nAlGoritmos e Estruturas de Dados: %i", contMaiusculoRecursivo("AlGoritmos e Estruturas de Dados")); printf("\nAlGoritmos e Estruturas de Dados: %i", contMaiusculoRecursivo("AlGoritmos e Estruturas de Dados"));
return 0; return 0;
} }

View File

@ -1,18 +1,18 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int fatorial(int n){ int fatorial(int n){
int resp; int resp;
printf("\nfat (%i)", n); printf("\nfat (%i)", n);
resp = (n == 1) ? 1 : n * fatorial(n-1); resp = (n == 1) ? 1 : n * fatorial(n-1);
printf("\nfat n(%i): %i", n, resp); printf("\nfat n(%i): %i", n, resp);
return resp; return resp;
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
int n = 5; int n = 5;
printf("\nFATORIAL RECURSIVO(%i): %i", n, fatorial(n)); printf("\nFATORIAL RECURSIVO(%i): %i", n, fatorial(n));
return 0; return 0;
} }

View File

@ -1,18 +1,18 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int fibonacci(int n){ int fibonacci(int n){
int resp; int resp;
printf("\nfib (%i)", n); printf("\nfib (%i)", n);
resp = (n == 0 || n == 1) ? 1 : fibonacci(n-1) + fibonacci(n-2); resp = (n == 0 || n == 1) ? 1 : fibonacci(n-1) + fibonacci(n-2);
printf("\nfib n(%i): %i", n, resp); printf("\nfib n(%i): %i", n, resp);
return resp; return resp;
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
int n = 5; int n = 5;
printf("\nFIBONACCI RECURSIVO(%i): %i", n, fibonacci(n)); printf("\nFIBONACCI RECURSIVO(%i): %i", n, fibonacci(n));
return 0; return 0;
} }

View File

@ -1,34 +1,34 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int multiplicacaoRec(int a, int b, int i){ int multiplicacaoRec(int a, int b, int i){
int resp = 0; int resp = 0;
if(i < b){ if(i < b){
resp = a + multiplicacaoRec(a, b, i+1); resp = a + multiplicacaoRec(a, b, i+1);
} }
return resp; return resp;
} }
int multiplicacao(int a, int b){ int multiplicacao(int a, int b){
return multiplicacaoRec(a, b, 0); return multiplicacaoRec(a, b, 0);
} }
int multiplicacaoIt(int a, int b){ int multiplicacaoIt(int a, int b){
int resp = 0; int resp = 0;
for(int i = 0; i < b; i++){ for(int i = 0; i < b; i++){
resp = a + resp; resp = a + resp;
} }
return resp; return resp;
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
int mult = multiplicacaoIt(4, 3); int mult = multiplicacaoIt(4, 3);
printf("\nRESPOSTA IT: %i", mult); printf("\nRESPOSTA IT: %i", mult);
mult = multiplicacao(4, 3); mult = multiplicacao(4, 3);
printf("\nRESPOSTA REC: %i", mult); printf("\nRESPOSTA REC: %i", mult);
return 0; return 0;
} }

View File

@ -1,17 +1,17 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
void printRecursivo(int i){ void printRecursivo(int i){
printf("\nvalor de i: %i", i); printf("\nvalor de i: %i", i);
if(i > 0){ if(i > 0){
printRecursivo(i-1); printRecursivo(i-1);
} }
printf("\nvalor de i: %i", i); printf("\nvalor de i: %i", i);
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
int n = 3; int n = 3;
printRecursivo(n); printRecursivo(n);
return 0; return 0;
} }

View File

@ -1,24 +1,24 @@
#include <stdio.h> #include <stdio.h>
#define MAXTAM 100 #define MAXTAM 100
struct Funcionario { struct Funcionario {
int matricula; int matricula;
char nome[MAXTAM]; char nome[MAXTAM];
}; };
void main (){ void main (){
struct Funcionario f; struct Funcionario f;
printf("\nEntre com a matricula: "); printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula); scanf("%d", &f.matricula);
printf("\nEntre com o nome: "); printf("\nEntre com o nome: ");
scanf("%s", f.nome); scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula); printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome); printf("\nNome: %s", f.nome);
printf("\n\n"); printf("\n\n");
} }

View File

@ -1,24 +1,24 @@
#include <stdio.h> #include <stdio.h>
#define MAXTAM 100 #define MAXTAM 100
struct Funcionario { struct Funcionario {
int matricula; int matricula;
char nome[MAXTAM]; char nome[MAXTAM];
}; };
typedef struct Funcionario Funcionario; typedef struct Funcionario Funcionario;
void main (){ void main (){
Funcionario f; Funcionario f;
printf("\nEntre com a matricula: "); printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula); scanf("%d", &f.matricula);
printf("\nEntre com o nome: "); printf("\nEntre com o nome: ");
scanf("%s", f.nome); scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula); printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome); printf("\nNome: %s", f.nome);
printf("\n\n"); printf("\n\n");
} }

View File

@ -1,22 +1,22 @@
#include <stdio.h> #include <stdio.h>
#define MAXTAM 100 #define MAXTAM 100
typedef struct Funcionario { typedef struct Funcionario {
int matricula; int matricula;
char nome[MAXTAM]; char nome[MAXTAM];
} Funcionario; } Funcionario;
void main (){ void main (){
Funcionario f; Funcionario f;
printf("\nEntre com a matricula: "); printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula); scanf("%d", &f.matricula);
printf("\nEntre com o nome: "); printf("\nEntre com o nome: ");
scanf("%s", f.nome); scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula); printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome); printf("\nNome: %s", f.nome);
printf("\n\n"); printf("\n\n");
} }

View File

@ -1,29 +1,29 @@
#include <stdio.h> #include <stdio.h>
#define MAXTAM 100 #define MAXTAM 100
struct Funcionario { struct Funcionario {
int matricula; int matricula;
char nome[MAXTAM]; char nome[MAXTAM];
}; };
typedef struct Funcionario Funcionario; typedef struct Funcionario Funcionario;
void main (){ void main (){
Funcionario vet[MAXTAM]; Funcionario vet[MAXTAM];
int n = 3; int n = 3;
for(int i = 0; i < n; i++){ for(int i = 0; i < n; i++){
printf("\nEntre com a matricula do funcionario %d: ", (i+1)); printf("\nEntre com a matricula do funcionario %d: ", (i+1));
scanf("%d", &vet[i].matricula); scanf("%d", &vet[i].matricula);
printf("\nEntre com o nome do funcionario %d: ", (i+1)); printf("\nEntre com o nome do funcionario %d: ", (i+1));
scanf("%s", vet[i].nome); scanf("%s", vet[i].nome);
} }
for(int i = 0; i < n; i++){ for(int i = 0; i < n; i++){
printf("\nMatricula do funcionario %d: %d", (i+1), vet[i].matricula); printf("\nMatricula do funcionario %d: %d", (i+1), vet[i].matricula);
printf("\nNome do funcionario %d: %s\n", (i+1), vet[i].nome); printf("\nNome do funcionario %d: %s\n", (i+1), vet[i].nome);
} }
printf("\n\n"); printf("\n\n");
} }

View File

@ -1,14 +1,14 @@
#include <stdio.h> #include <stdio.h>
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
int a = sizeof(char), int a = sizeof(char),
b = sizeof(int), b = sizeof(int),
c = sizeof(double), c = sizeof(double),
d = sizeof(float); d = sizeof(float);
printf ("Tamanho do char: %i\n", a); printf ("Tamanho do char: %i\n", a);
printf ("Tamanho do int: %i\n", b); printf ("Tamanho do int: %i\n", b);
printf ("Tamanho do double: %i\n", c); printf ("Tamanho do double: %i\n", c);
printf ("Tamanho do float: %i\n", d); printf ("Tamanho do float: %i\n", d);
return 0; return 0;
} }

View File

@ -1,33 +1,33 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
int main(int argc, char *argv[]){ int main(int argc, char *argv[]){
char s1[80], s2[80]; char s1[80], s2[80];
strcpy(s1, "Algoritmos"); strcpy(s1, "Algoritmos");
strcpy(s2, " e Estruturas de Dados II"); strcpy(s2, " e Estruturas de Dados II");
printf("\nTamanho s1(%i)", (int)strlen(s1)); printf("\nTamanho s1(%i)", (int)strlen(s1));
printf("\nTamanho s2(%i)", (int)strlen(s2)); printf("\nTamanho s2(%i)", (int)strlen(s2));
if(!strcmp(s1, s2)) printf("\nIguais!!!"); if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!"); else printf("\nDiferentes!!!");
strcat(s1, s2); strcat(s1, s2);
printf("\nNova s1 (%s)", s1); printf("\nNova s1 (%s)", s1);
strcpy(s2, s1); strcpy(s2, s1);
printf("\nNova s2 (%s)", s2); printf("\nNova s2 (%s)", s2);
if(!strcmp(s1, s2)) printf("\nIguais!!!"); if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!"); else printf("\nDiferentes!!!");
s1[10] = s2[10] = '\0'; s1[11] = 'a'; s2[11] = 'b'; s1[10] = s2[10] = '\0'; s1[11] = 'a'; s2[11] = 'b';
printf("\nNova s1 (%s)", s1); printf("\nNova s1 (%s)", s1);
printf("\nNova s2 (%s)", s2); printf("\nNova s2 (%s)", s2);
if(!strcmp(s1, s2)) printf("\nIguais!!!"); if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!"); else printf("\nDiferentes!!!");
return 0; return 0;
} }

View File

@ -1,6 +1,6 @@
class ArgumentoMain { class ArgumentoMain {
public static void main (String[] args){ public static void main (String[] args){
System.out.println("Primeiro parametro: " + args[0]); System.out.println("Primeiro parametro: " + args[0]);
System.out.println("Numero de parametros: " + args.length); System.out.println("Numero de parametros: " + args.length);
} }
} }

View File

@ -1,21 +1,21 @@
class ExemploArq01Escrita class ExemploArq01Escrita
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
//Abrir o arquivo texto //Abrir o arquivo texto
Arq.openWrite("exemplo.txt"); Arq.openWrite("exemplo.txt");
//Escrever no arquivo texto //Escrever no arquivo texto
Arq.println(1); Arq.println(1);
Arq.println(5.3); Arq.println(5.3);
Arq.println('X'); Arq.println('X');
Arq.println(true); Arq.println(true);
Arq.println("Algoritmos"); Arq.println("Algoritmos");
//Fechar o arquivo texto //Fechar o arquivo texto
Arq.close(); Arq.close();
} // Fim main() } // Fim main()
} // Fim class } // Fim class

View File

@ -1,28 +1,28 @@
class ExemploArq02Leitura class ExemploArq02Leitura
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
//Abrir o arquivo texto //Abrir o arquivo texto
Arq.openRead("exemplo.txt"); Arq.openRead("exemplo.txt");
//Ler o arquivo texto //Ler o arquivo texto
int inteiro = Arq.readInt(); int inteiro = Arq.readInt();
double real = Arq.readDouble(); double real = Arq.readDouble();
char caractere = Arq.readChar(); char caractere = Arq.readChar();
boolean boleano = Arq.readBoolean(); boolean boleano = Arq.readBoolean();
String str = Arq.readString(); String str = Arq.readString();
//Fechar o arquivo texto //Fechar o arquivo texto
Arq.close(); Arq.close();
//Mostrar os valores lidos na tela //Mostrar os valores lidos na tela
MyIO.println("inteiro: " + inteiro); MyIO.println("inteiro: " + inteiro);
MyIO.println("real: " + real); MyIO.println("real: " + real);
MyIO.println("caractere: " + caractere); MyIO.println("caractere: " + caractere);
MyIO.println("boleano: " + boleano); MyIO.println("boleano: " + boleano);
MyIO.println("str: " + str); MyIO.println("str: " + str);
} // Fim main() } // Fim main()
} // Fim class } // Fim class

View File

@ -1,28 +1,28 @@
class ExemploArq02bLeitura class ExemploArq02bLeitura
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
//Abrir o arquivo texto //Abrir o arquivo texto
Arq.openRead("exemplo.txt"); Arq.openRead("exemplo.txt");
//Ler o arquivo texto //Ler o arquivo texto
int inteiro = Integer.parseInt(Arq.readLine()); int inteiro = Integer.parseInt(Arq.readLine());
double real = Double.parseDouble(Arq.readLine().replace(",",".")); double real = Double.parseDouble(Arq.readLine().replace(",","."));
char caractere = Arq.readLine().charAt(0); char caractere = Arq.readLine().charAt(0);
boolean boleano = Boolean.parseBoolean(Arq.readLine()); boolean boleano = Boolean.parseBoolean(Arq.readLine());
String str = Arq.readLine(); String str = Arq.readLine();
//Fechar o arquivo texto //Fechar o arquivo texto
Arq.close(); Arq.close();
//Mostrar os valores lidos na tela //Mostrar os valores lidos na tela
MyIO.println("inteiro: " + inteiro); MyIO.println("inteiro: " + inteiro);
MyIO.println("real: " + real); MyIO.println("real: " + real);
MyIO.println("caractere: " + caractere); MyIO.println("caractere: " + caractere);
MyIO.println("boleano: " + boleano); MyIO.println("boleano: " + boleano);
MyIO.println("str: " + str); MyIO.println("str: " + str);
} // Fim main() } // Fim main()
} // Fim class } // Fim class

View File

@ -1,16 +1,16 @@
class ExemploArq03Exercicio { class ExemploArq03Exercicio {
public static void main (String[] args){ public static void main (String[] args){
Arq.openRead("exemplo.txt"); Arq.openRead("exemplo.txt");
String str = ""; String str = "";
while (Arq.hasNext() == true){ while (Arq.hasNext() == true){
str += Arq.readChar(); str += Arq.readChar();
} }
Arq.close(); Arq.close();
Arq.openWrite("copia.txt"); Arq.openWrite("copia.txt");
Arq.print(str); Arq.print(str);
Arq.close(); Arq.close();
} }
} }

View File

@ -1,16 +1,16 @@
import java.io.*; import java.io.*;
public class ExemploRAF01Escrita { public class ExemploRAF01Escrita {
public static void main(String args[]) throws Exception { public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw"); RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw");
raf.writeInt(1); raf.writeInt(1);
raf.writeDouble(5.3); raf.writeDouble(5.3);
raf.writeChar('X'); raf.writeChar('X');
raf.writeBoolean(true); raf.writeBoolean(true);
raf.writeBytes("Algoritmos"); raf.writeBytes("Algoritmos");
raf.close(); raf.close();
} }
} }

View File

@ -1,22 +1,22 @@
import java.io.*; import java.io.*;
class ExemploRAF02Leitura { class ExemploRAF02Leitura {
public static void main (String[] args) throws Exception{ public static void main (String[] args) throws Exception{
RandomAccessFile raf = new RandomAccessFile("exemplo.txt", "rw"); RandomAccessFile raf = new RandomAccessFile("exemplo.txt", "rw");
int inteiro = raf.readInt(); int inteiro = raf.readInt();
double real = raf.readDouble(); double real = raf.readDouble();
char caractere = raf.readChar(); char caractere = raf.readChar();
boolean boleano = raf.readBoolean(); boolean boleano = raf.readBoolean();
String str = raf.readLine(); String str = raf.readLine();
raf.close(); raf.close();
System.out.println("inteiro: " + inteiro); System.out.println("inteiro: " + inteiro);
System.out.println("real: " + real); System.out.println("real: " + real);
System.out.println("caractere: " + caractere); System.out.println("caractere: " + caractere);
System.out.println("boleano: " + boleano); System.out.println("boleano: " + boleano);
System.out.println("str: " + str); System.out.println("str: " + str);
} }
} }

View File

@ -1,29 +1,29 @@
import java.io.*; import java.io.*;
public class ExemploRAF03Cabecote { public class ExemploRAF03Cabecote {
public static void main(String args[]) throws Exception { public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw"); RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw");
raf.writeInt(1); raf.writeInt(1);
raf.writeDouble(5.3); raf.writeDouble(5.3);
raf.writeChar('X'); raf.writeChar('X');
raf.writeBoolean(true); raf.writeBoolean(true);
raf.writeBytes("Algoritmos"); raf.writeBytes("Algoritmos");
raf.seek(0); //Retornando o cabecote para a posicao 0 raf.seek(0); //Retornando o cabecote para a posicao 0
System.out.println(raf.readInt()); //imprimindo o inteiro System.out.println(raf.readInt()); //imprimindo o inteiro
raf.seek(12); //Setando o cabecote na posicao 12 (do caractere, raf.seek(12); //Setando o cabecote na posicao 12 (do caractere,
//12 = 4 do int + 8 do double) //12 = 4 do int + 8 do double)
System.out.println(raf.readChar()); System.out.println(raf.readChar());
raf.seek(12); //Setando o cabecote novamente na posicao 12 raf.seek(12); //Setando o cabecote novamente na posicao 12
raf.writeChar('@'); //Substituindo o caractere raf.writeChar('@'); //Substituindo o caractere
raf.seek(12); raf.seek(12);
System.out.println(raf.readChar()); System.out.println(raf.readChar());
raf.close(); raf.close();
} }
} }

View File

@ -1,44 +1,44 @@
/** /**
* Introducao a programacao orientada por objetos * Introducao a programacao orientada por objetos
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class Principal class Principal
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
Retangulo r1 = new Retangulo(); Retangulo r1 = new Retangulo();
Retangulo r2 = new Retangulo(); Retangulo r2 = new Retangulo();
r1.lerTudo(); r1.lerTudo();
r1.escreverTudo(); r1.escreverTudo();
r2.lerTudo(); r2.lerTudo();
r2.escreverTudo(); r2.escreverTudo();
if (r1.comparar(r2.getB(), r2.getH()) == true){ if (r1.comparar(r2.getB(), r2.getH()) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!"); System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!");
}else{ }else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!"); System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!");
} }
if (r1.comparar(r2) == true){ if (r1.comparar(r2) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!"); System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!");
}else{ }else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!"); System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!");
} }
if (r1.comparar(r1) == true){ if (r1.comparar(r1) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao iguais!"); System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao iguais!");
}else{ }else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao diferentes!"); System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao diferentes!");
} }
if (r2.comparar(r1) == true){ if (r2.comparar(r1) == true){
System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao iguais!"); System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao iguais!");
}else{ }else{
System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao diferentes!"); System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao diferentes!");
} }
} }
} }

View File

@ -1,102 +1,102 @@
/** /**
* Introducao a programacao orientada por objetos * Introducao a programacao orientada por objetos
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class Retangulo{ class Retangulo{
//Declaracao de variaveis //Declaracao de variaveis
private double b, h; private double b, h;
private String nome; private String nome;
//Construtor vazio //Construtor vazio
public Retangulo(){ public Retangulo(){
this.b = this.h = 0; this.b = this.h = 0;
this.nome = ""; this.nome = "";
} }
//Construtor que recebe parametros //Construtor que recebe parametros
public Retangulo(double b, double h, String nome){ public Retangulo(double b, double h, String nome){
this.b = b; this.b = b;
this.h = h; this.h = h;
this.nome = nome; this.nome = nome;
} }
public double getB(){ public double getB(){
return this.b; return this.b;
} }
public void setB(double b){ public void setB(double b){
this.b = b; this.b = b;
} }
public double getH(){ public double getH(){
return this.h; return this.h;
} }
public void setH(double h){ public void setH(double h){
this.h = h; this.h = h;
} }
public String getNome(){ public String getNome(){
return this.nome; return this.nome;
} }
public void setNome(String nome){ public void setNome(String nome){
this.nome = nome; this.nome = nome;
} }
public void lerTudo(){ public void lerTudo(){
b = MyIO.readDouble("Entre com a base: "); b = MyIO.readDouble("Entre com a base: ");
h = MyIO.readDouble("Entre com a altura: "); h = MyIO.readDouble("Entre com a altura: ");
nome = MyIO.readString("Entre com o nome: "); nome = MyIO.readString("Entre com o nome: ");
} }
public void escreverTudo(){ public void escreverTudo(){
System.out.println("NOME: " + nome); System.out.println("NOME: " + nome);
System.out.println("Base: " + b); System.out.println("Base: " + b);
System.out.println("Altura: " + h); System.out.println("Altura: " + h);
System.out.println("Area: " + getArea()); System.out.println("Area: " + getArea());
System.out.println("Diagonal: " + getDiagonal()); System.out.println("Diagonal: " + getDiagonal());
System.out.println("Perimetro: " + getPerimetro()); System.out.println("Perimetro: " + getPerimetro());
} }
//Retornar a area //Retornar a area
public double getArea(){ public double getArea(){
return (b * h); return (b * h);
} }
//Retornar o perimetro //Retornar o perimetro
public double getPerimetro(){ public double getPerimetro(){
return ((b + h) * 2); return ((b + h) * 2);
} }
//Retornar a diagonal //Retornar a diagonal
public double getDiagonal(){ public double getDiagonal(){
return Math.sqrt(b * b + h * h); return Math.sqrt(b * b + h * h);
} }
//Comparar //Comparar
public boolean comparar(double outraB, double outraH){ public boolean comparar(double outraB, double outraH){
boolean resp; boolean resp;
if (this.b == outraB && this.h == outraH){ if (this.b == outraB && this.h == outraH){
resp = true; resp = true;
}else{ }else{
resp = false; resp = false;
} }
return resp; return resp;
} }
//Comparar //Comparar
//public boolean comparar(double outraB, double outraH){ //public boolean comparar(double outraB, double outraH){
// return (this.b == outraB && this.h == outraH); // return (this.b == outraB && this.h == outraH);
//} //}
//Comparar //Comparar
public boolean comparar(Retangulo x){ public boolean comparar(Retangulo x){
return (this.b == x.b && this.h == x.h); return (this.b == x.b && this.h == x.h);
} }
} }

View File

@ -1,43 +1,43 @@
import java.io.*; import java.io.*;
import java.nio.charset.*; import java.nio.charset.*;
class ExemploBufferedReader { class ExemploBufferedReader {
//Declaracao da classe BufferedReader //Declaracao da classe BufferedReader
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1"))); private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")));
public static String readString(){ public static String readString(){
String s = ""; String s = "";
char tmp; char tmp;
try{ try{
do{ do{
tmp = (char)in.read(); tmp = (char)in.read();
if(tmp != '\n' && tmp != ' ' && tmp != 13){ if(tmp != '\n' && tmp != ' ' && tmp != 13){
s += tmp; s += tmp;
} }
}while(tmp != '\n' && tmp != ' '); }while(tmp != '\n' && tmp != ' ');
}catch(IOException ioe){} }catch(IOException ioe){}
return s; return s;
} }
public static void main(String [] args) throws Exception { public static void main(String [] args) throws Exception {
System.out.printf("Entre com uma palavra: "); System.out.printf("Entre com uma palavra: ");
String str = readString(); String str = readString();
System.out.printf("Entre com um numero inteiro: "); System.out.printf("Entre com um numero inteiro: ");
int inteiro = Integer.parseInt(readString().trim()); int inteiro = Integer.parseInt(readString().trim());
System.out.printf("Entre com um numero real: "); System.out.printf("Entre com um numero real: ");
double real = Double.parseDouble(readString().trim().replace(",",".")); double real = Double.parseDouble(readString().trim().replace(",","."));
System.out.printf("Entre com um caractere: "); System.out.printf("Entre com um caractere: ");
char caractere = (char)in.read(); char caractere = (char)in.read();
System.out.println("Sua str: " + str); System.out.println("Sua str: " + str);
System.out.println("Seu inteiro: " + inteiro); System.out.println("Seu inteiro: " + inteiro);
System.out.println("Seu real: " + real); System.out.println("Seu real: " + real);
System.out.println("Seu caractere: " + caractere); System.out.println("Seu caractere: " + caractere);
} // fim main () } // fim main ()
} // fim class } // fim class

View File

@ -1,13 +1,13 @@
class ExemploMyIO { class ExemploMyIO {
public static void main (String[] args){ public static void main (String[] args){
String str = MyIO.readString("Entre com uma palavra: "); String str = MyIO.readString("Entre com uma palavra: ");
int inteiro = MyIO.readInt("Entre com um inteiro: "); int inteiro = MyIO.readInt("Entre com um inteiro: ");
double real = MyIO.readDouble("Entre com um real: "); double real = MyIO.readDouble("Entre com um real: ");
char caractere = MyIO.readChar("Entre com um caractere: "); char caractere = MyIO.readChar("Entre com um caractere: ");
MyIO.println("Sua string: " + str); MyIO.println("Sua string: " + str);
MyIO.println("Seu inteiro: " + inteiro); MyIO.println("Seu inteiro: " + inteiro);
MyIO.println("Seu real: " + real); MyIO.println("Seu real: " + real);
MyIO.println("Seu caractere: " + caractere); MyIO.println("Seu caractere: " + caractere);
} }
} }

View File

@ -1,28 +1,28 @@
import java.util.*; import java.util.*;
class ExemploScanner { class ExemploScanner {
public static void main(String [] args){ public static void main(String [] args){
//Declaracao da classe scanner //Declaracao da classe scanner
Scanner scanner = new Scanner (System.in); Scanner scanner = new Scanner (System.in);
System.out.printf("Entre com uma palavra: "); System.out.printf("Entre com uma palavra: ");
String str = scanner.nextLine(); String str = scanner.nextLine();
System.out.printf("Entre com um caractere: "); System.out.printf("Entre com um caractere: ");
char caractere = scanner.nextLine().charAt(0); char caractere = scanner.nextLine().charAt(0);
System.out.printf("Entre com um numero inteiro: "); System.out.printf("Entre com um numero inteiro: ");
int inteiro = scanner.nextInt(); int inteiro = scanner.nextInt();
System.out.printf("Entre com um numero real: "); System.out.printf("Entre com um numero real: ");
double real = scanner.nextDouble(); double real = scanner.nextDouble();
System.out.println("Sua str: " + str); System.out.println("Sua str: " + str);
System.out.println("Seu inteiro: " + inteiro); System.out.println("Seu inteiro: " + inteiro);
System.out.println("Seu real: " + real); System.out.println("Seu real: " + real);
System.out.println("Seu caractere: " + caractere); System.out.println("Seu caractere: " + caractere);
} // fim main () } // fim main ()
} // fim class } // fim class

View File

@ -1,5 +1,5 @@
hoje hoje
3000000 3000000
12.3 12.3
a a

View File

@ -1,14 +1,14 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class Ponteiro01Array { class Ponteiro01Array {
public static void main (String[] args) { public static void main (String[] args) {
int[] vet = new int [10]; int[] vet = new int [10];
System.out.println(vet); System.out.println(vet);
vet = new int [10]; vet = new int [10];
System.out.println(vet); System.out.println(vet);
} }
} }

View File

@ -1,19 +1,19 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class Ponteiro02PassagemTipoPrimitivo { class Ponteiro02PassagemTipoPrimitivo {
public static void passagemDeTipoPrimitivo(int a){ public static void passagemDeTipoPrimitivo(int a){
System.out.println("a: " + a); System.out.println("a: " + a);
a = 10; a = 10;
System.out.println("a: " + a); System.out.println("a: " + a);
} }
public static void main(String[] args) { public static void main(String[] args) {
int x = 5; int x = 5;
System.out.println("x: " + x); System.out.println("x: " + x);
passagemDeTipoPrimitivo(x); passagemDeTipoPrimitivo(x);
System.out.println("x: " + x); System.out.println("x: " + x);
} }
} }

View File

@ -1,31 +1,31 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class Ponteiro03PassagemArray { class Ponteiro03PassagemArray {
public static void passangemDeArray(int[] b){ public static void passangemDeArray(int[] b){
for(int i = 0; i < 5; i++){ for(int i = 0; i < 5; i++){
b[i] *= 5; b[i] *= 5;
System.out.println("b[" + i + "]: " + b[i]); System.out.println("b[" + i + "]: " + b[i]);
} }
b = new int[5]; b = new int[5];
for(int i = 0; i < 5; i++){ for(int i = 0; i < 5; i++){
b[i] = i; b[i] = i;
System.out.println("b[" + i + "]: " + b[i]); System.out.println("b[" + i + "]: " + b[i]);
} }
} }
public static void main(String[] args) { public static void main(String[] args) {
int[] y = new int [5]; int[] y = new int [5];
for(int i = 0; i < 5; i++){ for(int i = 0; i < 5; i++){
y[i] = i; y[i] = i;
System.out.println("y[" + i + "]: " + y[i]); System.out.println("y[" + i + "]: " + y[i]);
} }
passangemDeArray(y); passangemDeArray(y);
for(int i = 0; i < 5; i++){ for(int i = 0; i < 5; i++){
System.out.println("y[" + i + "]: " + y[i]); System.out.println("y[" + i + "]: " + y[i]);
} }
} }
} }

View File

@ -1,55 +1,55 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 3 01/2016 * @version 3 01/2016
*/ */
class Cliente{ class Cliente{
private int codigo; private int codigo;
private String nome; private String nome;
public Cliente(){ public Cliente(){
this(0, ""); this(0, "");
} }
public Cliente(int codigo){ public Cliente(int codigo){
this(codigo, ""); this(codigo, "");
} }
public Cliente(int codigo, String nome){ public Cliente(int codigo, String nome){
this.codigo = codigo; this.codigo = codigo;
this.nome = nome; this.nome = nome;
} }
public int getCodigo(){ public int getCodigo(){
return codigo; return codigo;
} }
public void setCodigo(int codigo){ public void setCodigo(int codigo){
this.codigo = codigo; this.codigo = codigo;
} }
public String getNome(){ public String getNome(){
return nome; return nome;
} }
public void setNome(String nome){ public void setNome(String nome){
this.nome = nome; this.nome = nome;
} }
} }
class Ponteiro04Objeto { class Ponteiro04Objeto {
public static void main (String[] args){ public static void main (String[] args){
//Declarando tres ponteiros //Declarando tres ponteiros
Cliente c1 = null, c2 = null, c3 = null; Cliente c1 = null, c2 = null, c3 = null;
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas //Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas
c1 = new Cliente(1, "aa"); c1 = new Cliente(1, "aa");
c2 = c1; c2 = c1;
c3 = new Cliente(2, "bb"); c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Setando o codigo apontado por c1 e c2 //Setando o codigo apontado por c1 e c2
c2.setCodigo(3); c2.setCodigo(3);
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
} }
} }

View File

@ -1,96 +1,96 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 3 01/2016 * @version 3 01/2016
*/ */
class Cliente{ class Cliente{
private int codigo; private int codigo;
private String nome; private String nome;
public Cliente(){ public Cliente(){
this(0, ""); this(0, "");
} }
public Cliente(int codigo){ public Cliente(int codigo){
this(codigo, ""); this(codigo, "");
} }
public Cliente(int codigo, String nome){ public Cliente(int codigo, String nome){
this.codigo = codigo; this.codigo = codigo;
this.nome = nome; this.nome = nome;
} }
public int getCodigo(){ public int getCodigo(){
return codigo; return codigo;
} }
public void setCodigo(int codigo){ public void setCodigo(int codigo){
this.codigo = codigo; this.codigo = codigo;
} }
public String getNome(){ public String getNome(){
return nome; return nome;
} }
public void setNome(String nome){ public void setNome(String nome){
this.nome = nome; this.nome = nome;
} }
} }
class Ponteiro05PassagemObjeto { class Ponteiro05PassagemObjeto {
/** /**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o * Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal). * conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro). * Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro).
*/ */
public static Cliente setar2(Cliente y){ public static Cliente setar2(Cliente y){
y.setCodigo(6); y.setCodigo(6);
y.setNome("ff"); y.setNome("ff");
System.out.println("ADDRs: y(" + y + ")"); System.out.println("ADDRs: y(" + y + ")");
System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")"); System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")");
return y; return y;
} }
/** /**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o * Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal). * conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo * Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo
* princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a * princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a
* area de memoria que continha o ponteiro e o objeto criados neste metodo. * area de memoria que continha o ponteiro e o objeto criados neste metodo.
*/ */
public static void setar1(Cliente x){ public static void setar1(Cliente x){
x.setCodigo(4); x.setCodigo(4);
x.setNome("dd"); x.setNome("dd");
System.out.println("ADDRs: x(" + x + ")"); System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")"); System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
x = new Cliente (5, "ee"); x = new Cliente (5, "ee");
System.out.println("ADDRs: x(" + x + ")"); System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")"); System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
} }
public static void main (String[] args){ public static void main (String[] args){
//Declarando tres ponteiros //Declarando tres ponteiros
Cliente c1 = new Cliente(1, "aa"); Cliente c1 = new Cliente(1, "aa");
Cliente c2 = c1; Cliente c2 = c1;
Cliente c3 = new Cliente(2, "bb"); Cliente c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar1 e passando POR VALOR O ADDR de c1 //Chamando o metodo setar1 e passando POR VALOR O ADDR de c1
setar1(c1); setar1(c1);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3 //Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3
c3 = setar2(c2); c3 = setar2(c2);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
} }
} }

View File

@ -1,99 +1,99 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 3 01/2016 * @version 3 01/2016
*/ */
class Cliente{ class Cliente{
private int codigo; private int codigo;
private String nome; private String nome;
public Cliente(){ public Cliente(){
this(0, ""); this(0, "");
} }
public Cliente(int codigo){ public Cliente(int codigo){
this(codigo, ""); this(codigo, "");
} }
public Cliente(int codigo, String nome){ public Cliente(int codigo, String nome){
this.codigo = codigo; this.codigo = codigo;
this.nome = nome; this.nome = nome;
} }
public int getCodigo(){ public int getCodigo(){
return codigo; return codigo;
} }
public void setCodigo(int codigo){ public void setCodigo(int codigo){
this.codigo = codigo; this.codigo = codigo;
} }
public String getNome(){ public String getNome(){
return nome; return nome;
} }
public void setNome(String nome){ public void setNome(String nome){
this.nome = nome; this.nome = nome;
} }
public Cliente clone(){ public Cliente clone(){
return new Cliente(this.codigo, this.nome); return new Cliente(this.codigo, this.nome);
} }
} }
class Ponteiro06PassagemObjetoClone { class Ponteiro06PassagemObjetoClone {
/** /**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o * Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal). * conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro). * Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro).
*/ */
public static Cliente setar2(Cliente y){ public static Cliente setar2(Cliente y){
y.setCodigo(6); y.setCodigo(6);
y.setNome("ff"); y.setNome("ff");
System.out.println("ADDRs: y(" + y + ")"); System.out.println("ADDRs: y(" + y + ")");
System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")"); System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")");
return y; return y;
} }
/** /**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o * Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal). * conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo * Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo
* princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a * princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a
* area de memoria que continha o ponteiro e o objeto criados neste metodo. * area de memoria que continha o ponteiro e o objeto criados neste metodo.
*/ */
public static void setar1(Cliente x){ public static void setar1(Cliente x){
x.setCodigo(4); x.setCodigo(4);
x.setNome("dd"); x.setNome("dd");
System.out.println("ADDRs: x(" + x + ")"); System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")"); System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
x = new Cliente (5, "ee"); x = new Cliente (5, "ee");
System.out.println("ADDRs: x(" + x + ")"); System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")"); System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
} }
public static void main (String[] args){ public static void main (String[] args){
//Declarando tres ponteiros //Declarando tres ponteiros
Cliente c1 = new Cliente(1, "aa"); Cliente c1 = new Cliente(1, "aa");
Cliente c2 = c1.clone(); Cliente c2 = c1.clone();
Cliente c3 = new Cliente(2, "bb"); Cliente c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar1 e passando POR VALOR O ADDR de c1 //Chamando o metodo setar1 e passando POR VALOR O ADDR de c1
setar1(c1); setar1(c1);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3 //Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3
c3 = setar2(c2); c3 = setar2(c2);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
} }
} }

View File

@ -1,58 +1,58 @@
/** /**
* Ponteiro * Ponteiro
* @author Max do Val Machado * @author Max do Val Machado
* @version 3 01/2016 * @version 3 01/2016
*/ */
class Cliente{ class Cliente{
private int codigo; private int codigo;
private String nome; private String nome;
public Cliente(){ public Cliente(){
this(0, ""); this(0, "");
} }
public Cliente(int codigo){ public Cliente(int codigo){
this(codigo, ""); this(codigo, "");
} }
public Cliente(int codigo, String nome){ public Cliente(int codigo, String nome){
this.codigo = codigo; this.codigo = codigo;
this.nome = nome; this.nome = nome;
} }
public int getCodigo(){ public int getCodigo(){
return codigo; return codigo;
} }
public void setCodigo(int codigo){ public void setCodigo(int codigo){
this.codigo = codigo; this.codigo = codigo;
} }
public String getNome(){ public String getNome(){
return nome; return nome;
} }
public void setNome(String nome){ public void setNome(String nome){
this.nome = nome; this.nome = nome;
} }
public Cliente clone(){ public Cliente clone(){
return new Cliente(this.codigo, this.nome); return new Cliente(this.codigo, this.nome);
} }
} }
class Ponteiro07ObjetoClone { class Ponteiro07ObjetoClone {
public static void main (String[] args){ public static void main (String[] args){
//Declarando tres ponteiros //Declarando tres ponteiros
Cliente c1 = null, c2 = null, c3 = null; Cliente c1 = null, c2 = null, c3 = null;
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas //Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas
c1 = new Cliente(1, "aa"); c1 = new Cliente(1, "aa");
c2 = c1; c2 = c1;
c3 = new Cliente(2, "bb"); c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")"); System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Setando o codigo apontado por c1 e c2 //Setando o codigo apontado por c1 e c2
c2.setCodigo(3); c2.setCodigo(3);
System.out.println("ATRIBUTOs:"); System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")"); System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")"); System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")"); System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
} }
} }

View File

@ -1,20 +1,20 @@
class ChamandoMetodo { class ChamandoMetodo {
public static void primeiro(){ public static void primeiro(){
System.out.println("1o - inicio"); System.out.println("1o - inicio");
segundo(); segundo();
System.out.println("1o - fim"); System.out.println("1o - fim");
} }
public static void segundo(){ public static void segundo(){
System.out.println("2o - inicio"); System.out.println("2o - inicio");
terceiro(); terceiro();
System.out.println("2o - fim"); System.out.println("2o - fim");
} }
public static void terceiro(){ public static void terceiro(){
System.out.println("3o - inicio e fim"); System.out.println("3o - inicio e fim");
} }
public static void main (String[] args){ public static void main (String[] args){
System.out.println("main - inicio"); System.out.println("main - inicio");
primeiro(); primeiro();
System.out.println("main - fim"); System.out.println("main - fim");
} }
} }

View File

@ -1,40 +1,40 @@
/** /**
* Recursividade * Recursividade
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class ContarMaiuscula { class ContarMaiuscula {
public static boolean isUpper(char x){ public static boolean isUpper(char x){
return (x >= 'A' && x <= 'Z'); return (x >= 'A' && x <= 'Z');
} }
public static int contMaiusculo(String s){ public static int contMaiusculo(String s){
int cont = 0; int cont = 0;
for(int i = 0; i < s.length(); i++){ for(int i = 0; i < s.length(); i++){
if(isUpper(s.charAt(i)) == true){ if(isUpper(s.charAt(i)) == true){
cont++; cont++;
} }
} }
return cont; return cont;
} }
public static int contMaiusculo2(String s){ public static int contMaiusculo2(String s){
return contMaiusculo2(s, 0); return contMaiusculo2(s, 0);
} }
public static int contMaiusculo2(String s, int i){ public static int contMaiusculo2(String s, int i){
int cont = 0; int cont = 0;
if(i < s.length()){ if(i < s.length()){
if(isUpper(s.charAt(i)) == true){ if(isUpper(s.charAt(i)) == true){
cont++; cont++;
} }
cont += contMaiusculo2(s, i + 1); cont += contMaiusculo2(s, i + 1);
} }
return cont; return cont;
} }
public static void main (String[] args){ public static void main (String[] args){
System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo("AlGoritmos e Estruturas de Dados")); System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo("AlGoritmos e Estruturas de Dados"));
System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo2("AlGoritmos e Estruturas de Dados")); System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo2("AlGoritmos e Estruturas de Dados"));
} }
} }

View File

@ -1,20 +1,20 @@
/** /**
* Recursividade * Recursividade
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class FatorialRecursivo{ class FatorialRecursivo{
public static int fatorial(int n){ public static int fatorial(int n){
int resp; int resp;
System.out.println("fat (" + n + ")"); System.out.println("fat (" + n + ")");
resp = (n == 1) ? 1 : n * fatorial(n-1); resp = (n == 1) ? 1 : n * fatorial(n-1);
System.out.println("fat n(" + n + "): " + resp); System.out.println("fat n(" + n + "): " + resp);
return resp; return resp;
} }
public static void main(String[] args){ public static void main(String[] args){
int n = Integer.parseInt(args[0]); int n = Integer.parseInt(args[0]);
System.out.println("FATORIAL RECURSIVO(" + n + "): " + fatorial(n)); System.out.println("FATORIAL RECURSIVO(" + n + "): " + fatorial(n));
} }
} }

View File

@ -1,18 +1,18 @@
/** /**
* Recursividade * Recursividade
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class FibonacciRecursivo { class FibonacciRecursivo {
public static int fibRec (int n){ public static int fibRec (int n){
int resp; int resp;
System.out.println("fib (" + n + ")"); System.out.println("fib (" + n + ")");
resp = (n == 0 || n == 1) ? 1 : fibRec(n-1) + fibRec(n-2); resp = (n == 0 || n == 1) ? 1 : fibRec(n-1) + fibRec(n-2);
System.out.println("fib (" + n + "): " + resp); System.out.println("fib (" + n + "): " + resp);
return resp; return resp;
} }
public static void main (String[] args){ public static void main (String[] args){
int n = Integer.parseInt(args[0]); int n = Integer.parseInt(args[0]);
System.out.println("FIBONACCI RECURSIVO(" + n + "): " + fibRec(n)); System.out.println("FIBONACCI RECURSIVO(" + n + "): " + fibRec(n));
} }
} }

View File

@ -1,31 +1,31 @@
class Multiplicacao { class Multiplicacao {
public static int multiplicacao(int a, int b){ public static int multiplicacao(int a, int b){
return multiplicacao(a, b, 0); return multiplicacao(a, b, 0);
} }
public static int multiplicacao(int a, int b, int i){ public static int multiplicacao(int a, int b, int i){
int resp = 0; int resp = 0;
if(i < b){ if(i < b){
resp = a + multiplicacao(a, b, i+1); resp = a + multiplicacao(a, b, i+1);
} }
return resp; return resp;
} }
public static int multiplicacaoInt(int a, int b){ public static int multiplicacaoInt(int a, int b){
int resp = 0; int resp = 0;
for(int i = 0; i < b; i++){ for(int i = 0; i < b; i++){
resp = a + resp; resp = a + resp;
} }
return resp; return resp;
} }
public static void main (String[] args){ public static void main (String[] args){
int mult = multiplicacaoInt(4, 3); int mult = multiplicacaoInt(4, 3);
System.out.println("RESPOSTA INT: " + mult); System.out.println("RESPOSTA INT: " + mult);
mult = multiplicacao(4, 3); mult = multiplicacao(4, 3);
System.out.println("RESPOSTA REC: " + mult); System.out.println("RESPOSTA REC: " + mult);
} }
} }

View File

@ -1,18 +1,18 @@
/** /**
* Recursividade * Recursividade
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
class PrintRecursivo{ class PrintRecursivo{
public static void printRecursivo(int i){ public static void printRecursivo(int i){
System.out.println("valor de i: " + i); System.out.println("valor de i: " + i);
if(i > 0){ if(i > 0){
printRecursivo(i-1); printRecursivo(i-1);
} }
System.out.println("valor de i: " + i); System.out.println("valor de i: " + i);
} }
public static void main(String[] args){ public static void main(String[] args){
int n = Integer.parseInt(args[0]); int n = Integer.parseInt(args[0]);
printRecursivo(n); printRecursivo(n);
} }
} }

View File

@ -1,12 +1,12 @@
/** /**
* Tratamento de excecao * Tratamento de excecao
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
public class TratamentoExcecao01 { public class TratamentoExcecao01 {
public static void main(String[] args) { public static void main(String[] args) {
Integer i = new Integer(args[0]); Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i); MyIO.println("A variavel i vale " + i);
MyIO.println("FIM DE PROGRAMA!!!"); MyIO.println("FIM DE PROGRAMA!!!");
} }
} }

View File

@ -1,19 +1,19 @@
/** /**
* Tratamento de excecao * Tratamento de excecao
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
public class TratamentoExcecao02 { public class TratamentoExcecao02 {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
Integer i = new Integer(args[0]); Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i); MyIO.println("A variavel i vale " + i);
} catch (ArrayIndexOutOfBoundsException e){ } catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro na passagem de parametros!!!"); MyIO.println("Erro na passagem de parametros!!!");
} finally { } finally {
MyIO.println("FIM DE PROGRAMA!!!"); MyIO.println("FIM DE PROGRAMA!!!");
} }
} }
} }

View File

@ -1,22 +1,22 @@
/** /**
* Tratamento de excecao * Tratamento de excecao
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
public class TratamentoExcecao03 { public class TratamentoExcecao03 {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
Integer i = new Integer(args[0]); Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i); MyIO.println("A variavel i vale " + i);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
MyIO.println("Erro de formatacao!!!"); MyIO.println("Erro de formatacao!!!");
} catch (ArrayIndexOutOfBoundsException e){ } catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro na passagem de parametros!!!"); MyIO.println("Erro na passagem de parametros!!!");
} finally { } finally {
MyIO.println("FIM DE PROGRAMA!!!"); MyIO.println("FIM DE PROGRAMA!!!");
} }
} }
} }

View File

@ -1,37 +1,37 @@
/** /**
* Tratamento de excecao * Tratamento de excecao
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
public class TratamentoExcecao04 { public class TratamentoExcecao04 {
public static void metodo1(String s) throws NumberFormatException, ArrayIndexOutOfBoundsException { public static void metodo1(String s) throws NumberFormatException, ArrayIndexOutOfBoundsException {
Integer i = new Integer(s); Integer i = new Integer(s);
MyIO.println("A variavel i vale " + i); MyIO.println("A variavel i vale " + i);
} }
public static void metodo2(String s) throws NumberFormatException { public static void metodo2(String s) throws NumberFormatException {
Integer i = new Integer(s); Integer i = new Integer(s);
MyIO.println("A variavel i vale " + i); MyIO.println("A variavel i vale " + i);
} }
public static void main(String[] args) { public static void main(String[] args) {
try { try {
metodo1(args[0]); metodo1(args[0]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
MyIO.println("Erro!!!"); MyIO.println("Erro!!!");
} catch (ArrayIndexOutOfBoundsException e){ } catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro!!!"); MyIO.println("Erro!!!");
} }
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------"); MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
try { try {
metodo2(args[0]); metodo2(args[0]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
MyIO.println("Erro!!!"); MyIO.println("Erro!!!");
} }
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------"); MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
} }
} }

View File

@ -1,22 +1,22 @@
/** /**
* Tratamento de excecao * Tratamento de excecao
* @author Max do Val Machado * @author Max do Val Machado
* @version 2 01/2015 * @version 2 01/2015
*/ */
public class TratamentoExcecao05 { public class TratamentoExcecao05 {
public static void metodo(int i) throws Exception { public static void metodo(int i) throws Exception {
if(i % 2 == 1){ if(i % 2 == 1){
throw new Exception ("Valor impar"); throw new Exception ("Valor impar");
} }
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
int i = 2; int i = 2;
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------"); MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
metodo(i); metodo(i);
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------"); MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
metodo(++i); metodo(++i);
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------"); MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
} }
} }

View File

@ -1,2 +1,2 @@
# U1 - Introdução # U1 - Introdução
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II

View File

@ -1,19 +1,19 @@
class AND_OR { class AND_OR {
public static boolean m1(){ public static boolean m1(){
System.out.println("m1"); System.out.println("m1");
return true; return true;
} }
public static boolean m2(){ public static boolean m2(){
System.out.println("m2"); System.out.println("m2");
return false; return false;
} }
public static void main (String[] args) { public static void main (String[] args) {
System.out.println("====================="); System.out.println("=====================");
boolean or = m1() || m2(); boolean or = m1() || m2();
System.out.println("OR: " + or); System.out.println("OR: " + or);
System.out.println("====================="); System.out.println("=====================");
boolean and = m2() && m1(); boolean and = m2() && m1();
System.out.println("AND: " + and); System.out.println("AND: " + and);
System.out.println("====================="); System.out.println("=====================");
} }
} }

View File

@ -1,17 +1,17 @@
class Log { class Log {
public static void main (String[] args) { public static void main (String[] args) {
int[] n = {4,5,6,7,8,9,10,11,12,13,14,15,16,17,31,32,33,63,64,65}; int[] n = {4,5,6,7,8,9,10,11,12,13,14,15,16,17,31,32,33,63,64,65};
int cont; int cont;
for(int k = 0; k < n.length; k++){ for(int k = 0; k < n.length; k++){
System.out.print("\n[n = " + n[k] + "] => "); System.out.print("\n[n = " + n[k] + "] => ");
cont = 0; cont = 0;
for(int i = n[k]; i > 0; i /= 2){ for(int i = n[k]; i > 0; i /= 2){
System.out.print(" " + i); System.out.print(" " + i);
cont++; cont++;
} }
System.out.print(" (" + cont + " vezes)"); System.out.print(" (" + cont + " vezes)");
} }
System.out.print("\n"); System.out.print("\n");
} }
} }

View File

@ -1,61 +1,61 @@
class Pesquisa { class Pesquisa {
public static boolean pesqSeq(int[] vet, int x){ public static boolean pesqSeq(int[] vet, int x){
boolean resp = false; boolean resp = false;
int n = vet.length; int n = vet.length;
for(int i = 0; i < n; i++){ for(int i = 0; i < n; i++){
if(vet[i] == x){ if(vet[i] == x){
resp = true; resp = true;
i = n; i = n;
} }
} }
return resp; return resp;
} }
public static boolean pesqBin(int[] vet, int x){ public static boolean pesqBin(int[] vet, int x){
boolean resp = false; boolean resp = false;
int dir = (vet.length - 1), esq = 0, meio; int dir = (vet.length - 1), esq = 0, meio;
while (esq <= dir){ while (esq <= dir){
meio = (esq + dir) / 2; meio = (esq + dir) / 2;
if(x == vet[meio]){ if(x == vet[meio]){
resp = true; resp = true;
esq = dir + 1; esq = dir + 1;
} else if (x > vet[meio]) { } else if (x > vet[meio]) {
esq = meio + 1; esq = meio + 1;
} else { } else {
dir = meio - 1; dir = meio - 1;
} }
} }
return resp; return resp;
} }
public static boolean pesqBinRec(int[] vet, int x){ public static boolean pesqBinRec(int[] vet, int x){
return pesqBinRec(vet, x, 0, (vet.length - 1)); return pesqBinRec(vet, x, 0, (vet.length - 1));
} }
public static boolean pesqBinRec(int[] vet, int x, int esq, int dir){ public static boolean pesqBinRec(int[] vet, int x, int esq, int dir){
boolean resp; boolean resp;
int meio = (esq + dir) / 2; int meio = (esq + dir) / 2;
if(esq > dir) { if(esq > dir) {
resp = false; resp = false;
} else if(x == vet[meio]){ } else if(x == vet[meio]){
resp = true; resp = true;
} else if (x > vet[meio]) { } else if (x > vet[meio]) {
resp = pesqBinRec(vet, x, meio + 1, dir); resp = pesqBinRec(vet, x, meio + 1, dir);
} else { } else {
resp = pesqBinRec(vet, x, esq, meio - 1); resp = pesqBinRec(vet, x, esq, meio - 1);
} }
return resp; return resp;
} }
public static void main (String[] args){ public static void main (String[] args){
int[] vet = {2, 3, 5, 7, 9, 11, 15, 17, 20, 21, 30, 43, 49, 70, 71, 82}; int[] vet = {2, 3, 5, 7, 9, 11, 15, 17, 20, 21, 30, 43, 49, 70, 71, 82};
int x = 35; int x = 35;
System.out.println("Pesquisa Sequencial: " + pesqSeq(vet, x)); System.out.println("Pesquisa Sequencial: " + pesqSeq(vet, x));
System.out.println("Pesquisa Binária: " + pesqBin(vet, x)); System.out.println("Pesquisa Binária: " + pesqBin(vet, x));
System.out.println("Pesquisa Binária Recursiva: " + pesqBinRec(vet, x)); System.out.println("Pesquisa Binária Recursiva: " + pesqBinRec(vet, x));
} }
} }

View File

@ -1,2 +1,2 @@
# U2 - Somatórios # U2 - Somatórios
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II

View File

@ -1,2 +1,2 @@
# U3 - Fundamentos de análise de algoritmos # U3 - Fundamentos de análise de algoritmos
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II

View File

@ -1,14 +1,14 @@
# U4 - Ordenação em memória principal # U4 - Ordenação em memória principal
## Exemplo de como compilar o código ## Exemplo de como compilar o código
``` ```
gcc -I. bolha_teste.c -o bolha_teste gcc -I. bolha_teste.c -o bolha_teste
``` ```
## Exemplo de como executar o código ## Exemplo de como executar o código
``` ```
.\bolha_teste.exe 10 .\bolha_teste.exe 10
``` ```

View File

@ -1,14 +1,14 @@
#include "geracao.h" #include "geracao.h"
#include "bolha.h" #include "bolha.h"
//============================================================================= //=============================================================================
void bolha(int *array, int n){ void bolha(int *array, int n){
int i, j; int i, j;
for (i = (n - 1); i > 0; i--) { for (i = (n - 1); i > 0; i--) {
for (j = 0; j < i; j++) { for (j = 0; j < i; j++) {
if (array[j] > array[j + 1]) { if (array[j] > array[j + 1]) {
swap(&array[j], &array[j + 1]); swap(&array[j], &array[j + 1]);
} }
} }
} }
} }
//============================================================================= //=============================================================================

View File

@ -1,6 +1,6 @@
#ifndef BOLHA_H #ifndef BOLHA_H
#define BOLHA_H #define BOLHA_H
//============================================================================= //=============================================================================
void bolha(int *array, int n); void bolha(int *array, int n);
//============================================================================= //=============================================================================
#endif #endif

View File

@ -1,36 +1,36 @@
#include "geracao.h" #include "geracao.h"
#include "countingsort.h" #include "countingsort.h"
//============================================================================= //=============================================================================
int getMaior(int *array, int n) { int getMaior(int *array, int n) {
int maior = array[0]; int maior = array[0];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
if(maior < array[i]){ if(maior < array[i]){
maior = array[i]; maior = array[i];
} }
} }
return maior; return maior;
} }
//============================================================================= //=============================================================================
void countingsort(int *array, int n) { void countingsort(int *array, int n) {
//Array para contar o numero de ocorrencias de cada elemento //Array para contar o numero de ocorrencias de cada elemento
int tamCount = getMaior(array, n) + 1; int tamCount = getMaior(array, n) + 1;
int count[tamCount]; int count[tamCount];
int ordenado[n]; int ordenado[n];
//Inicializar cada posicao do array de contagem //Inicializar cada posicao do array de contagem
for (int i = 0; i < tamCount; count[i] = 0, i++); for (int i = 0; i < tamCount; count[i] = 0, i++);
//Agora, o count[i] contem o numero de elemento iguais a i //Agora, o count[i] contem o numero de elemento iguais a i
for (int i = 0; i < n; count[array[i]]++, i++); for (int i = 0; i < n; count[array[i]]++, i++);
//Agora, o count[i] contem o numero de elemento menores ou iguais a i //Agora, o count[i] contem o numero de elemento menores ou iguais a i
for(int i = 1; i < tamCount; count[i] += count[i-1], i++); for(int i = 1; i < tamCount; count[i] += count[i-1], i++);
//Ordenando //Ordenando
for(int i = n-1; i >= 0; ordenado[count[array[i]]-1] = array[i], count[array[i]]--, i--); for(int i = n-1; i >= 0; ordenado[count[array[i]]-1] = array[i], count[array[i]]--, i--);
//Copiando para o array original //Copiando para o array original
for(int i = 0; i < n; array[i] = ordenado[i], i++); for(int i = 0; i < n; array[i] = ordenado[i], i++);
} }
//============================================================================= //=============================================================================

View File

@ -1,8 +1,8 @@
#ifndef COUNTINGSORT_H #ifndef COUNTINGSORT_H
#define COUNTINGSORT_H #define COUNTINGSORT_H
//============================================================================= //=============================================================================
int getMaior(int *array, int n); int getMaior(int *array, int n);
//============================================================================= //=============================================================================
void countingsort(int *array, int n); void countingsort(int *array, int n);
//============================================================================= //=============================================================================
#endif #endif

View File

@ -1,70 +1,70 @@
#include "geracao.h" #include "geracao.h"
//============================================================================= //=============================================================================
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
#include <time.h> #include <time.h>
#include <stdlib.h> #include <stdlib.h>
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA TROCAR DOIS ELEMENTOS DO VETOR // PROCEDIMENTO PARA TROCAR DOIS ELEMENTOS DO VETOR
void swap(int *i, int *j) { void swap(int *i, int *j) {
int temp = *i; int temp = *i;
*i = *j; *i = *j;
*j = temp; *j = temp;
} }
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM CRESCENTE // PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM CRESCENTE
void crescente(int *array, int n) { void crescente(int *array, int n) {
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
array[i] = i; array[i] = i;
} }
} }
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM DECRESCENTE // PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM DECRESCENTE
void decrescente(int *array, int n) { void decrescente(int *array, int n) {
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
array[i] = n - 1 - i; array[i] = n - 1 - i;
} }
} }
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM ALEATORIA // PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM ALEATORIA
void aleatorio(int *array, int n) { void aleatorio(int *array, int n) {
crescente(array, n); crescente(array, n);
srand(time(NULL)); srand(time(NULL));
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
swap(&array[i], &array[rand() % n]); swap(&array[i], &array[rand() % n]);
} }
} }
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS DA ENTRADA PADRAO // PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS DA ENTRADA PADRAO
int entradaPadrao(int *array) { int entradaPadrao(int *array) {
int n; int n;
scanf("%i", &n); scanf("%i", &n);
array = (int*) malloc(n*sizeof(int)); array = (int*) malloc(n*sizeof(int));
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
scanf("%i", &array[i]); scanf("%i", &array[i]);
} }
return n; return n;
} }
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA EXIBIR OS DADOS PRESENTES NO ARRANJO // PROCEDIMENTO PARA EXIBIR OS DADOS PRESENTES NO ARRANJO
void mostrar(int *array, int n) { void mostrar(int *array, int n) {
printf("[ "); printf("[ ");
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
printf("%d ", array[i]); printf("%d ", array[i]);
} }
printf("] \n"); printf("] \n");
} }
//============================================================================= //=============================================================================
// PROCEDIMENTO PARA VERIFICAR SE O ARRANJO ESTA ORDENADO // PROCEDIMENTO PARA VERIFICAR SE O ARRANJO ESTA ORDENADO
bool isOrdenado(int *array, int n){ bool isOrdenado(int *array, int n){
bool resp = true; bool resp = true;
for(int i = 1; i < n; i++){ for(int i = 1; i < n; i++){
if(array[i-1] > array[i]){ if(array[i-1] > array[i]){
i = n; i = n;
resp = false; resp = false;
} }
} }
return resp; return resp;
} }
//============================================================================= //=============================================================================

View File

@ -1,18 +1,18 @@
#ifndef GERACAO_H #ifndef GERACAO_H
#define GERACAO_H #define GERACAO_H
//============================================================================= //=============================================================================
#include <stdbool.h> #include <stdbool.h>
//============================================================================= //=============================================================================
void swap(int *i, int *j); void swap(int *i, int *j);
//============================================================================= //=============================================================================
void crescente(int *array, int n); void crescente(int *array, int n);
//============================================================================= //=============================================================================
void decrescente(int *array, int n); void decrescente(int *array, int n);
//============================================================================= //=============================================================================
void aleatorio(int *array, int n); void aleatorio(int *array, int n);
//============================================================================= //=============================================================================
void mostrar(int *array, int n); void mostrar(int *array, int n);
//============================================================================= //=============================================================================
bool isOrdenado(int *array, int n); bool isOrdenado(int *array, int n);
//============================================================================= //=============================================================================
#endif #endif

View File

@ -1,56 +1,56 @@
#include "heapsort.h" #include "heapsort.h"
//============================================================================= //=============================================================================
void construir(int *array, int tamHeap){ void construir(int *array, int tamHeap){
for(int i = tamHeap; i > 1 && array[i] > array[i/2]; i /= 2){ for(int i = tamHeap; i > 1 && array[i] > array[i/2]; i /= 2){
swap(array + i, array + i/2); swap(array + i, array + i/2);
} }
} }
//============================================================================= //=============================================================================
int getMaiorFilho(int *array, int i, int tamHeap){ int getMaiorFilho(int *array, int i, int tamHeap){
int filho; int filho;
if (2*i == tamHeap || array[2*i] > array[2*i+1]){ if (2*i == tamHeap || array[2*i] > array[2*i+1]){
filho = 2*i; filho = 2*i;
} else { } else {
filho = 2*i + 1; filho = 2*i + 1;
} }
return filho; return filho;
} }
//============================================================================= //=============================================================================
void reconstruir(int *array, int tamHeap){ void reconstruir(int *array, int tamHeap){
int i = 1; int i = 1;
while(i <= (tamHeap/2)){ while(i <= (tamHeap/2)){
int filho = getMaiorFilho(array, i, tamHeap); int filho = getMaiorFilho(array, i, tamHeap);
if(array[i] < array[filho]){ if(array[i] < array[filho]){
swap(array + i, array + filho); swap(array + i, array + filho);
i = filho; i = filho;
}else{ }else{
i = tamHeap; i = tamHeap;
} }
} }
} }
//============================================================================= //=============================================================================
void heapsort(int *array, int n) { void heapsort(int *array, int n) {
//Alterar o vetor ignorando a posicao zero //Alterar o vetor ignorando a posicao zero
int arrayTmp[n+1]; int arrayTmp[n+1];
for(int i = 0; i < n; i++){ for(int i = 0; i < n; i++){
arrayTmp[i+1] = array[i]; arrayTmp[i+1] = array[i];
} }
//Contrucao do heap //Contrucao do heap
for(int tamHeap = 2; tamHeap <= n; tamHeap++){ for(int tamHeap = 2; tamHeap <= n; tamHeap++){
construir(arrayTmp, tamHeap); construir(arrayTmp, tamHeap);
} }
//Ordenacao propriamente dita //Ordenacao propriamente dita
int tamHeap = n; int tamHeap = n;
while(tamHeap > 1){ while(tamHeap > 1){
swap(arrayTmp + 1, arrayTmp + tamHeap--); swap(arrayTmp + 1, arrayTmp + tamHeap--);
reconstruir(arrayTmp, tamHeap); reconstruir(arrayTmp, tamHeap);
} }
//Alterar o vetor para voltar a posicao zero //Alterar o vetor para voltar a posicao zero
for(int i = 0; i < n; i++){ for(int i = 0; i < n; i++){
array[i] = arrayTmp[i+1]; array[i] = arrayTmp[i+1];
} }
} }
//============================================================================= //=============================================================================

View File

@ -1,14 +1,14 @@
#ifndef HEAPSORT_H #ifndef HEAPSORT_H
#define HEAPSORT_H #define HEAPSORT_H
//============================================================================= //=============================================================================
#include "geracao.h" #include "geracao.h"
//============================================================================= //=============================================================================
void construir(int *array, int tamHeap); void construir(int *array, int tamHeap);
//============================================================================= //=============================================================================
int getMaiorFilho(int *array, int i, int tamHeap); int getMaiorFilho(int *array, int i, int tamHeap);
//============================================================================= //=============================================================================
void reconstruir(int *array, int tamHeap); void reconstruir(int *array, int tamHeap);
//============================================================================= //=============================================================================
void heapsort(int *array, int n); void heapsort(int *array, int n);
//============================================================================= //=============================================================================
#endif #endif

View File

@ -1,15 +1,15 @@
#include "insercao.h" #include "insercao.h"
//============================================================================= //=============================================================================
void insercao(int *array, int n){ void insercao(int *array, int n){
for (int i = 1; i < n; i++) { for (int i = 1; i < n; i++) {
int tmp = array[i]; int tmp = array[i];
int j = i - 1; int j = i - 1;
while ((j >= 0) && (array[j] > tmp)) { while ((j >= 0) && (array[j] > tmp)) {
array[j + 1] = array[j]; array[j + 1] = array[j];
j--; j--;
} }
array[j+1] = tmp; array[j+1] = tmp;
} }
} }
//============================================================================= //=============================================================================

View File

@ -1,8 +1,8 @@
#ifndef INSERCAO_H #ifndef INSERCAO_H
#define INSERCAO_H #define INSERCAO_H
//============================================================================= //=============================================================================
#include "geracao.h" #include "geracao.h"
//============================================================================= //=============================================================================
void insercao(int *array, int n); void insercao(int *array, int n);
//============================================================================= //=============================================================================
#endif #endif

Some files were not shown because too many files have changed in this diff Show More